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.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.WindowsRuntime.Internal; using System.Runtime; using System.Security; using System.Threading; namespace System.IO { [Flags] internal enum FileAccess { // Specifies read access to the file. Data can be read from the file and // the file pointer can be moved. Combine with WRITE for read-write access. Read = 1, // Specifies write access to the file. Data can be written to the file and // the file pointer can be moved. Combine with READ for read-write access. Write = 2, // Specifies read and write access to the file. Data can be written to the // file and the file pointer can be moved. Data can also be read from the // file. ReadWrite = 3, } /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. */ internal class UnmanagedMemoryStream : Stream { // BUGBUG: Consider removing this restriction, or making in // Int64.MaxValue and ensuring we never wrap around to positive. private const long UnmanagedMemStreamMaxLength = Int64.MaxValue; private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private FileAccess _access; internal bool _isOpen; // Needed for subclasses that need to map a file, etc. protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { Initialize(pointer, length, capacity, access, skipSecurityCheck); } protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException("pointer"); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_LengthGreaterThanCapacity); Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (_isOpen) throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); _mem = pointer; _length = length; _capacity = capacity; _access = access; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } public override void Flush() { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } public override long Length { get { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); return Interlocked.Read(ref _length); } } public long Capacity { get { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); return _capacity; } } public override long Position { get { if (!CanSeek) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (!CanSeek) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); #if WIN32 unsafe { // On 32 bit machines, ensure we don't wrap around. if (value > (long)Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_StreamLength); } #endif Interlocked.Exchange(ref _position, value); } } public unsafe byte* PositionPointer { get { // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition); byte* ptr = _mem + pos; if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); return ptr; } set { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); // Note: subtracting pointers returns an Int64. Working around // to avoid hitting compiler warning CS0652 on this line. if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, value - _mem); } } internal unsafe byte* Pointer { get { return _mem; } } [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) nInt = 0; // _position could be beyond EOF Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { Marshal.Copy((IntPtr)(_mem + pos), buffer, offset, nInt); } Interlocked.Exchange(ref _position, pos + n); return nInt; } [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; unsafe { result = _mem[pos]; } return result; } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (offset > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); switch (loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } long finalPos = Interlocked.Read(ref _position); Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { Helpers.ZeroMemory(_mem + len, value - len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) { throw new NotSupportedException(SR.IO_FixedCapacity); } // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Helpers.ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } unsafe { Marshal.Copy(buffer, offset, (IntPtr)(_mem + pos), count); } Interlocked.Exchange(ref _position, n); return; } [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) throw new NotSupportedException(SR.IO_FixedCapacity); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Helpers.ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } unsafe { _mem[pos] = value; } Interlocked.Exchange(ref _position, n); } } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.IO; using Aga.Controls.Tree.NodeControls; using Aga.Controls.Tree; using System.Collections; using System.Threading; namespace IronScheme.Editor.Controls { partial class FileExplorer : UserControl { public FileExplorer() { InitializeComponent(); _name.ToolTipProvider = new ToolTipProvider(); _name.EditorShowing += new CancelEventHandler(_name_EditorShowing); _treeView.Model = new SortedTreeModel(new FolderBrowserModel()); } private class ToolTipProvider: IToolTipProvider { public string GetToolTip(TreeNodeAdv node, NodeControl nodeControl) { if (node.Tag is RootItem) return null; else return "Second click to rename node"; } } void _name_EditorShowing(object sender, CancelEventArgs e) { if (_treeView.CurrentNode.Tag is RootItem) e.Cancel = true; } private void _treeView_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { NodeControlInfo info = _treeView.GetNodeControlInfoAt(e.Location); if (info.Control != null) { Console.WriteLine(info.Bounds); } } } private void _treeView_ColumnClicked(object sender, TreeColumnEventArgs e) { TreeColumn clicked = e.Column; if (clicked.SortOrder == SortOrder.Ascending) clicked.SortOrder = SortOrder.Descending; else clicked.SortOrder = SortOrder.Ascending; (_treeView.Model as SortedTreeModel).Comparer = new FolderItemSorter(clicked.Header, clicked.SortOrder); } } abstract class BaseItem { private string _path = ""; public string ItemPath { get { return _path; } set { _path = value; } } private Image _icon; public Image Icon { get { return _icon; } set { _icon = value; } } private long _size = 0; public long Size { get { return _size; } set { _size = value; } } private DateTime? _date; public DateTime? Date { get { return _date; } set { _date = value; } } public abstract string Name { get; set; } private BaseItem _parent; public BaseItem Parent { get { return _parent; } set { _parent = value; } } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { _isChecked = value; if (Owner != null) Owner.OnNodesChanged(this); } } private FolderBrowserModel _owner; public FolderBrowserModel Owner { get { return _owner; } set { _owner = value; } } /*public override bool Equals(object obj) { if (obj is BaseItem) return _path.Equals((obj as BaseItem).ItemPath); else return base.Equals(obj); } public override int GetHashCode() { return _path.GetHashCode(); }*/ public override string ToString() { return _path; } } class RootItem : BaseItem { public RootItem(string name, FolderBrowserModel owner) { ItemPath = name; Owner = owner; } public override string Name { get { return ItemPath; } set { } } } class FolderItem : BaseItem { public override string Name { get { return Path.GetFileName(ItemPath); } set { string dir = Path.GetDirectoryName(ItemPath); string destination = Path.Combine(dir, value); Directory.Move(ItemPath, destination); ItemPath = destination; } } public FolderItem(string name, BaseItem parent, FolderBrowserModel owner) { ItemPath = name; Parent = parent; Owner = owner; } } class FileItem : BaseItem { public override string Name { get { return Path.GetFileName(ItemPath); } set { string dir = Path.GetDirectoryName(ItemPath); string destination = Path.Combine(dir, value); File.Move(ItemPath, destination); ItemPath = destination; } } public FileItem(string name, BaseItem parent, FolderBrowserModel owner) { ItemPath = name; Parent = parent; Owner = owner; } } class FolderBrowserModel : ITreeModel { private BackgroundWorker _worker; private List<BaseItem> _itemsToRead; private Dictionary<string, List<BaseItem>> _cache = new Dictionary<string, List<BaseItem>>(); public FolderBrowserModel() { _itemsToRead = new List<BaseItem>(); _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.DoWork += new DoWorkEventHandler(ReadFilesProperties); _worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged); } static Dictionary<string, Image> icocache = new Dictionary<string, Image>(); void ReadFilesProperties(object sender, DoWorkEventArgs e) { while (_itemsToRead.Count > 0) { BaseItem item = _itemsToRead[0]; _itemsToRead.RemoveAt(0); if (item is FolderItem) { DirectoryInfo info = new DirectoryInfo(item.ItemPath); item.Date = info.CreationTime; } else if (item is FileItem) { FileInfo info = new FileInfo(item.ItemPath); item.Size = info.Length; item.Date = info.CreationTime; //string ext = Path.GetExtension(item.ItemPath); //if (icocache.ContainsKey(ext)) //{ // item.Icon = icocache[ext]; //} //else //{ // Icon ico = Icon.ExtractAssociatedIcon(item.ItemPath); // Image b = ico.ToBitmap(); // b = b.GetThumbnailImage(16, 16, null, IntPtr.Zero); // item.Icon = icocache[ext] = b; //} } _worker.ReportProgress(0, item); } } void ProgressChanged(object sender, ProgressChangedEventArgs e) { OnNodesChanged(e.UserState as BaseItem); } private TreePath GetPath(BaseItem item) { if (item == null) return TreePath.Empty; else { Stack<object> stack = new Stack<object>(); while (item != null) { stack.Push(item); item = item.Parent; } return new TreePath(stack.ToArray()); } } public System.Collections.IEnumerable GetChildren(TreePath treePath) { List<BaseItem> items = null; if (treePath.IsEmpty()) { if (_cache.ContainsKey("ROOT")) items = _cache["ROOT"]; else { items = new List<BaseItem>(); _cache.Add("ROOT", items); foreach (string str in Environment.GetLogicalDrives()) { DriveInfo di = new DriveInfo(str); if (di.DriveType == DriveType.Unknown || di.DriveType == DriveType.Network) { } else if (!di.IsReady) { } else { RootItem ri = new RootItem(str, this); items.Add(ri); } } } } else { BaseItem parent = treePath.LastNode as BaseItem; if (parent != null) { if (_cache.ContainsKey(parent.ItemPath)) items = _cache[parent.ItemPath]; else { items = new List<BaseItem>(); try { foreach (string str in Directory.GetDirectories(parent.ItemPath)) { FileAttributes fa = File.GetAttributes(str); if ((fa & FileAttributes.Hidden) == 0 && 0 == (FileAttributes.System & fa)) { items.Add(new FolderItem(str, parent, this)); } } foreach (string str in Directory.GetFiles(parent.ItemPath)) { FileAttributes fa = File.GetAttributes(str); if ((fa & FileAttributes.Hidden) == 0 && 0 == (FileAttributes.System & fa)) { items.Add(new FileItem(str, parent, this)); } } } catch (IOException) { return null; } _cache.Add(parent.ItemPath, items); _itemsToRead.AddRange(items); if (!_worker.IsBusy) _worker.RunWorkerAsync(); } } } return items; } public bool IsLeaf(TreePath treePath) { return treePath.LastNode is FileItem; } public event EventHandler<TreeModelEventArgs> NodesChanged; internal void OnNodesChanged(BaseItem item) { if (NodesChanged != null) { TreePath path = GetPath(item.Parent); NodesChanged(this, new TreeModelEventArgs(path, new object[] { item })); } } public event EventHandler<TreeModelEventArgs> NodesInserted; public event EventHandler<TreeModelEventArgs> NodesRemoved; public event EventHandler<TreePathEventArgs> StructureChanged; public void OnStructureChanged() { if (StructureChanged != null) StructureChanged(this, new TreePathEventArgs()); } } class FolderItemSorter : IComparer { private string _mode; private SortOrder _order; public FolderItemSorter(string mode, SortOrder order) { _mode = mode; _order = order; } public int Compare(object x, object y) { BaseItem a = x as BaseItem; BaseItem b = y as BaseItem; int res = 0; if (a is FolderItem && b is FileItem) { return -1; } else if (b is FolderItem && a is FileItem) { return 1; } else { if (a is FileItem && b is FileItem) { if (_mode == "Date") res = DateTime.Compare(a.Date.Value, b.Date.Value); else if (_mode == "Size") { if (a.Size < b.Size) res = -1; else if (a.Size > b.Size) res = 1; } else res = string.Compare(a.Name, b.Name); } else { res = string.Compare(a.Name, b.Name); } } if (a is FileItem && b is FileItem) { if (_order == SortOrder.Ascending) return -res; else return res; } else { return res; } } private string GetData(object x) { return (x as BaseItem).Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Invio.Xunit; using Xunit; namespace Invio.Extensions.Reflection { [UnitTest] public sealed class CachedDelegatesMethodInfoExtensionsTests { public static IEnumerable<object[]> CachedDelegateCases { get { return new List<object[]> { new object[] { nameof(Fake.Func0), TypedTestCases<Fake>.Func0 }, new object[] { nameof(Fake.Func0), TestCases<Fake>.Func0 }, new object[] { nameof(Fake.Func1), TypedTestCases<Fake>.Func1 }, new object[] { nameof(Fake.Func1), TestCases<Fake>.Func1 }, new object[] { nameof(Fake.Func2), TypedTestCases<Fake>.Func2 }, new object[] { nameof(Fake.Func2), TestCases<Fake>.Func2 }, new object[] { nameof(Fake.Func3), TypedTestCases<Fake>.Func3 }, new object[] { nameof(Fake.Func3), TestCases<Fake>.Func3 }, new object[] { nameof(Fake.Func4), TypedTestCases<Fake>.Func4 }, new object[] { nameof(Fake.Func4), TestCases<Fake>.Func4 }, new object[] { nameof(Fake.Func5), TypedTestCases<Fake>.Func5 }, new object[] { nameof(Fake.Func5), TestCases<Fake>.Func5 }, new object[] { nameof(Fake.Func6), TypedTestCases<Fake>.Func6 }, new object[] { nameof(Fake.Func6), TestCases<Fake>.Func6 }, new object[] { nameof(Fake.Func7), TypedTestCases<Fake>.Func7 }, new object[] { nameof(Fake.Func7), TestCases<Fake>.Func7 }, new object[] { nameof(Fake.Func8), TypedTestCases<Fake>.Func8 }, new object[] { nameof(Fake.Func8), TestCases<Fake>.Func8 }, new object[] { nameof(Fake.Func9), TypedTestCases<Fake>.Func9 }, new object[] { nameof(Fake.Func9), TestCases<Fake>.Func9 }, new object[] { nameof(Fake.Action0), TypedTestCases<Fake>.Action0 }, new object[] { nameof(Fake.Action0), TestCases<Fake>.Action0 }, new object[] { nameof(Fake.Action1), TypedTestCases<Fake>.Action1 }, new object[] { nameof(Fake.Action1), TestCases<Fake>.Action1 }, new object[] { nameof(Fake.Action2), TypedTestCases<Fake>.Action2 }, new object[] { nameof(Fake.Action2), TestCases<Fake>.Action2 }, new object[] { nameof(Fake.Action3), TypedTestCases<Fake>.Action3 }, new object[] { nameof(Fake.Action3), TestCases<Fake>.Action3 }, new object[] { nameof(Fake.Action4), TypedTestCases<Fake>.Action4 }, new object[] { nameof(Fake.Action4), TestCases<Fake>.Action4 }, new object[] { nameof(Fake.Action5), TypedTestCases<Fake>.Action5 }, new object[] { nameof(Fake.Action5), TestCases<Fake>.Action5 }, new object[] { nameof(Fake.Action6), TypedTestCases<Fake>.Action6 }, new object[] { nameof(Fake.Action6), TestCases<Fake>.Action6 }, new object[] { nameof(Fake.Action7), TypedTestCases<Fake>.Action7 }, new object[] { nameof(Fake.Action7), TestCases<Fake>.Action7 }, new object[] { nameof(Fake.Action8), TypedTestCases<Fake>.Action8 }, new object[] { nameof(Fake.Action8), TestCases<Fake>.Action8 }, new object[] { nameof(Fake.Action9), TypedTestCases<Fake>.Action9 }, new object[] { nameof(Fake.Action9), TestCases<Fake>.Action9 } }; } } [Theory] [MemberData(nameof(CachedDelegateCases))] public void CreateDelegate_CachedInstances<TFunc>( String methodName, ITestCase<Fake, TFunc> testCase) { // Arrange var method = typeof(Fake).GetMethod(methodName); // Act var left = testCase.CreateDelegate(method); var right = testCase.CreateDelegate(method); // Assert Assert.True( Object.ReferenceEquals(left, right), "Expect the same instance to be returned from the cache." ); } public static IEnumerable<object[]> ActionWithReturnTypeCases { get { return new List<object[]> { new object[] { nameof(Fake.Func0), TypedTestCases<Fake>.Action0 }, new object[] { nameof(Fake.Func0), TestCases<Fake>.Action0 }, new object[] { nameof(Fake.Func1), TypedTestCases<Fake>.Action1 }, new object[] { nameof(Fake.Func1), TestCases<Fake>.Action1 }, new object[] { nameof(Fake.Func2), TypedTestCases<Fake>.Action2 }, new object[] { nameof(Fake.Func2), TestCases<Fake>.Action2 }, new object[] { nameof(Fake.Func3), TypedTestCases<Fake>.Action3 }, new object[] { nameof(Fake.Func3), TestCases<Fake>.Action3 }, new object[] { nameof(Fake.Func4), TypedTestCases<Fake>.Action4 }, new object[] { nameof(Fake.Func4), TestCases<Fake>.Action4 }, new object[] { nameof(Fake.Func5), TypedTestCases<Fake>.Action5 }, new object[] { nameof(Fake.Func5), TestCases<Fake>.Action5 }, new object[] { nameof(Fake.Func6), TypedTestCases<Fake>.Action6 }, new object[] { nameof(Fake.Func6), TestCases<Fake>.Action6 }, new object[] { nameof(Fake.Func7), TypedTestCases<Fake>.Action7 }, new object[] { nameof(Fake.Func7), TestCases<Fake>.Action7 }, new object[] { nameof(Fake.Func8), TypedTestCases<Fake>.Action8 }, new object[] { nameof(Fake.Func8), TestCases<Fake>.Action8 }, new object[] { nameof(Fake.Func9), TypedTestCases<Fake>.Action9 }, new object[] { nameof(Fake.Func9), TestCases<Fake>.Action9 } }; } } [Theory] [MemberData(nameof(ActionWithReturnTypeCases))] public void CreateAction_OnMethodInfoWithReturnValue<TFunc>( String methodName, ITestCase<Fake, TFunc> testCase) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var exception = Record.Exception( () => testCase.CreateDelegate(method) ); // Assert Assert.Equal( "You cannot create an Action delegate for a method with a " + "non-void return type." + Environment.NewLine + "Parameter name: method", exception.Message ); } public static IEnumerable<object[]> FuncWithoutReturnTypeCases { get { return new List<object[]> { new object[] { nameof(Fake.Action0), TypedTestCases<Fake>.Func0 }, new object[] { nameof(Fake.Action0), TestCases<Fake>.Func0 }, new object[] { nameof(Fake.Action1), TypedTestCases<Fake>.Func1 }, new object[] { nameof(Fake.Action1), TestCases<Fake>.Func1 }, new object[] { nameof(Fake.Action2), TypedTestCases<Fake>.Func2 }, new object[] { nameof(Fake.Action2), TestCases<Fake>.Func2 }, new object[] { nameof(Fake.Action3), TypedTestCases<Fake>.Func3 }, new object[] { nameof(Fake.Action3), TestCases<Fake>.Func3 }, new object[] { nameof(Fake.Action4), TypedTestCases<Fake>.Func4 }, new object[] { nameof(Fake.Action4), TestCases<Fake>.Func4 }, new object[] { nameof(Fake.Action5), TypedTestCases<Fake>.Func5 }, new object[] { nameof(Fake.Action5), TestCases<Fake>.Func5 }, new object[] { nameof(Fake.Action6), TypedTestCases<Fake>.Func6 }, new object[] { nameof(Fake.Action6), TestCases<Fake>.Func6 }, new object[] { nameof(Fake.Action7), TypedTestCases<Fake>.Func7 }, new object[] { nameof(Fake.Action7), TestCases<Fake>.Func7 }, new object[] { nameof(Fake.Action8), TypedTestCases<Fake>.Func8 }, new object[] { nameof(Fake.Action8), TestCases<Fake>.Func8 }, new object[] { nameof(Fake.Action9), TypedTestCases<Fake>.Func9 }, new object[] { nameof(Fake.Action9), TestCases<Fake>.Func9 } }; } } [Theory] [MemberData(nameof(FuncWithoutReturnTypeCases))] public void CreateFunc_OnVoidMethodInfo<TFunc>( String methodName, ITestCase<Fake, TFunc> testCase) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var exception = Record.Exception( () => testCase.CreateDelegate(method) ); // Assert Assert.Equal( "You cannot create a Func delegate for a method with a " + "void return type." + Environment.NewLine + "Parameter name: method", exception.Message ); } public static IEnumerable<object[]> TooFewArgumentsCases { get { return new List<object[]> { new object[] { nameof(Fake.Func0), TypedTestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func0), TestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func1), TypedTestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func1), TestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func2), TypedTestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func2), TestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func3), TypedTestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func3), TestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func4), TypedTestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func4), TestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func5), TypedTestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func5), TestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func6), TypedTestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func6), TestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func7), TypedTestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func7), TestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func8), TypedTestCases<Fake>.Func9, 9 }, new object[] { nameof(Fake.Func8), TestCases<Fake>.Func9, 9}, new object[] { nameof(Fake.Action0), TypedTestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action0), TestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action1), TypedTestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action1), TestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action2), TypedTestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action2), TestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action3), TypedTestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action3), TestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action4), TypedTestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action4), TestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action5), TypedTestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action5), TestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action6), TypedTestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action6), TestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action7), TypedTestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action7), TestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action8), TypedTestCases<Fake>.Action9, 9 }, new object[] { nameof(Fake.Action8), TestCases<Fake>.Action9, 9 } }; } } [Theory] [MemberData(nameof(TooFewArgumentsCases))] public void CreateDelegate_TooFewArguments<TFunc>( String methodName, ITestCase<Fake, TFunc> test, int expectedNumberOfParameters) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var exception = Record.Exception( () => test.CreateDelegate(method) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( "The 'method' argument must reference a " + "MethodInfo with " + expectedNumberOfParameters + " parameters." + Environment.NewLine + "Parameter name: method", exception.Message ); } public static IEnumerable<object[]> TooManyArgumentsCases { get { return new List<object[]> { new object[] { nameof(Fake.Func1), TypedTestCases<Fake>.Func0, 0 }, new object[] { nameof(Fake.Func1), TestCases<Fake>.Func0, 0 }, new object[] { nameof(Fake.Func2), TypedTestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func2), TestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func3), TypedTestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func3), TestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func4), TypedTestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func4), TestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func5), TypedTestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func5), TestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func6), TypedTestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func6), TestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func7), TypedTestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func7), TestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func8), TypedTestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func8), TestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func9), TypedTestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func9), TestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func10), TypedTestCases<Fake>.Func9, 9 }, new object[] { nameof(Fake.Func10), TestCases<Fake>.Func9, 9 }, new object[] { nameof(Fake.Action1), TypedTestCases<Fake>.Action0, 0 }, new object[] { nameof(Fake.Action1), TestCases<Fake>.Action0, 0 }, new object[] { nameof(Fake.Action2), TypedTestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action2), TestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action3), TypedTestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action3), TestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action4), TypedTestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action4), TestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action5), TypedTestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action5), TestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action6), TypedTestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action6), TestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action7), TypedTestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action7), TestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action8), TypedTestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action8), TestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action9), TypedTestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action9), TestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action10), TypedTestCases<Fake>.Action9, 9 }, new object[] { nameof(Fake.Action10), TestCases<Fake>.Action9, 9 } }; } } [Theory] [MemberData(nameof(TooManyArgumentsCases))] public void CreateDelegate_TooManyArguments<TFunc>( String methodName, ITestCase<Fake, TFunc> test, int expectedNumberOfParameters) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var exception = Record.Exception( () => test.CreateDelegate(method) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( "The 'method' argument must reference a " + "MethodInfo with " + expectedNumberOfParameters + " parameters." + Environment.NewLine + "Parameter name: method", exception.Message ); } public static IEnumerable<object[]> InvalidBaseTypeCases { get { return new List<object[]> { new object[] { nameof(IFake.Func0), TypedTestCases<IFake>.Func0 }, new object[] { nameof(IFake.Func1), TypedTestCases<IFake>.Func1 }, new object[] { nameof(IFake.Func2), TypedTestCases<IFake>.Func2 }, new object[] { nameof(IFake.Func3), TypedTestCases<IFake>.Func3 }, new object[] { nameof(IFake.Func4), TypedTestCases<IFake>.Func4 }, new object[] { nameof(IFake.Func5), TypedTestCases<IFake>.Func5 }, new object[] { nameof(IFake.Func6), TypedTestCases<IFake>.Func6 }, new object[] { nameof(IFake.Func7), TypedTestCases<IFake>.Func7 }, new object[] { nameof(IFake.Func8), TypedTestCases<IFake>.Func8 }, new object[] { nameof(IFake.Func9), TypedTestCases<IFake>.Func9 }, new object[] { nameof(IFake.Action0), TypedTestCases<IFake>.Action0 }, new object[] { nameof(IFake.Action1), TypedTestCases<IFake>.Action1 }, new object[] { nameof(IFake.Action2), TypedTestCases<IFake>.Action2 }, new object[] { nameof(IFake.Action3), TypedTestCases<IFake>.Action3 }, new object[] { nameof(IFake.Action4), TypedTestCases<IFake>.Action4 }, new object[] { nameof(IFake.Action5), TypedTestCases<IFake>.Action5 }, new object[] { nameof(IFake.Action6), TypedTestCases<IFake>.Action6 }, new object[] { nameof(IFake.Action7), TypedTestCases<IFake>.Action7 }, new object[] { nameof(IFake.Action8), TypedTestCases<IFake>.Action8 }, new object[] { nameof(IFake.Action9), TypedTestCases<IFake>.Action9 } }; } } [Theory] [MemberData(nameof(InvalidBaseTypeCases))] public void CreateDelegate_InvalidBaseType<TFunc>( String methodName, ITestCase<IFake, TFunc> test) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var exception = Record.Exception( () => test.CreateDelegate(method) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( "Type parameter 'TBase' was 'IFake', which is not " + "assignable to the method's declaring type of 'Fake'." + Environment.NewLine + "Parameter name: method", exception.Message ); } public static IEnumerable<object[]> ValidBaseTypeCases { get { return new List<object[]> { new object[] { nameof(Fake.Func0), TypedTestCases<Fake>.Func0, 0 }, new object[] { nameof(Fake.Func0), TestCases<Fake>.Func0, 0 }, new object[] { nameof(Fake.Func1), TypedTestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func1), TestCases<Fake>.Func1, 1 }, new object[] { nameof(Fake.Func2), TypedTestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func2), TestCases<Fake>.Func2, 2 }, new object[] { nameof(Fake.Func3), TypedTestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func3), TestCases<Fake>.Func3, 3 }, new object[] { nameof(Fake.Func4), TypedTestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func4), TestCases<Fake>.Func4, 4 }, new object[] { nameof(Fake.Func5), TypedTestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func5), TestCases<Fake>.Func5, 5 }, new object[] { nameof(Fake.Func6), TypedTestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func6), TestCases<Fake>.Func6, 6 }, new object[] { nameof(Fake.Func7), TypedTestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func7), TestCases<Fake>.Func7, 7 }, new object[] { nameof(Fake.Func8), TypedTestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func8), TestCases<Fake>.Func8, 8 }, new object[] { nameof(Fake.Func9), TypedTestCases<Fake>.Func9, 9 }, new object[] { nameof(Fake.Func9), TestCases<Fake>.Func9, 9 }, new object[] { nameof(Fake.Action0), TypedTestCases<Fake>.Action0, 0 }, new object[] { nameof(Fake.Action0), TestCases<Fake>.Action0, 0 }, new object[] { nameof(Fake.Action1), TypedTestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action1), TestCases<Fake>.Action1, 1 }, new object[] { nameof(Fake.Action2), TypedTestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action2), TestCases<Fake>.Action2, 2 }, new object[] { nameof(Fake.Action3), TypedTestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action3), TestCases<Fake>.Action3, 3 }, new object[] { nameof(Fake.Action4), TypedTestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action4), TestCases<Fake>.Action4, 4 }, new object[] { nameof(Fake.Action5), TypedTestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action5), TestCases<Fake>.Action5, 5 }, new object[] { nameof(Fake.Action6), TypedTestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action6), TestCases<Fake>.Action6, 6 }, new object[] { nameof(Fake.Action7), TypedTestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action7), TestCases<Fake>.Action7, 7 }, new object[] { nameof(Fake.Action8), TypedTestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action8), TestCases<Fake>.Action8, 8 }, new object[] { nameof(Fake.Action9), TypedTestCases<Fake>.Action9, 9 }, new object[] { nameof(Fake.Action9), TestCases<Fake>.Action9, 9 } }; } } [Theory] [MemberData(nameof(ValidBaseTypeCases))] public void CreateDelegate_ExactBaseType<TFunc>( String methodName, ITestCase<Fake, TFunc> test, int expectedValue) { // Arrange var fake = new Fake(); var method = typeof(Fake).GetMethod(methodName); // Act var methodDelegate = test.CreateDelegate(method); var actualValue = test.InvokeDelegate(fake, methodDelegate); // Assert Assert.Equal(expectedValue, actualValue); } [Theory] [MemberData(nameof(ValidBaseTypeCases))] public void CreateDelegate_AssignableBaseType<TFunc>( String methodName, ITestCase<Fake, TFunc> test, int expectedValue) { // Arrange var fake = new Fake(); var method = typeof(IFake).GetMethod(methodName); // Act var methodDelegate = test.CreateDelegate(method); var actualValue = test.InvokeDelegate(fake, methodDelegate); // Assert Assert.Equal(expectedValue, actualValue); } public static IEnumerable<object[]> ArgumentNullCases { get { return new List<object[]> { new object[] { ToFunc(m => m.CreateFunc0<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc0()) }, new object[] { ToFunc(m => m.CreateFunc1<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc1()) }, new object[] { ToFunc(m => m.CreateFunc2<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc2()) }, new object[] { ToFunc(m => m.CreateFunc3<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc3()) }, new object[] { ToFunc(m => m.CreateFunc4<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc4()) }, new object[] { ToFunc(m => m.CreateFunc5<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc5()) }, new object[] { ToFunc(m => m.CreateFunc6<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc6()) }, new object[] { ToFunc(m => m.CreateFunc7<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc7()) }, new object[] { ToFunc(m => m.CreateFunc8<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc8()) }, new object[] { ToFunc(m => m.CreateFunc9<Fake>()) }, new object[] { ToFunc(m => m.CreateFunc9()) }, new object[] { ToFunc(m => m.CreateAction0()) }, new object[] { ToFunc(m => m.CreateAction0<Fake>()) }, new object[] { ToFunc(m => m.CreateAction1()) }, new object[] { ToFunc(m => m.CreateAction1<Fake>()) } }; } } [Theory] [MemberData(nameof(ArgumentNullCases))] public void CreateDelegate_NullMethodInfo(Func<MethodInfo, object> createDelegate) { // Arrange MethodInfo method = null; // Act var exception = Record.Exception( () => createDelegate(method) ); // Assert Assert.IsType<ArgumentNullException>(exception); } public static class TypedTestCases<TBase> where TBase : class, IFake { public static ITestCase<TBase, Func<TBase, object>> Func0 = new FuncTestCase<TBase, Func<TBase, object>>( method => method.CreateFunc0<TBase>(), (fake, func) => func(fake) ); public static ITestCase<TBase, Func<TBase, object, object>> Func1 = new FuncTestCase<TBase, Func<TBase, object, object>>( method => method.CreateFunc1<TBase>(), (fake, func) => func(fake, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object>> Func2 = new FuncTestCase<TBase, Func<TBase, object, object, object>>( method => method.CreateFunc2<TBase>(), (fake, func) => func(fake, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object>> Func3 = new FuncTestCase<TBase, Func<TBase, object, object, object, object>>( method => method.CreateFunc3<TBase>(), (fake, func) => func(fake, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object>> Func4 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object>>( method => method.CreateFunc4<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object, object>> Func5 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object, object>>( method => method.CreateFunc5<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object, object, object>> Func6 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object, object, object>>( method => method.CreateFunc6<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object>> Func7 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object>>( method => method.CreateFunc7<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object, object>> Func8 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object, object>>( method => method.CreateFunc8<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object, object, object>> Func9 = new FuncTestCase<TBase, Func<TBase, object, object, object, object, object, object, object, object, object, object>>( method => method.CreateFunc9<TBase>(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase>> Action0 = new ActionTestCase<TBase, Action<TBase>>( method => method.CreateAction0<TBase>(), (fake, action) => action(fake) ); public static ITestCase<TBase, Action<TBase, object>> Action1 = new ActionTestCase<TBase, Action<TBase, object>>( method => method.CreateAction1<TBase>(), (fake, action) => action(fake, 1) ); public static ITestCase<TBase, Action<TBase, object, object>> Action2 = new ActionTestCase<TBase, Action<TBase, object, object>>( method => method.CreateAction2<TBase>(), (fake, action) => action(fake, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object>> Action3 = new ActionTestCase<TBase, Action<TBase, object, object, object>>( method => method.CreateAction3<TBase>(), (fake, action) => action(fake, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object>> Action4 = new ActionTestCase<TBase, Action<TBase, object, object, object, object>>( method => method.CreateAction4<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object, object>> Action5 = new ActionTestCase<TBase, Action<TBase, object, object, object, object, object>>( method => method.CreateAction5<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object, object, object>> Action6 = new ActionTestCase<TBase, Action<TBase, object, object, object, object, object, object>>( method => method.CreateAction6<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object, object, object, object>> Action7 = new ActionTestCase<TBase, Action<TBase, object, object, object, object, object, object, object>>( method => method.CreateAction7<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object, object, object, object, object>> Action8 = new ActionTestCase<TBase, Action<TBase, object, object, object, object, object, object, object, object>>( method => method.CreateAction8<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<TBase, object, object, object, object, object, object, object, object, object>> Action9 = new ActionTestCase<TBase, Action<TBase, object, object, object, object, object, object, object, object, object>>( method => method.CreateAction9<TBase>(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1, 1, 1) ); } public static class TestCases<TBase> where TBase : class, IFake { public static ITestCase<TBase, Func<object, object>> Func0 = new FuncTestCase<TBase, Func<object, object>>( method => method.CreateFunc0(), (fake, func) => func(fake) ); public static ITestCase<TBase, Func<object, object, object>> Func1 = new FuncTestCase<TBase, Func<object, object, object>>( method => method.CreateFunc1(), (fake, func) => func(fake, 1) ); public static ITestCase<TBase, Func<object, object, object, object>> Func2 = new FuncTestCase<TBase, Func<object, object, object, object>>( method => method.CreateFunc2(), (fake, func) => func(fake, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object>> Func3 = new FuncTestCase<TBase, Func<object, object, object, object, object>>( method => method.CreateFunc3(), (fake, func) => func(fake, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object>> Func4 = new FuncTestCase<TBase, Func<object, object, object, object, object, object>>( method => method.CreateFunc4(), (fake, func) => func(fake, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object, object>> Func5 = new FuncTestCase<TBase, Func<object, object, object, object, object, object, object>>( method => method.CreateFunc5(), (fake, func) => func(fake, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object, object, object>> Func6 = new FuncTestCase<TBase, Func<object, object, object, object, object, object, object, object>>( method => method.CreateFunc6(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object, object, object, object>> Func7 = new FuncTestCase<TBase, Func<object, object, object, object, object, object, object, object, object>>( method => method.CreateFunc7(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object, object, object, object, object>> Func8 = new FuncTestCase<TBase, Func<object, object, object, object, object, object, object, object, object, object>>( method => method.CreateFunc8(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Func<object, object, object, object, object, object, object, object, object, object, object>> Func9 = new FuncTestCase<TBase, Func<object, object, object, object, object, object, object, object, object, object, object>>( method => method.CreateFunc9(), (fake, func) => func(fake, 1, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object>> Action0 = new ActionTestCase<TBase, Action<object>>( method => method.CreateAction0(), (fake, action) => action(fake) ); public static ITestCase<TBase, Action<object, object>> Action1 = new ActionTestCase<TBase, Action<object, object>>( method => method.CreateAction1(), (fake, action) => action(fake, 1) ); public static ITestCase<TBase, Action<object, object, object>> Action2 = new ActionTestCase<TBase, Action<object, object, object>>( method => method.CreateAction2(), (fake, action) => action(fake, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object>> Action3 = new ActionTestCase<TBase, Action<object, object, object, object>>( method => method.CreateAction3(), (fake, action) => action(fake, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object>> Action4 = new ActionTestCase<TBase, Action<object, object, object, object, object>>( method => method.CreateAction4(), (fake, action) => action(fake, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object, object>> Action5 = new ActionTestCase<TBase, Action<object, object, object, object, object, object>>( method => method.CreateAction5(), (fake, action) => action(fake, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object, object, object>> Action6 = new ActionTestCase<TBase, Action<object, object, object, object, object, object, object>>( method => method.CreateAction6(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object, object, object, object>> Action7 = new ActionTestCase<TBase, Action<object, object, object, object, object, object, object, object>>( method => method.CreateAction7(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object, object, object, object, object>> Action8 = new ActionTestCase<TBase, Action<object, object, object, object, object, object, object, object, object>>( method => method.CreateAction8(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1, 1) ); public static ITestCase<TBase, Action<object, object, object, object, object, object, object, object, object, object>> Action9 = new ActionTestCase<TBase, Action<object, object, object, object, object, object, object, object, object, object>>( method => method.CreateAction9(), (fake, action) => action(fake, 1, 1, 1, 1, 1, 1, 1, 1, 1) ); } public interface ITestCase<TBase, TFunc> { TFunc CreateDelegate(MethodInfo method); int InvokeDelegate(TBase fake, TFunc func); } private class FuncTestCase<TBase, TFunc> : ITestCase<TBase, TFunc> where TBase : class, IFake { private Func<MethodInfo, TFunc> createDelegate { get; } private Func<TBase, TFunc, object> invokeDelegate { get; } public FuncTestCase( Func<MethodInfo, TFunc> createDelegate, Func<TBase, TFunc, object> invokeDelegate) { this.createDelegate = createDelegate; this.invokeDelegate = invokeDelegate; } public TFunc CreateDelegate(MethodInfo method) { return this.createDelegate(method); } public int InvokeDelegate(TBase fake, TFunc action) { return (int)this.invokeDelegate(fake, action); } } private class ActionTestCase<TBase, TAction> : ITestCase<TBase, TAction> where TBase : class, IFake { private Func<MethodInfo, TAction> createDelegate { get; } private Action<TBase, TAction> invokeDelegate { get; } public ActionTestCase( Func<MethodInfo, TAction> createDelegate, Action<TBase, TAction> invokeDelegate) { this.createDelegate = createDelegate; this.invokeDelegate = invokeDelegate; } public TAction CreateDelegate(MethodInfo method) { return this.createDelegate(method); } public int InvokeDelegate(TBase fake, TAction action) { this.invokeDelegate(fake, action); return fake.Value; } } public interface IFake { int Func0(); int Func1(int a); int Func2(int a, int b); int Func3(int a, int b, int c); int Func4(int a, int b, int c, int d); int Func5(int a, int b, int c, int d, int e); int Func6(int a, int b, int c, int d, int e, int f); int Func7(int a, int b, int c, int d, int e, int f, int g); int Func8(int a, int b, int c, int d, int e, int f, int g, int h); int Func9(int a, int b, int c, int d, int e, int f, int g, int h, int i); int Value { get; } void Action0(); void Action1(int a); void Action2(int a, int b); void Action3(int a, int b, int c); void Action4(int a, int b, int c, int d); void Action5(int a, int b, int c, int d, int e); void Action6(int a, int b, int c, int d, int e, int f); void Action7(int a, int b, int c, int d, int e, int f, int g); void Action8(int a, int b, int c, int d, int e, int f, int g, int h); void Action9(int a, int b, int c, int d, int e, int f, int g, int h, int i); } public class Fake : IFake { public int Value { get; private set; } public int Func0() { return 0; } public int Func1(int a) { return a; } public int Func2(int a, int b) { return a + b; } public int Func3(int a, int b, int c) { return a + b + c; } public int Func4(int a, int b, int c, int d) { return a + b + c + d; } public int Func5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } public int Func6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } public int Func7(int a, int b, int c, int d, int e, int f, int g) { return a + b + c + d + e + f + g; } public int Func8(int a, int b, int c, int d, int e, int f, int g, int h) { return a + b + c + d + e + f + g + h; } public int Func9(int a, int b, int c, int d, int e, int f, int g, int h, int i) { return a + b + c + d + e + f + g + h + i; } public int Func10( int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { return a + b + c + d + e + f + g + h + i + j; } public void Action0() { this.Value = 0; } public void Action1(int a) { this.Value = a; } public void Action2(int a, int b) { this.Value = a + b; } public void Action3(int a, int b, int c) { this.Value = a + b + c; } public void Action4(int a, int b, int c, int d) { this.Value = a + b + c + d; } public void Action5(int a, int b, int c, int d, int e) { this.Value = a + b + c + d + e; } public void Action6(int a, int b, int c, int d, int e, int f) { this.Value = a + b + c + d + e + f; } public void Action7(int a, int b, int c, int d, int e, int f, int g) { this.Value = a + b + c + d + e + f + g; } public void Action8(int a, int b, int c, int d, int e, int f, int g, int h) { this.Value = a + b + c + d + e + f + g + h; } public void Action9(int a, int b, int c, int d, int e, int f, int g, int h, int i) { this.Value = a + b + c + d + e + f + g + h + i; } public void Action10( int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { this.Value = a + b + c + d + e + f + g + h + i + j; } } private static Func<MethodInfo, object> ToFunc<T>(Func<MethodInfo, T> createDelegate) { return new Func<MethodInfo, object>(method => (object)createDelegate(method)); } public static IEnumerable<object[]> StaticMethodCases { get { return new List<object[]> { new object[] { nameof(StaticFake.Func0), ToFunc(m => m.CreateFunc0<StaticFake>()) }, new object[] { nameof(StaticFake.Func0), ToFunc(m => m.CreateFunc0()) }, new object[] { nameof(StaticFake.Func1), ToFunc(m => m.CreateFunc1<StaticFake>()) }, new object[] { nameof(StaticFake.Func1), ToFunc(m => m.CreateFunc1()) }, new object[] { nameof(StaticFake.Func2), ToFunc(m => m.CreateFunc2<StaticFake>()) }, new object[] { nameof(StaticFake.Func2), ToFunc(m => m.CreateFunc2()) }, new object[] { nameof(StaticFake.Func3), ToFunc(m => m.CreateFunc3<StaticFake>()) }, new object[] { nameof(StaticFake.Func3), ToFunc(m => m.CreateFunc3()) }, new object[] { nameof(StaticFake.Func4), ToFunc(m => m.CreateFunc4<StaticFake>()) }, new object[] { nameof(StaticFake.Func4), ToFunc(m => m.CreateFunc4()) }, new object[] { nameof(StaticFake.Func5), ToFunc(m => m.CreateFunc5<StaticFake>()) }, new object[] { nameof(StaticFake.Func5), ToFunc(m => m.CreateFunc5()) }, new object[] { nameof(StaticFake.Func6), ToFunc(m => m.CreateFunc6<StaticFake>()) }, new object[] { nameof(StaticFake.Func6), ToFunc(m => m.CreateFunc6()) }, new object[] { nameof(StaticFake.Func7), ToFunc(m => m.CreateFunc7<StaticFake>()) }, new object[] { nameof(StaticFake.Func7), ToFunc(m => m.CreateFunc7()) }, new object[] { nameof(StaticFake.Func8), ToFunc(m => m.CreateFunc8<StaticFake>()) }, new object[] { nameof(StaticFake.Func8), ToFunc(m => m.CreateFunc8()) }, new object[] { nameof(StaticFake.Func9), ToFunc(m => m.CreateFunc9<StaticFake>()) }, new object[] { nameof(StaticFake.Func9), ToFunc(m => m.CreateFunc9()) }, new object[] { nameof(StaticFake.Action0), ToFunc(m => m.CreateAction0()) }, new object[] { nameof(StaticFake.Action0), ToFunc(m => m.CreateAction0<StaticFake>()) }, new object[] { nameof(StaticFake.Action1), ToFunc(m => m.CreateAction1()) }, new object[] { nameof(StaticFake.Action1), ToFunc(m => m.CreateAction1<StaticFake>()) } }; } } [Theory] [MemberData(nameof(StaticMethodCases))] public void CreateDelegate_StaticMethod( String methodName, Func<MethodInfo, object> createDelegate) { // Arrange var method = typeof(StaticFake).GetMethod(methodName); // Act var exception = Record.Exception( () => createDelegate(method) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{methodName}' method is static." + Environment.NewLine + "Parameter name: method", exception.Message ); } public class StaticFake { public static int Func0() { return 0; } public static int Func1(int a) { return a; } public static int Func2(int a, int b) { return a + b; } public static int Func3(int a, int b, int c) { return a + b + c; } public static int Func4(int a, int b, int c, int d) { return a + b + c + d; } public static int Func5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } public static int Func6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } public static int Func7(int a, int b, int c, int d, int e, int f, int g) { return a + b + c + d + e + f + g; } public static int Func8(int a, int b, int c, int d, int e, int f, int g, int h) { return a + b + c + d + e + f + g + h; } public static int Func9( int a, int b, int c, int d, int e, int f, int g, int h, int i) { return a + b + c + d + e + f + g + h + i; } public static void Action0() {} public static void Action1(int a) {} } } }
using JetBrains.Annotations; using LinFx.Extensions.MultiTenancy; using LinFx.Reflection; using LinFx.Utils; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace LinFx.Domain.Entities { /// <summary> /// Some helper methods for entities. /// </summary> public static class EntityHelper { public static bool IsMultiTenant<TEntity>() where TEntity : IEntity { return IsMultiTenant(typeof(TEntity)); } public static bool IsMultiTenant(Type type) { return typeof(IMultiTenant).IsAssignableFrom(type); } public static bool EntityEquals(IEntity entity1, IEntity entity2) { if (entity1 == null || entity2 == null) return false; //Same instances must be considered as equal if (ReferenceEquals(entity1, entity2)) return true; //Must have a IS-A relation of types or must be same type var typeOfEntity1 = entity1.GetType(); var typeOfEntity2 = entity2.GetType(); if (!typeOfEntity1.IsAssignableFrom(typeOfEntity2) && !typeOfEntity2.IsAssignableFrom(typeOfEntity1)) { return false; } //Different tenants may have an entity with same Id. if (entity1 is IMultiTenant && entity2 is IMultiTenant) { var tenant1Id = ((IMultiTenant)entity1).TenantId; var tenant2Id = ((IMultiTenant)entity2).TenantId; if (tenant1Id != tenant2Id) { if (tenant1Id == null || tenant2Id == null) { return false; } if (!tenant1Id.Equals(tenant2Id)) { return false; } } } //Transient objects are not considered as equal if (HasDefaultKeys(entity1) && HasDefaultKeys(entity2)) { return false; } //var entity1Keys = entity1.GetKeys(); //var entity2Keys = entity2.GetKeys(); //if (entity1Keys.Length != entity2Keys.Length) //{ // return false; //} //for (var i = 0; i < entity1Keys.Length; i++) //{ // var entity1Key = entity1Keys[i]; // var entity2Key = entity2Keys[i]; // if (entity1Key == null) // { // if (entity2Key == null) // { // //Both null, so considered as equals // continue; // } // //entity2Key is not null! // return false; // } // if (entity2Key == null) // { // //entity1Key was not null! // return false; // } // if (TypeHelper.IsDefaultValue(entity1Key) && TypeHelper.IsDefaultValue(entity2Key)) // { // return false; // } // if (!entity1Key.Equals(entity2Key)) // { // return false; // } //} return true; } public static bool IsEntity([NotNull] Type type) { Check.NotNull(type, nameof(type)); return typeof(IEntity).IsAssignableFrom(type); } public static void CheckEntity([NotNull] Type type) { Check.NotNull(type, nameof(type)); if (!IsEntity(type)) { throw new Exception($"Given {nameof(type)} is not an entity: {type.AssemblyQualifiedName}. It must implement {typeof(IEntity).AssemblyQualifiedName}."); } } public static bool IsEntityWithId([NotNull] Type type) { foreach (var interfaceType in type.GetInterfaces()) { if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEntity<>)) { return true; } } return false; } public static bool HasDefaultId<TKey>(IEntity<TKey> entity) { if (EqualityComparer<TKey>.Default.Equals(entity.Id, default)) { return true; } //Workaround for EF Core since it sets int/long to min value when attaching to dbcontext if (typeof(TKey) == typeof(int)) { return Convert.ToInt32(entity.Id) <= 0; } if (typeof(TKey) == typeof(long)) { return Convert.ToInt64(entity.Id) <= 0; } return false; } private static bool IsDefaultKeyValue(object value) { if (value == null) { return true; } var type = value.GetType(); //Workaround for EF Core since it sets int/long to min value when attaching to DbContext if (type == typeof(int)) { return Convert.ToInt32(value) <= 0; } if (type == typeof(long)) { return Convert.ToInt64(value) <= 0; } return TypeHelper.IsDefaultValue(value); } public static bool HasDefaultKeys([NotNull] IEntity entity) { Check.NotNull(entity, nameof(entity)); //foreach (var key in entity.GetKeys()) //{ // if (!IsDefaultKeyValue(key)) // { // return false; // } //} return true; } /// <summary> /// Tries to find the primary key type of the given entity type. /// May return null if given type does not implement <see cref="IEntity{TKey}"/> /// </summary> [CanBeNull] public static Type FindPrimaryKeyType<TEntity>() where TEntity : IEntity { return FindPrimaryKeyType(typeof(TEntity)); } /// <summary> /// Tries to find the primary key type of the given entity type. /// May return null if given type does not implement <see cref="IEntity{TKey}"/> /// </summary> [CanBeNull] public static Type FindPrimaryKeyType([NotNull] Type entityType) { if (!typeof(IEntity).IsAssignableFrom(entityType)) { throw new Exception($"Given {nameof(entityType)} is not an entity. It should implement {typeof(IEntity).AssemblyQualifiedName}!"); } foreach (var interfaceType in entityType.GetTypeInfo().GetInterfaces()) { if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEntity<>)) { return interfaceType.GenericTypeArguments[0]; } } return null; } public static Expression<Func<TEntity, bool>> CreateEqualityExpressionForId<TEntity, TKey>(TKey id) where TEntity : IEntity<TKey> { var lambdaParam = Expression.Parameter(typeof(TEntity)); var leftExpression = Expression.PropertyOrField(lambdaParam, "Id"); var idValue = Convert.ChangeType(id, typeof(TKey)); Expression<Func<object>> closure = () => idValue; var rightExpression = Expression.Convert(closure.Body, leftExpression.Type); var lambdaBody = Expression.Equal(leftExpression, rightExpression); return Expression.Lambda<Func<TEntity, bool>>(lambdaBody, lambdaParam); } public static void TrySetId<TKey>( IEntity<TKey> entity, Func<TKey> idFactory, bool checkForDisableIdGenerationAttribute = false) { ObjectHelper.TrySetProperty( entity, x => x.Id, idFactory, checkForDisableIdGenerationAttribute ? new Type[] { typeof(DisableIdGenerationAttribute) } : new Type[] { }); } public static void TrySetId<TKey>( IEntity<TKey> entity, string id, bool checkForDisableIdGenerationAttribute = false) { } } }
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class RagePixelSprite : MonoBehaviour, IRagePixel { public Vector3 accuratePosition; public RagePixelSpriteSheet spriteSheet; public enum Mode { Default = 0, Grid9 }; public Mode mode = Mode.Default; public enum PivotMode { BottomLeft = 0, Bottom, Middle }; public PivotMode pivotMode = PivotMode.BottomLeft; public enum AnimationMode { PlayOnce = 0, PlayOnceReverse, Loop, LoopReverse, PingPong }; public AnimationMode animationMode = 0; public int animationMinIndex = -1; public int animationMaxIndex = -1; private int animationPingPongDirection = 1; private RagePixelSpriteSheet lastCellSpriteSheetCache; private RagePixelCell lastCellCache; private int lastCellCacheKey; private RagePixelSpriteSheet lastRowSpriteSheetCache; private RagePixelRow lastRowCache; private int lastRowCacheKey; public int grid9Left; public int grid9Top; public int grid9Right; public int grid9Bottom; public int currentRowKey; public int currentCellKey; public int ZLayer; public int pixelSizeX = 16; public int pixelSizeY = 16; public bool meshIsDirty = false; public bool vertexColorsAreDirty = false; public Color tintColor = new Color(1f, 1f, 1f, 1f); public bool flipHorizontal; public bool flipVertical; public float nextAnimFrame = 0f; public bool playAnimation = false; private bool toBeRefreshed; private float myTime=0f; void Awake() { lastRowSpriteSheetCache = null; lastCellSpriteSheetCache = null; lastRowCache = null; lastCellCache = null; lastCellCacheKey = 0; lastRowCacheKey = 0; meshIsDirty = true; vertexColorsAreDirty = true; if (!Application.isPlaying) { MeshFilter meshFilter = null; MeshRenderer meshRenderer = null; meshRenderer = gameObject.GetComponent("MeshRenderer") as MeshRenderer; if (meshRenderer == null) { meshRenderer = gameObject.AddComponent("MeshRenderer") as MeshRenderer; } meshFilter = gameObject.GetComponent("MeshFilter") as MeshFilter; if (meshFilter == null) { meshFilter = gameObject.AddComponent("MeshFilter") as MeshFilter; } if (meshFilter.sharedMesh != null) { RagePixelSprite[] ragePixelSprites = GameObject.FindObjectsOfType(typeof(RagePixelSprite)) as RagePixelSprite[]; foreach (RagePixelSprite ragePixelSprite in ragePixelSprites) { MeshFilter otherMeshFilter = ragePixelSprite.GetComponent(typeof(MeshFilter)) as MeshFilter; if (otherMeshFilter != null) { if (otherMeshFilter.sharedMesh == meshFilter.sharedMesh && otherMeshFilter != meshFilter) { meshFilter.mesh = new Mesh(); toBeRefreshed = true; } } } } if (meshFilter.sharedMesh == null) { meshFilter.sharedMesh = new Mesh(); toBeRefreshed = true; } } else { meshIsDirty = true; refreshMesh(); } } void Start () { if (Application.isPlaying && playAnimation && gameObject.active) { nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } } void OnEnable() { if (Application.isPlaying && playAnimation) { nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } } public void SnapToScale() { transform.localScale = new Vector3(1f, 1f, 1f); } public void SnapToIntegerPosition() { if (!Application.isPlaying) { //transform.rotation = Quaternion.identity; transform.localEulerAngles = new Vector3(0f, 0f, transform.localEulerAngles.z); } //SnapToScale(); transform.localPosition = new Vector3(Mathf.RoundToInt(transform.localPosition.x), Mathf.RoundToInt(transform.localPosition.y), ZLayer); } public void SnapToIntegerPosition(float divider) { transform.rotation = Quaternion.identity; //SnapToScale(); transform.localPosition = new Vector3(Mathf.RoundToInt(transform.localPosition.x * divider) / divider, Mathf.RoundToInt(transform.localPosition.y * divider) / divider, ZLayer); } public void refreshMesh() { MeshRenderer meshRenderer = GetComponent(typeof(MeshRenderer)) as MeshRenderer; MeshFilter meshFilter = GetComponent(typeof(MeshFilter)) as MeshFilter; if (meshRenderer == null) { meshRenderer = gameObject.AddComponent("MeshRenderer") as MeshRenderer; } if (meshFilter == null) { meshFilter = gameObject.AddComponent("MeshFilter") as MeshFilter; } if (meshFilter.sharedMesh == null) { DestroyImmediate(meshFilter.sharedMesh); meshFilter.mesh = new Mesh(); } if (meshFilter.sharedMesh.vertexCount == 0) { meshIsDirty = true; } if (spriteSheet != null) { GenerateMesh(meshFilter.sharedMesh); } if (!Application.isPlaying) { SnapToIntegerPosition(); //SnapToScale(); } else { //SnapToScale(); } if (spriteSheet != null) { if (meshRenderer.sharedMaterial != spriteSheet.atlas) { meshRenderer.sharedMaterial = spriteSheet.atlas; } } } public void GenerateMesh(Mesh mesh) { if (meshIsDirty) { mesh.Clear(); } Rect uv = new Rect(); int[] triangles = null; Vector3[] verts = null; Vector2[] uvs = null; Color[] colors = null; int tIndex = 0; int uvIndex = 0; int vIndex = 0; int cIndex = 0; int quadCountX; int quadCountY; int quadCount; float pivotOffsetX; float pivotOffsetY; float xMin; float yMin; float uvWidth; float uvHeight; float left; float top; float offX; float offY; RagePixelRow currentRow = GetCurrentRow(); RagePixelCell currentCell = GetCurrentCell(); if (pixelSizeX > 0 && pixelSizeY > 0) { switch (mode) { case(Mode.Default): /* if (spriteSheet.rows.Length == 1 && currentRow.cells.Length == 1) { triangles = new int[6]; verts = new Vector3[4]; uvs = new Vector2[4]; colors = new Color[4]; int tIndex = 0; int uvIndex = 0; int vIndex = 0; int cIndex = 0; triangles[tIndex++] = 0; triangles[tIndex++] = 1; triangles[tIndex++] = 2; triangles[tIndex++] = 0; triangles[tIndex++] = 2; triangles[tIndex++] = 3; float left = 0f; float top = 0f; float offY = pixelSizeY; float offX = pixelSizeX; verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); Rect uv = new Rect(0f, 0f, 1f, 1f); uvs[uvIndex++] = new Vector2(0f, uv.yMin + (offY / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(0f + (offX / (float)currentRow.pixelSizeX), 0f + (offY / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(0f + (offX / (float)currentRow.pixelSizeX), 0f); uvs[uvIndex++] = new Vector2(0f, 0f); if (flipHorizontal) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 2]; uvs[uvIndex - 2] = tmp; Vector2 tmp2 = uvs[uvIndex - 3]; uvs[uvIndex - 3] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp2; } if (flipVertical) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp; Vector2 tmp2 = uvs[uvIndex - 2]; uvs[uvIndex - 2] = uvs[uvIndex - 3]; uvs[uvIndex - 3] = tmp2; } if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } }*/ quadCountX = Mathf.CeilToInt((float)pixelSizeX / (float)currentRow.pixelSizeX); quadCountY = Mathf.CeilToInt((float)pixelSizeY / (float)currentRow.pixelSizeY); quadCount = quadCountX * quadCountY; pivotOffsetX = 0f; pivotOffsetY = 0f; switch (pivotMode) { case(PivotMode.BottomLeft): pivotOffsetX = 0f; pivotOffsetY = 0f; break; case (PivotMode.Bottom): pivotOffsetX = -pixelSizeX / 2f; pivotOffsetY = 0f; break; case (PivotMode.Middle): pivotOffsetX = -pixelSizeX / 2f; pivotOffsetY = -pixelSizeY / 2f; break; } triangles = new int[quadCount * 6]; verts = new Vector3[quadCount * 4]; uvs = new Vector2[quadCount * 4]; colors = new Color[quadCount * 4]; uv = currentCell.uv; xMin = uv.xMin; yMin = uv.yMin; uvWidth = uv.width; uvHeight = uv.height; for (int qy = 0; qy < quadCountY; qy++) { for (int qx = 0; qx < quadCountX; qx++) { left = (float)qx * (float)currentRow.pixelSizeX + pivotOffsetX; top = (float)qy * (float)currentRow.pixelSizeY + pivotOffsetY; offX = (float)currentRow.pixelSizeX; offY = (float)currentRow.pixelSizeY; if (qy == quadCountY - 1) { offY = (float)(pixelSizeY % currentRow.pixelSizeY); if (Mathf.Approximately(offY, 0f)) { offY = (float)currentRow.pixelSizeY; } } if (qx == quadCountX - 1) { offX = (float)(pixelSizeX % currentRow.pixelSizeX); if (Mathf.Approximately(offX, 0f)) { offX = (float)currentRow.pixelSizeX; } } if (meshIsDirty) { int triangleTmp = (qy * quadCountX + qx) * 4; triangles[tIndex++] = triangleTmp + 0; triangles[tIndex++] = triangleTmp + 1; triangles[tIndex++] = triangleTmp + 2; triangles[tIndex++] = triangleTmp + 0; triangles[tIndex++] = triangleTmp + 2; triangles[tIndex++] = triangleTmp + 3; verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); } uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight * (offY / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * (offX / (float)currentRow.pixelSizeX), yMin + uvHeight * (offY / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * (offX / (float)currentRow.pixelSizeX), yMin); uvs[uvIndex++] = new Vector2(xMin, yMin); if (flipHorizontal) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 2]; uvs[uvIndex - 2] = tmp; Vector2 tmp2 = uvs[uvIndex - 3]; uvs[uvIndex - 3] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp2; } if (flipVertical) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp; Vector2 tmp2 = uvs[uvIndex - 2]; uvs[uvIndex - 2] = uvs[uvIndex - 3]; uvs[uvIndex - 3] = tmp2; } if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } } break; case (Mode.Grid9): quadCountX = Mathf.CeilToInt((float)(pixelSizeX - grid9Left - grid9Right) / ((float)currentRow.pixelSizeX - grid9Left - grid9Right)); quadCountY = Mathf.CeilToInt((float)(pixelSizeY - grid9Bottom - grid9Top) / ((float)currentRow.pixelSizeY - grid9Bottom - grid9Top)); quadCount = quadCountX * quadCountY; pivotOffsetX = 0f; pivotOffsetY = 0f; switch (pivotMode) { case(PivotMode.BottomLeft): pivotOffsetX = 0f; pivotOffsetY = 0f; break; case (PivotMode.Bottom): pivotOffsetX = -pixelSizeX / 2f; pivotOffsetY = 0f; break; case (PivotMode.Middle): pivotOffsetX = -pixelSizeX / 2f; pivotOffsetY = -pixelSizeY / 2f; break; } int edgeQuadCount = 0; if (grid9Bottom > 0f && grid9Left > 0f) { edgeQuadCount++; } if (grid9Bottom > 0f && grid9Right > 0f) { edgeQuadCount++; } if (grid9Top > 0f && grid9Left > 0f) { edgeQuadCount++; } if (grid9Top > 0f && grid9Right > 0f) { edgeQuadCount++; } if (grid9Bottom > 0f) { edgeQuadCount += quadCountX; } if (grid9Top > 0f) { edgeQuadCount += quadCountX; } if (grid9Left > 0f) { edgeQuadCount += quadCountY; } if (grid9Right > 0f) { edgeQuadCount += quadCountY; } triangles = new int[quadCount * 6 + edgeQuadCount * 6]; verts = new Vector3[quadCount * 4 + edgeQuadCount * 4]; uvs = new Vector2[quadCount * 4 + edgeQuadCount * 4]; colors = new Color[quadCount * 4 + edgeQuadCount * 4]; //Debug.Log("verts.length: " + verts.Length); uv = currentCell.uv; xMin = uv.xMin; yMin = uv.yMin; uvWidth = uv.width; uvHeight = uv.height; for (int qy = 0; qy < quadCountY; qy++) { for (int qx = 0; qx < quadCountX; qx++) { if ( qy==0 && grid9Bottom > 0f) { left = (float)qx * (float)(currentRow.pixelSizeX - grid9Left - grid9Right) + pivotOffsetX + grid9Left; top = pivotOffsetY; offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); offY = grid9Bottom; if (qx == quadCountX - 1) { offX = (float)((pixelSizeX - grid9Left - grid9Right) % (currentRow.pixelSizeX - grid9Left - grid9Right)); if (Mathf.Approximately(offX, 0f)) { offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); } } if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (qy == quadCountY - 1 && grid9Top > 0f) { left = (float)qx * (float)(currentRow.pixelSizeX - grid9Left - grid9Right) + pivotOffsetX + grid9Left; top = pivotOffsetY+pixelSizeY-grid9Top; offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); offY = grid9Top; if (qx == quadCountX - 1) { offX = (float)((pixelSizeX - grid9Left - grid9Right) % (currentRow.pixelSizeX - grid9Left - grid9Right)); if (Mathf.Approximately(offX, 0f)) { offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); } } if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (qx == 0 && grid9Left > 0f) { left = pivotOffsetX; top = (float)qy * (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top) + pivotOffsetY + grid9Bottom; offX = grid9Left; offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); if (qy == quadCountY - 1) { offY = (float)((pixelSizeY - grid9Bottom - grid9Top) % (currentRow.pixelSizeY - grid9Bottom - grid9Top)); if (Mathf.Approximately(offY, 0f)) { offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); } } if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (qx == quadCountX-1 && grid9Right > 0f) { left = (float)(pivotOffsetX + pixelSizeX - grid9Right); top = (float)qy * (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top) + pivotOffsetY + grid9Bottom; offX = (float)grid9Right; offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); if (qy == quadCountY - 1) { offY = (float)((pixelSizeY - grid9Bottom - grid9Top) % (currentRow.pixelSizeY - grid9Bottom - grid9Top)); if (Mathf.Approximately(offY, 0f)) { offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); } } if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } left = (float)qx * (float)(currentRow.pixelSizeX - grid9Left - grid9Right) + pivotOffsetX + grid9Left; top = (float)qy * (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top) + pivotOffsetY + grid9Bottom; offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); if (qy == quadCountY - 1) { offY = (float)((pixelSizeY- grid9Bottom - grid9Top) % (currentRow.pixelSizeY - grid9Bottom - grid9Top)); if (Mathf.Approximately(offY, 0f)) { offY = (float)(currentRow.pixelSizeY - grid9Bottom - grid9Top); } } if (qx == quadCountX - 1) { offX = (float)((pixelSizeX- grid9Left - grid9Right) % (currentRow.pixelSizeX - grid9Left - grid9Right)); if (Mathf.Approximately(offX, 0f)) { offX = (float)(currentRow.pixelSizeX - grid9Left - grid9Right); } } if (meshIsDirty) { //int triangleTmp = (qy * quadCountX + qx) * 4; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); } uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(offY + grid9Bottom) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(offX + grid9Left) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); if (flipHorizontal) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 2]; uvs[uvIndex - 2] = tmp; Vector2 tmp2 = uvs[uvIndex - 3]; uvs[uvIndex - 3] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp2; } if (flipVertical) { Vector2 tmp = uvs[uvIndex - 1]; uvs[uvIndex - 1] = uvs[uvIndex - 4]; uvs[uvIndex - 4] = tmp; Vector2 tmp2 = uvs[uvIndex - 2]; uvs[uvIndex - 2] = uvs[uvIndex - 3]; uvs[uvIndex - 3] = tmp2; } if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } } if (grid9Bottom > 0f && grid9Left > 0f) { left = pivotOffsetX; top = pivotOffsetY; offX = grid9Left; offY = grid9Bottom; if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin); uvs[uvIndex++] = new Vector2(xMin, yMin); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (grid9Bottom > 0f && grid9Right > 0f) { left = pivotOffsetX + pixelSizeX - grid9Right; top = pivotOffsetY; offX = grid9Right; offY = grid9Bottom; if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin + uvHeight * ((float)grid9Bottom / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (grid9Top > 0f && grid9Right > 0f) { left = pivotOffsetX + pixelSizeX - grid9Right; top = pivotOffsetY + pixelSizeY - grid9Top; offX = grid9Right; offY = grid9Top; if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth, yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)(currentRow.pixelSizeX - grid9Right) / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } if (grid9Top > 0f && grid9Left > 0f) { left = pivotOffsetX; top = pivotOffsetY + pixelSizeY - grid9Top; offX = grid9Left; offY = grid9Top; if (meshIsDirty) { triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 1; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 0; triangles[tIndex++] = vIndex + 2; triangles[tIndex++] = vIndex + 3; } verts[vIndex++] = new Vector3(left, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top + offY, 0f); verts[vIndex++] = new Vector3(left + offX, top, 0f); verts[vIndex++] = new Vector3(left, top, 0f); uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight); uvs[uvIndex++] = new Vector2(xMin + uvWidth * ((float)grid9Left / (float)currentRow.pixelSizeX), yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); uvs[uvIndex++] = new Vector2(xMin, yMin + uvHeight * ((float)(currentRow.pixelSizeY - grid9Top) / (float)currentRow.pixelSizeY)); if (vertexColorsAreDirty || meshIsDirty) { colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; colors[cIndex++] = tintColor; } } break; } } if (meshIsDirty) { mesh.vertices = verts; mesh.triangles = triangles; } if (vertexColorsAreDirty || meshIsDirty) { mesh.colors = colors; } mesh.uv = uvs; mesh.RecalculateBounds(); mesh.RecalculateNormals(); meshIsDirty = false; vertexColorsAreDirty = false; } public void checkKeyIntegrity() { if (!GetCurrentRow().key.Equals(currentRowKey)) { currentRowKey = GetCurrentRow().key; } if (!GetCurrentCell().key.Equals(currentCellKey)) { currentCellKey = GetCurrentCell().key; } } public void OnDestroy() { MeshFilter meshFilter = GetComponent(typeof(MeshFilter)) as MeshFilter; if (meshFilter != null) { DestroyImmediate(meshFilter.sharedMesh); } } public void shiftCell(int amount, bool loop) { int currIndex = GetCurrentRow().GetIndex(currentCellKey); if (currIndex + amount >= Mathf.Max(0, animationMinIndex) && (currIndex + amount < GetCurrentRow().cells.Length && animationMaxIndex < 0 || currIndex + amount <= animationMaxIndex)) { currentCellKey = GetCurrentRow().cells[currIndex + amount].key; } else if(loop) { if (amount > 0) { currentCellKey = GetCurrentRow().cells[Mathf.Max(animationMinIndex, 0)].key; } else { if (animationMaxIndex >= 0) { currentCellKey = GetCurrentRow().cells[Mathf.Min(animationMaxIndex, GetCurrentRow().cells.Length - 1)].key; } else { currentCellKey = GetCurrentRow().cells[GetCurrentRow().cells.Length - 1].key; } } } } public void shiftRow(int amount) { int currIndex = spriteSheet.GetIndex(currentRowKey); if (currIndex + amount >= 0 && currIndex + amount < spriteSheet.rows.Length) { currentRowKey = spriteSheet.rows[currIndex + amount].key; currentCellKey = GetCurrentRow().cells[0].key; } else { if (currIndex < 0) { //noop } else { if (amount > 0) { currentRowKey = spriteSheet.rows[0].key; } else { currentRowKey = spriteSheet.rows[spriteSheet.rows.Length-1].key; } currentCellKey = GetCurrentRow().cells[0].key; } } } public void selectRow(int index) { if (index >= 0 && index < spriteSheet.rows.Length) { currentRowKey = spriteSheet.rows[index].key; } } public void selectCell(int index) { currentCellKey = GetCurrentRow().cells[0].key; } public string getCurrentRowName() { return GetCurrentRow().name; } public RagePixelRow GetCurrentRow() { if (Application.isPlaying) { if (lastRowCacheKey == currentRowKey && lastRowSpriteSheetCache.Equals(spriteSheet)) { return lastRowCache; } else { lastRowCache = spriteSheet.GetRow(currentRowKey); lastRowCacheKey = currentRowKey; lastRowSpriteSheetCache = spriteSheet; return lastRowCache; } } else { return spriteSheet.GetRow(currentRowKey); } } public RagePixelCell GetCurrentCell() { if (Application.isPlaying) { if (lastCellCacheKey == currentCellKey && lastCellSpriteSheetCache.Equals(spriteSheet)) { return lastCellCache; } else { lastCellCache = GetCurrentRow().GetCell(currentCellKey); lastCellCacheKey = currentCellKey; lastCellSpriteSheetCache = spriteSheet; return lastCellCache; } } else { return GetCurrentRow().GetCell(currentCellKey); } } public int GetCurrentCellIndex() { return GetCurrentRow().GetIndex(GetCurrentCell().key); } public int GetCurrentRowIndex() { return spriteSheet.GetIndex(currentRowKey); } public void OnDrawGizmosSelected() { if (toBeRefreshed) { refreshMesh(); toBeRefreshed = false; } } void Update () { if (playAnimation) { myTime += Time.deltaTime; if (myTime > 1000f) { nextAnimFrame -= myTime; myTime = 0f; } if (nextAnimFrame < myTime) { switch (animationMode) { case(AnimationMode.PlayOnce): if (GetCurrentRow().GetIndex(currentCellKey) < GetCurrentRow().cells.Length - 1 && animationMaxIndex < 0 || GetCurrentRow().GetIndex(currentCellKey) < animationMaxIndex) { while (nextAnimFrame < myTime) { shiftCell(1, false); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } refreshMesh(); } else { playAnimation = false; } break; case (AnimationMode.PlayOnceReverse): if (GetCurrentRow().GetIndex(currentCellKey) > Mathf.Max(animationMinIndex, 0)) { while (nextAnimFrame < myTime) { shiftCell(-1, false); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } refreshMesh(); } else { playAnimation = false; } break; case (AnimationMode.Loop): while (nextAnimFrame < myTime) { shiftCell(1, true); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } refreshMesh(); break; case (AnimationMode.LoopReverse): while (nextAnimFrame < myTime) { shiftCell(-1, true); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } refreshMesh(); break; case (AnimationMode.PingPong): while (nextAnimFrame < myTime) { if (animationPingPongDirection == 1) { if (GetCurrentRow().GetIndex(currentCellKey) < GetCurrentRow().cells.Length - 1 && animationMaxIndex < 0 || GetCurrentRow().GetIndex(currentCellKey) < animationMaxIndex) { //noop } else { animationPingPongDirection = -1; } } else { if (GetCurrentRow().GetIndex(currentCellKey) > Mathf.Max(animationMinIndex, 0)) { //noop } else { animationPingPongDirection = 1; } } shiftCell(animationPingPongDirection, true); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; } refreshMesh(); break; } } } } private void DrawRectangle(Rect rect, Color color) { Color oldColor = Gizmos.color; Gizmos.color = color; Gizmos.DrawLine(new Vector3(rect.xMin, rect.yMin, 0f), new Vector3(rect.xMax, rect.yMin, 0f)); Gizmos.DrawLine(new Vector3(rect.xMax, rect.yMin, 0f), new Vector3(rect.xMax, rect.yMax, 0f)); Gizmos.DrawLine(new Vector3(rect.xMax, rect.yMax, 0f), new Vector3(rect.xMin, rect.yMax, 0f)); Gizmos.DrawLine(new Vector3(rect.xMin, rect.yMax, 0f), new Vector3(rect.xMin, rect.yMin, 0f)); Gizmos.color = oldColor; } // API public void SetSprite(string name) { int key = spriteSheet.GetRowByName(name).key; if (key != 0) { currentRowKey = spriteSheet.GetRowByName(name).key; currentCellKey = GetCurrentRow().cells[0].key; meshIsDirty = true; refreshMesh(); } else { Debug.Log("ERROR: No RagePixel sprite with name " + name + " found!"); } } public void SetSprite(string name, int frameIndex) { int key = spriteSheet.GetRowByName(name).key; if (key != 0) { currentRowKey = spriteSheet.GetRowByName(name).key; if (GetCurrentRow().cells.Length > frameIndex) { currentCellKey = GetCurrentRow().cells[frameIndex].key; meshIsDirty = true; refreshMesh(); } else { Debug.Log("ERROR: RagePixel has only " + GetCurrentRow().cells.Length + " frames!"); } } else { Debug.Log("ERROR: No RagePixel sprite with name " + name + " found!"); } } public void PlayAnimation() { if (playAnimation == false) { playAnimation = true; } } public void PlayAnimation(bool forceRestart) { if (playAnimation == false || forceRestart) { nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; playAnimation = true; } } public void PlayAnimation(bool forceRestart, int rangeMinIndex, int rangeMaxIndex) { if (playAnimation == false || forceRestart) { animationMinIndex = Mathf.Clamp(rangeMinIndex, 0, GetCurrentRow().cells.Length - 1); animationMaxIndex = Mathf.Clamp(rangeMaxIndex, animationMinIndex, GetCurrentRow().cells.Length - 1); CheckAnimRangesOnPlay(); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; playAnimation = true; } } public void PlayAnimation(bool forceRestart, int animMode, int rangeMinIndex, int rangeMaxIndex) { if (playAnimation == false || forceRestart) { animationMode = (AnimationMode)animMode; animationMinIndex = Mathf.Clamp(rangeMinIndex, 0, GetCurrentRow().cells.Length - 1); animationMaxIndex = Mathf.Clamp(rangeMaxIndex, animationMinIndex, GetCurrentRow().cells.Length - 1); CheckAnimRangesOnPlay(); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; playAnimation = true; } } public void CheckAnimRangesOnPlay() { switch (animationMode) { case (AnimationMode.PlayOnce): case (AnimationMode.Loop): case (AnimationMode.PingPong): currentCellKey = GetCurrentRow().cells[Mathf.Clamp(animationMinIndex, 0, GetCurrentRow().cells.Length-1)].key; refreshMesh(); break; case (AnimationMode.LoopReverse): case (AnimationMode.PlayOnceReverse): if(animationMaxIndex >= 0) { currentCellKey = GetCurrentRow().cells[animationMaxIndex].key; } else { currentCellKey = GetCurrentRow().cells.Length-1; } refreshMesh(); break; } } public void PlayNamedAnimation(string name) { RagePixelAnimation animation = GetCurrentRow().GetAnimationByName(name); if (animation != null) { animationMinIndex = animation.startIndex; animationMaxIndex = animation.endIndex; animationMinIndex = Mathf.Clamp(animation.startIndex, 0, GetCurrentRow().cells.Length - 1); animationMaxIndex = Mathf.Clamp(animation.endIndex, animationMinIndex, GetCurrentRow().cells.Length - 1); animationMode = animation.mode; CheckAnimRangesOnPlay(); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; playAnimation = true; } else { Debug.Log("No animation: " + name + " found in the sprite: " + (GetCurrentRow().name.Length > 0 ? GetCurrentRow().name : "empty")); } } public void PlayNamedAnimation(string name, bool forceRestart) { RagePixelAnimation animation = GetCurrentRow().GetAnimationByName(name); if (animation != null) { if (playAnimation == false || forceRestart || animationMinIndex != animation.startIndex || animation.endIndex != animationMaxIndex) { animationMinIndex = animation.startIndex; animationMaxIndex = animation.endIndex; animationMinIndex = Mathf.Clamp(animation.startIndex, 0, GetCurrentRow().cells.Length - 1); animationMaxIndex = Mathf.Clamp(animation.endIndex, animationMinIndex, GetCurrentRow().cells.Length - 1); animationMode = animation.mode; CheckAnimRangesOnPlay(); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f; playAnimation = true; } } else { Debug.Log("No animation: " + name + " found in the sprite: " + (GetCurrentRow().name.Length > 0 ? GetCurrentRow().name : "empty")); } } public void PlayNamedAnimation(string name, bool forceRestart, float delayFirstFrame) { RagePixelAnimation animation = GetCurrentRow().GetAnimationByName(name); if (animation != null) { if (playAnimation == false || forceRestart || animationMinIndex != animation.startIndex || animation.endIndex != animationMaxIndex) { animationMinIndex = animation.startIndex; animationMaxIndex = animation.endIndex; animationMinIndex = Mathf.Clamp(animation.startIndex, 0, GetCurrentRow().cells.Length - 1); animationMaxIndex = Mathf.Clamp(animation.endIndex, animationMinIndex, GetCurrentRow().cells.Length - 1); animationMode = animation.mode; CheckAnimRangesOnPlay(); nextAnimFrame = myTime + GetCurrentCell().delay / 1000f + delayFirstFrame; playAnimation = true; } } else { Debug.Log("No animation: " + name + " found in the sprite: " + (GetCurrentRow().name.Length > 0 ? GetCurrentRow().name : "empty")); } } public void StopAnimation() { playAnimation = false; } public bool isPlaying() { return playAnimation; } public void SetSize(int height, int width) { if (height >= 1 && width >= 1 && (width != pixelSizeX || height != pixelSizeY)) { pixelSizeX = width; pixelSizeY = height; meshIsDirty = true; refreshMesh(); } } public Rect GetRect() { return new Rect( transform.position.x + GetPivotOffset().x, transform.position.y + GetPivotOffset().y, pixelSizeX, pixelSizeY ); } public Vector3 GetPivotOffset() { Vector3 pivotOffset = new Vector3(); switch (pivotMode) { case (RagePixelSprite.PivotMode.BottomLeft): pivotOffset.x = 0f; pivotOffset.y = 0f; break; case (RagePixelSprite.PivotMode.Bottom): pivotOffset.x = -pixelSizeX / 2f; pivotOffset.y = 0f; break; case (RagePixelSprite.PivotMode.Middle): pivotOffset.x = -pixelSizeX / 2f; pivotOffset.y = -pixelSizeY / 2f; break; } return pivotOffset; } public void SetHorizontalFlip(bool value) { if (value != flipHorizontal) { flipHorizontal = value; meshIsDirty = true; refreshMesh(); } } public void SetVerticalFlip(bool value) { if (value != flipVertical) { flipVertical = value; meshIsDirty = true; refreshMesh(); } } public void SetTintColor(Color color) { tintColor = color; vertexColorsAreDirty = true; refreshMesh(); } }
// // 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.Internal { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; /// <summary> /// Reflection helpers for accessing properties. /// </summary> internal static class PropertyHelper { private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> DefaultPropertyConversionMapper = BuildPropertyConversionMapper(); #pragma warning disable S1144 // Unused private types or members should be removed. BUT they help CoreRT to provide config through reflection private static readonly RequiredParameterAttribute _requiredParameterAttribute = new RequiredParameterAttribute(); private static readonly ArrayParameterAttribute _arrayParameterAttribute = new ArrayParameterAttribute(null, string.Empty); private static readonly DefaultValueAttribute _defaultValueAttribute = new DefaultValueAttribute(string.Empty); private static readonly AdvancedAttribute _advancedAttribute = new AdvancedAttribute(); private static readonly DefaultParameterAttribute _defaultParameterAttribute = new DefaultParameterAttribute(); private static readonly NLogConfigurationIgnorePropertyAttribute _ignorePropertyAttribute = new NLogConfigurationIgnorePropertyAttribute(); private static readonly FlagsAttribute _flagsAttribute = new FlagsAttribute(); #pragma warning restore S1144 // Unused private types or members should be removed private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> BuildPropertyConversionMapper() { return new Dictionary<Type, Func<string, ConfigurationItemFactory, object>>() { { typeof(Layout), TryParseLayoutValue }, { typeof(SimpleLayout), TryParseLayoutValue }, { typeof(ConditionExpression), TryParseConditionValue }, { typeof(Encoding), TryParseEncodingValue }, { typeof(string), (stringvalue, factory) => stringvalue }, { typeof(int), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Int32, CultureInfo.InvariantCulture) }, { typeof(bool), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Boolean, CultureInfo.InvariantCulture) }, { typeof(CultureInfo), (stringvalue, factory) => new CultureInfo(stringvalue.Trim()) }, { typeof(Type), (stringvalue, factory) => Type.GetType(stringvalue.Trim(), true) }, { typeof(LineEndingMode), (stringvalue, factory) => LineEndingMode.FromString(stringvalue.Trim()) }, { typeof(Uri), (stringvalue, factory) => new Uri(stringvalue.Trim()) } }; } /// <summary> /// Set value parsed from string. /// </summary> /// <param name="obj">object instance to set with property <paramref name="propertyName"/></param> /// <param name="propertyName">name of the property on <paramref name="obj"/></param> /// <param name="value">The value to be parsed.</param> /// <param name="configurationItemFactory"></param> internal static void SetPropertyFromString(object obj, string propertyName, string value, ConfigurationItemFactory configurationItemFactory) { var objType = obj.GetType(); InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", objType, propertyName, value); if (!TryGetPropertyInfo(objType, propertyName, out var propInfo)) { throw new NotSupportedException($"Parameter {propertyName} not supported on {objType.Name}"); } try { Type propertyType = propInfo.PropertyType; if (!TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out var newValue)) { if (propInfo.IsDefined(_arrayParameterAttribute.GetType(), false)) { throw new NotSupportedException($"Parameter {propertyName} of {objType.Name} is an array and cannot be assigned a scalar value."); } propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType; if (!(TryGetEnumValue(propertyType, value, out newValue, true) || TryImplicitConversion(propertyType, value, out newValue) || TryFlatListConversion(obj, propInfo, value, configurationItemFactory, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } propInfo.SetValue(obj, newValue, null); } catch (TargetInvocationException ex) { throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}' on {objType.Name}", ex.InnerException); } catch (Exception exception) { InternalLogger.Warn(exception, "Error when setting property '{0}' on '{1}'", propInfo.Name, objType); if (exception.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}' on {objType.Name}", exception); } } /// <summary> /// Get property info /// </summary> /// <param name="obj">object which could have property <paramref name="propertyName"/></param> /// <param name="propertyName">property name on <paramref name="obj"/></param> /// <param name="result">result when success.</param> /// <returns>success.</returns> internal static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result) { return TryGetPropertyInfo(obj.GetType(), propertyName, out result); } internal static Type GetArrayItemType(PropertyInfo propInfo) { var arrayParameterAttribute = propInfo.GetCustomAttribute<ArrayParameterAttribute>(); return arrayParameterAttribute?.ItemType; } internal static bool IsConfigurationItemType(Type type) { if (type == null || IsSimplePropertyType(type)) return false; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(type)) return true; if (typeof(Layout).IsAssignableFrom(type)) return true; // NLog will register no properties for types that are not marked with NLogConfigurationItemAttribute return TryLookupConfigItemProperties(type) != null; } internal static Dictionary<string, PropertyInfo> GetAllConfigItemProperties(Type type) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute return TryLookupConfigItemProperties(type) ?? new Dictionary<string, PropertyInfo>(); } private static Dictionary<string, PropertyInfo> TryLookupConfigItemProperties(Type type) { lock (parameterInfoCache) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute if (!parameterInfoCache.TryGetValue(type, out var cache)) { if (TryCreatePropertyInfoDictionary(type, out cache)) { parameterInfoCache[type] = cache; } else { parameterInfoCache[type] = null; // Not config item type } } return cache; } } internal static void CheckRequiredParameters(object o) { foreach (var configProp in GetAllConfigItemProperties(o.GetType())) { var propInfo = configProp.Value; if (propInfo.IsDefined(_requiredParameterAttribute.GetType(), false)) { object value = propInfo.GetValue(o, null); if (value == null) { throw new NLogConfigurationException( $"Required parameter '{propInfo.Name}' on '{o}' was not specified."); } } } } internal static bool IsSimplePropertyType(Type type) { #if !NETSTANDARD1_3 if (Type.GetTypeCode(type) != TypeCode.Object) #else if (type.IsPrimitive() || type == typeof(string)) #endif return true; if (type == typeof(CultureInfo)) return true; if (type == typeof(Type)) return true; if (type == typeof(Encoding)) return true; return false; } private static bool TryImplicitConversion(Type resultType, string value, out object result) { try { if (IsSimplePropertyType(resultType)) { result = null; return false; } MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { value.GetType() }, null); if (operatorImplicitMethod == null || !resultType.IsAssignableFrom(operatorImplicitMethod.ReturnType)) { result = null; return false; } result = operatorImplicitMethod.Invoke(null, new object[] { value }); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", value, resultType); } result = null; return false; } private static bool TryNLogSpecificConversion(Type propertyType, string value, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (DefaultPropertyConversionMapper.TryGetValue(propertyType, out var objectConverter)) { newValue = objectConverter.Invoke(value, configurationItemFactory); return true; } newValue = null; return false; } private static bool TryGetEnumValue(Type resultType, string value, out object result, bool flagsEnumAllowed) { if (!resultType.IsEnum()) { result = null; return false; } if (flagsEnumAllowed && resultType.IsDefined(_flagsAttribute.GetType(), false)) { ulong union = 0; foreach (string v in value.SplitAndTrimTokens(',')) { FieldInfo enumField = resultType.GetField(v, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField == null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture); } result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture); result = Enum.ToObject(resultType, result); return true; } else { FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField == null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } result = enumField.GetValue(null); return true; } } private static object TryParseEncodingValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { _ = configurationItemFactory; // Discard unreferenced parameter stringValue = stringValue.Trim(); if (string.Equals(stringValue, nameof(Encoding.UTF8), StringComparison.OrdinalIgnoreCase)) stringValue = Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8) return Encoding.GetEncoding(stringValue); } private static object TryParseLayoutValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(stringValue, configurationItemFactory); } private static object TryParseConditionValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { return ConditionParser.ParseExpression(stringValue, configurationItemFactory); } /// <summary> /// Try parse of string to (Generic) list, comma separated. /// </summary> /// <remarks> /// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape /// </remarks> private static bool TryFlatListConversion(object obj, PropertyInfo propInfo, string valueRaw, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (propInfo.PropertyType.IsGenericType() && TryCreateCollectionObject(obj, propInfo, valueRaw, out var newList, out var collectionAddMethod, out var propertyType)) { var values = valueRaw.SplitQuoted(',', '\'', '\\'); foreach (var value in values) { if (!(TryGetEnumValue(propertyType, value, out newValue, false) || TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out newValue) || TryImplicitConversion(propertyType, value, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) { newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } collectionAddMethod.Invoke(newList, new object[] { newValue }); } newValue = newList; return true; } newValue = null; return false; } private static bool TryCreateCollectionObject(object obj, PropertyInfo propInfo, string valueRaw, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType) { var collectionType = propInfo.PropertyType; var typeDefinition = collectionType.GetGenericTypeDefinition(); #if NET3_5 var isSet = typeDefinition == typeof(HashSet<>); #else var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>); #endif //not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc { object hashsetComparer = isSet ? ExtractHashSetComparer(obj, propInfo) : null; //note: type.GenericTypeArguments is .NET 4.5+ collectionItemType = collectionType.GetGenericArguments()[0]; collectionObject = CreateCollectionObjectInstance(isSet ? typeof(HashSet<>) : typeof(List<>), collectionItemType, hashsetComparer); //no support for array if (collectionObject == null) { throw new NLogConfigurationException("Cannot create instance of {0} for value {1}", collectionType.ToString(), valueRaw); } collectionAddMethod = collectionObject.GetType().GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); if (collectionAddMethod == null) { throw new NLogConfigurationException("Add method on type {0} for value {1} not found", collectionType.ToString(), valueRaw); } return true; } collectionObject = null; collectionAddMethod = null; collectionItemType = null; return false; } private static object CreateCollectionObjectInstance(Type collectionType, Type collectionItemType, object hashSetComparer) { var concreteType = collectionType.MakeGenericType(collectionItemType); if (hashSetComparer != null) { var constructor = concreteType.GetConstructor(new[] { hashSetComparer.GetType() }); if (constructor != null) return constructor.Invoke(new[] { hashSetComparer }); } return Activator.CreateInstance(concreteType); } /// <summary> /// Attempt to reuse the HashSet.Comparer from the original HashSet-object (Ex. StringComparer.OrdinalIgnoreCase) /// </summary> private static object ExtractHashSetComparer(object obj, PropertyInfo propInfo) { var exitingValue = propInfo.IsValidPublicProperty() ? propInfo.GetPropertyValue(obj) : null; if (exitingValue != null) { // Found original HashSet-object. See if we can extract the Comparer var comparerPropInfo = exitingValue.GetType().GetProperty("Comparer", BindingFlags.Instance | BindingFlags.Public); if (comparerPropInfo.IsValidPublicProperty()) { return comparerPropInfo.GetPropertyValue(exitingValue); } } return null; } private static bool TryTypeConverterConversion(Type type, string value, out object newValue) { try { #if !SILVERLIGHT && !NETSTANDARD1_3 var converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { newValue = converter.ConvertFromInvariantString(value); return true; } #endif newValue = null; return false; } catch (MissingMethodException ex) { InternalLogger.Error(ex, "Error in lookup of TypeDescriptor for type={0} to convert value '{1}'", type, value); newValue = null; return false; } } private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result) { if (!string.IsNullOrEmpty(propertyName)) { PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null) { result = propInfo; return true; } } // NLog has special property-lookup handling for default-parameters (and array-properties) var configProperties = GetAllConfigItemProperties(targetType); return configProperties.TryGetValue(propertyName, out result); } private static bool TryCreatePropertyInfoDictionary(Type t, out Dictionary<string, PropertyInfo> result) { result = null; try { if (!t.IsDefined(typeof(NLogConfigurationItemAttribute), true)) { return false; } result = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo propInfo in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { try { var parameterName = LookupPropertySymbolName(propInfo); if (string.IsNullOrEmpty(parameterName)) { continue; } result[parameterName] = propInfo; if (propInfo.IsDefined(_defaultParameterAttribute.GetType(), false)) { // define a property with empty name (Default property name) result[string.Empty] = propInfo; } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", propInfo.Name, t); } } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", t); } return result != null; } private static string LookupPropertySymbolName(PropertyInfo propInfo) { if (propInfo.PropertyType == null) return null; if (IsSimplePropertyType(propInfo.PropertyType)) return propInfo.Name; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(propInfo.PropertyType)) return propInfo.Name; if (typeof(Layout).IsAssignableFrom(propInfo.PropertyType)) return propInfo.Name; if (propInfo.IsDefined(_ignorePropertyAttribute.GetType(), false)) return null; var arrayParameterAttribute = propInfo.GetCustomAttribute<ArrayParameterAttribute>(); if (arrayParameterAttribute != null) { return arrayParameterAttribute.ElementName; } return propInfo.Name; } } }
// 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.Xml; using System.Collections.Generic; namespace System.ServiceModel { // NOTE: This is a dynamic dictionary of XmlDictionaryStrings for the Binary Encoder to dynamically encode should // the string not exist in the static cache. // When adding or removing memebers please keep the capacity of the XmlDictionary field current. internal static class DXD { private static Wsrm11Dictionary s_wsrm11Dictionary; static DXD() { // Each string added to the XmlDictionary will keep a reference to the XmlDictionary so this class does // not need to keep a reference. XmlDictionary dictionary = new XmlDictionary(137); // Each dictionaries' constructor should add strings to the XmlDictionary. AtomicTransactionExternal11Dictionary = new AtomicTransactionExternal11Dictionary(dictionary); CoordinationExternal11Dictionary = new CoordinationExternal11Dictionary(dictionary); SecureConversationDec2005Dictionary = new SecureConversationDec2005Dictionary(dictionary); SecureConversationDec2005Dictionary.PopulateSecureConversationDec2005(); SecurityAlgorithmDec2005Dictionary = new SecurityAlgorithmDec2005Dictionary(dictionary); SecurityAlgorithmDec2005Dictionary.PopulateSecurityAlgorithmDictionaryString(); TrustDec2005Dictionary = new TrustDec2005Dictionary(dictionary); TrustDec2005Dictionary.PopulateDec2005DictionaryStrings(); TrustDec2005Dictionary.PopulateFeb2005DictionaryString(); s_wsrm11Dictionary = new Wsrm11Dictionary(dictionary); } static public AtomicTransactionExternal11Dictionary AtomicTransactionExternal11Dictionary { get; private set; } static public CoordinationExternal11Dictionary CoordinationExternal11Dictionary { get; private set; } static public SecureConversationDec2005Dictionary SecureConversationDec2005Dictionary { get; private set; } static public SecurityAlgorithmDec2005Dictionary SecurityAlgorithmDec2005Dictionary { get; private set; } static public TrustDec2005Dictionary TrustDec2005Dictionary { get; private set; } static public Wsrm11Dictionary Wsrm11Dictionary { get { return s_wsrm11Dictionary; } } } internal class AtomicTransactionExternal11Dictionary { public XmlDictionaryString Namespace; public XmlDictionaryString CompletionUri; public XmlDictionaryString Durable2PCUri; public XmlDictionaryString Volatile2PCUri; public XmlDictionaryString CommitAction; public XmlDictionaryString RollbackAction; public XmlDictionaryString CommittedAction; public XmlDictionaryString AbortedAction; public XmlDictionaryString PrepareAction; public XmlDictionaryString PreparedAction; public XmlDictionaryString ReadOnlyAction; public XmlDictionaryString ReplayAction; public XmlDictionaryString FaultAction; public XmlDictionaryString UnknownTransaction; public AtomicTransactionExternal11Dictionary(XmlDictionary dictionary) { Namespace = dictionary.Add(AtomicTransactionExternal11Strings.Namespace); CompletionUri = dictionary.Add(AtomicTransactionExternal11Strings.CompletionUri); Durable2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Durable2PCUri); Volatile2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Volatile2PCUri); CommitAction = dictionary.Add(AtomicTransactionExternal11Strings.CommitAction); RollbackAction = dictionary.Add(AtomicTransactionExternal11Strings.RollbackAction); CommittedAction = dictionary.Add(AtomicTransactionExternal11Strings.CommittedAction); AbortedAction = dictionary.Add(AtomicTransactionExternal11Strings.AbortedAction); PrepareAction = dictionary.Add(AtomicTransactionExternal11Strings.PrepareAction); PreparedAction = dictionary.Add(AtomicTransactionExternal11Strings.PreparedAction); ReadOnlyAction = dictionary.Add(AtomicTransactionExternal11Strings.ReadOnlyAction); ReplayAction = dictionary.Add(AtomicTransactionExternal11Strings.ReplayAction); FaultAction = dictionary.Add(AtomicTransactionExternal11Strings.FaultAction); UnknownTransaction = dictionary.Add(AtomicTransactionExternal11Strings.UnknownTransaction); } } internal class CoordinationExternal11Dictionary { public XmlDictionaryString Namespace; public XmlDictionaryString CreateCoordinationContextAction; public XmlDictionaryString CreateCoordinationContextResponseAction; public XmlDictionaryString RegisterAction; public XmlDictionaryString RegisterResponseAction; public XmlDictionaryString FaultAction; public XmlDictionaryString CannotCreateContext; public XmlDictionaryString CannotRegisterParticipant; public CoordinationExternal11Dictionary(XmlDictionary dictionary) { Namespace = dictionary.Add(CoordinationExternal11Strings.Namespace); CreateCoordinationContextAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextAction); CreateCoordinationContextResponseAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextResponseAction); RegisterAction = dictionary.Add(CoordinationExternal11Strings.RegisterAction); RegisterResponseAction = dictionary.Add(CoordinationExternal11Strings.RegisterResponseAction); FaultAction = dictionary.Add(CoordinationExternal11Strings.FaultAction); CannotCreateContext = dictionary.Add(CoordinationExternal11Strings.CannotCreateContext); CannotRegisterParticipant = dictionary.Add(CoordinationExternal11Strings.CannotRegisterParticipant); } } internal class SecureConversationDec2005Dictionary : SecureConversationDictionary { public XmlDictionaryString RequestSecurityContextRenew; public XmlDictionaryString RequestSecurityContextRenewResponse; public XmlDictionaryString RequestSecurityContextClose; public XmlDictionaryString RequestSecurityContextCloseResponse; public XmlDictionaryString Instance; public List<XmlDictionaryString> SecureConversationDictionaryStrings = new List<XmlDictionaryString>(); public SecureConversationDec2005Dictionary(XmlDictionary dictionary) { SecurityContextToken = dictionary.Add(SecureConversationDec2005Strings.SecurityContextToken); AlgorithmAttribute = dictionary.Add(SecureConversationDec2005Strings.AlgorithmAttribute); Generation = dictionary.Add(SecureConversationDec2005Strings.Generation); Label = dictionary.Add(SecureConversationDec2005Strings.Label); Offset = dictionary.Add(SecureConversationDec2005Strings.Offset); Properties = dictionary.Add(SecureConversationDec2005Strings.Properties); Identifier = dictionary.Add(SecureConversationDec2005Strings.Identifier); Cookie = dictionary.Add(SecureConversationDec2005Strings.Cookie); RenewNeededFaultCode = dictionary.Add(SecureConversationDec2005Strings.RenewNeededFaultCode); BadContextTokenFaultCode = dictionary.Add(SecureConversationDec2005Strings.BadContextTokenFaultCode); Prefix = dictionary.Add(SecureConversationDec2005Strings.Prefix); DerivedKeyTokenType = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyTokenType); SecurityContextTokenType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenType); SecurityContextTokenReferenceValueType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenReferenceValueType); RequestSecurityContextIssuance = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuance); RequestSecurityContextIssuanceResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuanceResponse); RequestSecurityContextRenew = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenew); RequestSecurityContextRenewResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenewResponse); RequestSecurityContextClose = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextClose); RequestSecurityContextCloseResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextCloseResponse); Namespace = dictionary.Add(SecureConversationDec2005Strings.Namespace); DerivedKeyToken = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyToken); Nonce = dictionary.Add(SecureConversationDec2005Strings.Nonce); Length = dictionary.Add(SecureConversationDec2005Strings.Length); Instance = dictionary.Add(SecureConversationDec2005Strings.Instance); } public void PopulateSecureConversationDec2005() { SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextToken); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.AlgorithmAttribute); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Generation); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Label); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Offset); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Properties); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Identifier); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Cookie); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RenewNeededFaultCode); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.BadContextTokenFaultCode); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Prefix); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyTokenType); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenType); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenReferenceValueType); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuance); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuanceResponse); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenew); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenewResponse); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextClose); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextCloseResponse); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Namespace); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyToken); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Nonce); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Length); SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Instance); } } internal class SecurityAlgorithmDec2005Dictionary { public XmlDictionaryString Psha1KeyDerivationDec2005; public List<XmlDictionaryString> SecurityAlgorithmDictionaryStrings = new List<XmlDictionaryString>(); public SecurityAlgorithmDec2005Dictionary(XmlDictionary dictionary) { Psha1KeyDerivationDec2005 = dictionary.Add(SecurityAlgorithmDec2005Strings.Psha1KeyDerivationDec2005); } public void PopulateSecurityAlgorithmDictionaryString() { SecurityAlgorithmDictionaryStrings.Add(DXD.SecurityAlgorithmDec2005Dictionary.Psha1KeyDerivationDec2005); } } internal class TrustDec2005Dictionary : TrustDictionary { public XmlDictionaryString AsymmetricKeyBinarySecret; public XmlDictionaryString RequestSecurityTokenCollectionIssuanceFinalResponse; public XmlDictionaryString RequestSecurityTokenRenewal; public XmlDictionaryString RequestSecurityTokenRenewalResponse; public XmlDictionaryString RequestSecurityTokenCollectionRenewalFinalResponse; public XmlDictionaryString RequestSecurityTokenCancellation; public XmlDictionaryString RequestSecurityTokenCancellationResponse; public XmlDictionaryString RequestSecurityTokenCollectionCancellationFinalResponse; public XmlDictionaryString KeyWrapAlgorithm; public XmlDictionaryString BearerKeyType; public XmlDictionaryString SecondaryParameters; public XmlDictionaryString Dialect; public XmlDictionaryString DialectType; public List<XmlDictionaryString> Feb2005DictionaryStrings = new List<XmlDictionaryString>(); public List<XmlDictionaryString> Dec2005DictionaryString = new List<XmlDictionaryString>(); public TrustDec2005Dictionary(XmlDictionary dictionary) { CombinedHashLabel = dictionary.Add(TrustDec2005Strings.CombinedHashLabel); RequestSecurityTokenResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponse); TokenType = dictionary.Add(TrustDec2005Strings.TokenType); KeySize = dictionary.Add(TrustDec2005Strings.KeySize); RequestedTokenReference = dictionary.Add(TrustDec2005Strings.RequestedTokenReference); AppliesTo = dictionary.Add(TrustDec2005Strings.AppliesTo); Authenticator = dictionary.Add(TrustDec2005Strings.Authenticator); CombinedHash = dictionary.Add(TrustDec2005Strings.CombinedHash); BinaryExchange = dictionary.Add(TrustDec2005Strings.BinaryExchange); Lifetime = dictionary.Add(TrustDec2005Strings.Lifetime); RequestedSecurityToken = dictionary.Add(TrustDec2005Strings.RequestedSecurityToken); Entropy = dictionary.Add(TrustDec2005Strings.Entropy); RequestedProofToken = dictionary.Add(TrustDec2005Strings.RequestedProofToken); ComputedKey = dictionary.Add(TrustDec2005Strings.ComputedKey); RequestSecurityToken = dictionary.Add(TrustDec2005Strings.RequestSecurityToken); RequestType = dictionary.Add(TrustDec2005Strings.RequestType); Context = dictionary.Add(TrustDec2005Strings.Context); BinarySecret = dictionary.Add(TrustDec2005Strings.BinarySecret); Type = dictionary.Add(TrustDec2005Strings.Type); SpnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.SpnegoValueTypeUri); TlsnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.TlsnegoValueTypeUri); Prefix = dictionary.Add(TrustDec2005Strings.Prefix); RequestSecurityTokenIssuance = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuance); RequestSecurityTokenIssuanceResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuanceResponse); RequestTypeIssue = dictionary.Add(TrustDec2005Strings.RequestTypeIssue); AsymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.AsymmetricKeyBinarySecret); SymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.SymmetricKeyBinarySecret); NonceBinarySecret = dictionary.Add(TrustDec2005Strings.NonceBinarySecret); Psha1ComputedKeyUri = dictionary.Add(TrustDec2005Strings.Psha1ComputedKeyUri); KeyType = dictionary.Add(TrustDec2005Strings.KeyType); SymmetricKeyType = dictionary.Add(TrustDec2005Strings.SymmetricKeyType); PublicKeyType = dictionary.Add(TrustDec2005Strings.PublicKeyType); Claims = dictionary.Add(TrustDec2005Strings.Claims); InvalidRequestFaultCode = dictionary.Add(TrustDec2005Strings.InvalidRequestFaultCode); FailedAuthenticationFaultCode = dictionary.Add(TrustDec2005Strings.FailedAuthenticationFaultCode); UseKey = dictionary.Add(TrustDec2005Strings.UseKey); SignWith = dictionary.Add(TrustDec2005Strings.SignWith); EncryptWith = dictionary.Add(TrustDec2005Strings.EncryptWith); EncryptionAlgorithm = dictionary.Add(TrustDec2005Strings.EncryptionAlgorithm); CanonicalizationAlgorithm = dictionary.Add(TrustDec2005Strings.CanonicalizationAlgorithm); ComputedKeyAlgorithm = dictionary.Add(TrustDec2005Strings.ComputedKeyAlgorithm); RequestSecurityTokenResponseCollection = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponseCollection); Namespace = dictionary.Add(TrustDec2005Strings.Namespace); BinarySecretClauseType = dictionary.Add(TrustDec2005Strings.BinarySecretClauseType); RequestSecurityTokenCollectionIssuanceFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionIssuanceFinalResponse); RequestSecurityTokenRenewal = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewal); RequestSecurityTokenRenewalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewalResponse); RequestSecurityTokenCollectionRenewalFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionRenewalFinalResponse); RequestSecurityTokenCancellation = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellation); RequestSecurityTokenCancellationResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellationResponse); RequestSecurityTokenCollectionCancellationFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionCancellationFinalResponse); RequestTypeRenew = dictionary.Add(TrustDec2005Strings.RequestTypeRenew); RequestTypeClose = dictionary.Add(TrustDec2005Strings.RequestTypeClose); RenewTarget = dictionary.Add(TrustDec2005Strings.RenewTarget); CloseTarget = dictionary.Add(TrustDec2005Strings.CloseTarget); RequestedTokenClosed = dictionary.Add(TrustDec2005Strings.RequestedTokenClosed); RequestedAttachedReference = dictionary.Add(TrustDec2005Strings.RequestedAttachedReference); RequestedUnattachedReference = dictionary.Add(TrustDec2005Strings.RequestedUnattachedReference); IssuedTokensHeader = dictionary.Add(TrustDec2005Strings.IssuedTokensHeader); KeyWrapAlgorithm = dictionary.Add(TrustDec2005Strings.KeyWrapAlgorithm); BearerKeyType = dictionary.Add(TrustDec2005Strings.BearerKeyType); SecondaryParameters = dictionary.Add(TrustDec2005Strings.SecondaryParameters); Dialect = dictionary.Add(TrustDec2005Strings.Dialect); DialectType = dictionary.Add(TrustDec2005Strings.DialectType); } public void PopulateFeb2005DictionaryString() { Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponseCollection); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Namespace); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecretClauseType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHashLabel); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponse); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TokenType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeySize); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenReference); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.AppliesTo); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Authenticator); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHash); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinaryExchange); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Lifetime); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedSecurityToken); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Entropy); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedProofToken); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKey); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityToken); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Context); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecret); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Type); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SpnegoValueTypeUri); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TlsnegoValueTypeUri); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Prefix); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuance); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuanceResponse); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeIssue); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyBinarySecret); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Psha1ComputedKeyUri); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.NonceBinarySecret); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RenewTarget); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CloseTarget); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenClosed); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedAttachedReference); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedUnattachedReference); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.IssuedTokensHeader); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeRenew); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeClose); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeyType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.PublicKeyType); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Claims); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.InvalidRequestFaultCode); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.FailedAuthenticationFaultCode); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.UseKey); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SignWith); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptWith); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptionAlgorithm); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CanonicalizationAlgorithm); Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKeyAlgorithm); } public void PopulateDec2005DictionaryStrings() { Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHashLabel); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TokenType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeySize); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenReference); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AppliesTo); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Authenticator); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHash); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinaryExchange); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Lifetime); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedSecurityToken); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Entropy); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedProofToken); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKey); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityToken); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Context); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecret); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Type); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SpnegoValueTypeUri); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TlsnegoValueTypeUri); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Prefix); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuance); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuanceResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeIssue); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AsymmetricKeyBinarySecret); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyBinarySecret); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.NonceBinarySecret); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Psha1ComputedKeyUri); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.PublicKeyType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Claims); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.InvalidRequestFaultCode); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.FailedAuthenticationFaultCode); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.UseKey); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SignWith); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptWith); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptionAlgorithm); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CanonicalizationAlgorithm); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKeyAlgorithm); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponseCollection); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Namespace); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecretClauseType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionIssuanceFinalResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewal); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewalResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionRenewalFinalResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellation); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellationResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionCancellationFinalResponse); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeRenew); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeClose); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RenewTarget); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CloseTarget); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenClosed); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedAttachedReference); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedUnattachedReference); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.IssuedTokensHeader); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyWrapAlgorithm); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BearerKeyType); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SecondaryParameters); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Dialect); Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.DialectType); } } internal class Wsrm11Dictionary { public XmlDictionaryString AckRequestedAction; public XmlDictionaryString CloseSequence; public XmlDictionaryString CloseSequenceAction; public XmlDictionaryString CloseSequenceResponse; public XmlDictionaryString CloseSequenceResponseAction; public XmlDictionaryString CreateSequenceAction; public XmlDictionaryString CreateSequenceResponseAction; public XmlDictionaryString DiscardFollowingFirstGap; public XmlDictionaryString Endpoint; public XmlDictionaryString FaultAction; public XmlDictionaryString Final; public XmlDictionaryString IncompleteSequenceBehavior; public XmlDictionaryString LastMsgNumber; public XmlDictionaryString MaxMessageNumber; public XmlDictionaryString Namespace; public XmlDictionaryString NoDiscard; public XmlDictionaryString None; public XmlDictionaryString SequenceAcknowledgementAction; public XmlDictionaryString SequenceClosed; public XmlDictionaryString TerminateSequenceAction; public XmlDictionaryString TerminateSequenceResponse; public XmlDictionaryString TerminateSequenceResponseAction; public XmlDictionaryString UsesSequenceSSL; public XmlDictionaryString UsesSequenceSTR; public XmlDictionaryString WsrmRequired; public Wsrm11Dictionary(XmlDictionary dictionary) { AckRequestedAction = dictionary.Add(Wsrm11Strings.AckRequestedAction); CloseSequence = dictionary.Add(Wsrm11Strings.CloseSequence); CloseSequenceAction = dictionary.Add(Wsrm11Strings.CloseSequenceAction); CloseSequenceResponse = dictionary.Add(Wsrm11Strings.CloseSequenceResponse); CloseSequenceResponseAction = dictionary.Add(Wsrm11Strings.CloseSequenceResponseAction); CreateSequenceAction = dictionary.Add(Wsrm11Strings.CreateSequenceAction); CreateSequenceResponseAction = dictionary.Add(Wsrm11Strings.CreateSequenceResponseAction); DiscardFollowingFirstGap = dictionary.Add(Wsrm11Strings.DiscardFollowingFirstGap); Endpoint = dictionary.Add(Wsrm11Strings.Endpoint); FaultAction = dictionary.Add(Wsrm11Strings.FaultAction); Final = dictionary.Add(Wsrm11Strings.Final); IncompleteSequenceBehavior = dictionary.Add(Wsrm11Strings.IncompleteSequenceBehavior); LastMsgNumber = dictionary.Add(Wsrm11Strings.LastMsgNumber); MaxMessageNumber = dictionary.Add(Wsrm11Strings.MaxMessageNumber); Namespace = dictionary.Add(Wsrm11Strings.Namespace); NoDiscard = dictionary.Add(Wsrm11Strings.NoDiscard); None = dictionary.Add(Wsrm11Strings.None); SequenceAcknowledgementAction = dictionary.Add(Wsrm11Strings.SequenceAcknowledgementAction); SequenceClosed = dictionary.Add(Wsrm11Strings.SequenceClosed); TerminateSequenceAction = dictionary.Add(Wsrm11Strings.TerminateSequenceAction); TerminateSequenceResponse = dictionary.Add(Wsrm11Strings.TerminateSequenceResponse); TerminateSequenceResponseAction = dictionary.Add(Wsrm11Strings.TerminateSequenceResponseAction); UsesSequenceSSL = dictionary.Add(Wsrm11Strings.UsesSequenceSSL); UsesSequenceSTR = dictionary.Add(Wsrm11Strings.UsesSequenceSTR); WsrmRequired = dictionary.Add(Wsrm11Strings.WsrmRequired); } } internal static class AtomicTransactionExternal11Strings { // dictionary strings public const string Namespace = "http://docs.oasis-open.org/ws-tx/wsat/2006/06"; public const string CompletionUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Completion"; public const string Durable2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Durable2PC"; public const string Volatile2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Volatile2PC"; public const string CommitAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Commit"; public const string RollbackAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Rollback"; public const string CommittedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Committed"; public const string AbortedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Aborted"; public const string PrepareAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepare"; public const string PreparedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepared"; public const string ReadOnlyAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/ReadOnly"; public const string ReplayAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Replay"; public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/fault"; public const string UnknownTransaction = "UnknownTransaction"; } internal static class CoordinationExternal11Strings { // dictionary strings public const string Namespace = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06"; public const string CreateCoordinationContextAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContext"; public const string CreateCoordinationContextResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContextResponse"; public const string RegisterAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/Register"; public const string RegisterResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/RegisterResponse"; public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/fault"; public const string CannotCreateContext = "CannotCreateContext"; public const string CannotRegisterParticipant = "CannotRegisterParticipant"; } internal static class SecureConversationDec2005Strings { // dictionary strings public const string SecurityContextToken = "SecurityContextToken"; public const string AlgorithmAttribute = "Algorithm"; public const string Generation = "Generation"; public const string Label = "Label"; public const string Offset = "Offset"; public const string Properties = "Properties"; public const string Identifier = "Identifier"; public const string Cookie = "Cookie"; public const string RenewNeededFaultCode = "RenewNeeded"; public const string BadContextTokenFaultCode = "BadContextToken"; public const string Prefix = "sc"; public const string DerivedKeyTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk"; public const string SecurityContextTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct"; public const string SecurityContextTokenReferenceValueType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct"; public const string RequestSecurityContextIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT"; public const string RequestSecurityContextIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT"; public const string RequestSecurityContextRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Renew"; public const string RequestSecurityContextRenewResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Renew"; public const string RequestSecurityContextClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Cancel"; public const string RequestSecurityContextCloseResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Cancel"; public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512"; public const string DerivedKeyToken = "DerivedKeyToken"; public const string Nonce = "Nonce"; public const string Length = "Length"; public const string Instance = "Instance"; } internal static class SecurityAlgorithmDec2005Strings { // dictionary strings public const string Psha1KeyDerivationDec2005 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha1"; } internal static class TrustDec2005Strings { // dictionary strings public const string CombinedHashLabel = "AUTH-HASH"; public const string RequestSecurityTokenResponse = "RequestSecurityTokenResponse"; public const string TokenType = "TokenType"; public const string KeySize = "KeySize"; public const string RequestedTokenReference = "RequestedTokenReference"; public const string AppliesTo = "AppliesTo"; public const string Authenticator = "Authenticator"; public const string CombinedHash = "CombinedHash"; public const string BinaryExchange = "BinaryExchange"; public const string Lifetime = "Lifetime"; public const string RequestedSecurityToken = "RequestedSecurityToken"; public const string Entropy = "Entropy"; public const string RequestedProofToken = "RequestedProofToken"; public const string ComputedKey = "ComputedKey"; public const string RequestSecurityToken = "RequestSecurityToken"; public const string RequestType = "RequestType"; public const string Context = "Context"; public const string BinarySecret = "BinarySecret"; public const string Type = "Type"; public const string SpnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego"; public const string TlsnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego"; public const string Prefix = "trust"; public const string RequestSecurityTokenIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"; public const string RequestSecurityTokenIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Issue"; public const string RequestTypeIssue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue"; public const string AsymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/AsymmetricKey"; public const string SymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey"; public const string NonceBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce"; public const string Psha1ComputedKeyUri = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PSHA1"; public const string KeyType = "KeyType"; public const string SymmetricKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey"; public const string PublicKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey"; public const string Claims = "Claims"; public const string InvalidRequestFaultCode = "InvalidRequest"; public const string FailedAuthenticationFaultCode = "FailedAuthentication"; public const string UseKey = "UseKey"; public const string SignWith = "SignWith"; public const string EncryptWith = "EncryptWith"; public const string EncryptionAlgorithm = "EncryptionAlgorithm"; public const string CanonicalizationAlgorithm = "CanonicalizationAlgorithm"; public const string ComputedKeyAlgorithm = "ComputedKeyAlgorithm"; public const string RequestSecurityTokenResponseCollection = "RequestSecurityTokenResponseCollection"; public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512"; public const string BinarySecretClauseType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512#BinarySecret"; public const string RequestSecurityTokenCollectionIssuanceFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal"; public const string RequestSecurityTokenRenewal = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Renew"; public const string RequestSecurityTokenRenewalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Renew"; public const string RequestSecurityTokenCollectionRenewalFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/RenewFinal"; public const string RequestSecurityTokenCancellation = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Cancel"; public const string RequestSecurityTokenCancellationResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Cancel"; public const string RequestSecurityTokenCollectionCancellationFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/CancelFinal"; public const string RequestTypeRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew"; public const string RequestTypeClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel"; public const string RenewTarget = "RenewTarget"; public const string CloseTarget = "CancelTarget"; public const string RequestedTokenClosed = "RequestedTokenCancelled"; public const string RequestedAttachedReference = "RequestedAttachedReference"; public const string RequestedUnattachedReference = "RequestedUnattachedReference"; public const string IssuedTokensHeader = "IssuedTokens"; public const string KeyWrapAlgorithm = "KeyWrapAlgorithm"; public const string BearerKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer"; public const string SecondaryParameters = "SecondaryParameters"; public const string Dialect = "Dialect"; public const string DialectType = "http://schemas.xmlsoap.org/ws/2005/05/identity"; } internal static class Wsrm11Strings { // dictionary strings public const string AckRequestedAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/AckRequested"; public const string CloseSequence = "CloseSequence"; public const string CloseSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequence"; public const string CloseSequenceResponse = "CloseSequenceResponse"; public const string CloseSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequenceResponse"; public const string CreateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequence"; public const string CreateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequenceResponse"; public const string DiscardFollowingFirstGap = "DiscardFollowingFirstGap"; public const string Endpoint = "Endpoint"; public const string FaultAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/fault"; public const string Final = "Final"; public const string IncompleteSequenceBehavior = "IncompleteSequenceBehavior"; public const string LastMsgNumber = "LastMsgNumber"; public const string MaxMessageNumber = "MaxMessageNumber"; public const string Namespace = "http://docs.oasis-open.org/ws-rx/wsrm/200702"; public const string NoDiscard = "NoDiscard"; public const string None = "None"; public const string SequenceAcknowledgementAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/SequenceAcknowledgement"; public const string SequenceClosed = "SequenceClosed"; public const string TerminateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequence"; public const string TerminateSequenceResponse = "TerminateSequenceResponse"; public const string TerminateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequenceResponse"; public const string UsesSequenceSSL = "UsesSequenceSSL"; public const string UsesSequenceSTR = "UsesSequenceSTR"; public const string WsrmRequired = "WsrmRequired"; // string constants public const string DiscardEntireSequence = "DiscardEntireSequence"; } }
using System; using System.Collections; using System.Drawing; using System.Timers; using System.Windows.Forms; namespace Skybound.VisualTips { internal class VisualTipTracker : System.Windows.Forms.IMessageFilter { private static System.Windows.Forms.Control _LastMouseEventControl; private static System.IntPtr _LastMouseEventHwnd; private static Skybound.VisualTips.VisualTipProvider _TrackingProvider; private static System.Collections.Hashtable ElapsedHandlers; private static Skybound.VisualTips.VisualTipTracker Instance; private static System.Timers.Timer TimeoutHandler; private static System.EventHandler TimeoutHandlerCallback; private static System.Collections.Hashtable Timers; private static System.Windows.Forms.Control TimerSynchronizingObject; public static System.Windows.Forms.Control LastMouseEventControl { get { if (Skybound.VisualTips.VisualTipTracker._LastMouseEventControl != null) return Skybound.VisualTips.VisualTipTracker._LastMouseEventControl; Skybound.VisualTips.VisualTipTracker._LastMouseEventControl = System.Windows.Forms.Control.FromHandle(Skybound.VisualTips.VisualTipTracker._LastMouseEventHwnd); return System.Windows.Forms.Control.FromHandle(Skybound.VisualTips.VisualTipTracker._LastMouseEventHwnd); } } public static Skybound.VisualTips.VisualTipProvider TrackingProvider { get { return Skybound.VisualTips.VisualTipTracker._TrackingProvider; } set { Skybound.VisualTips.VisualTipTracker._TrackingProvider = value; } } private VisualTipTracker() { } static VisualTipTracker() { Skybound.VisualTips.VisualTipTracker.ElapsedHandlers = new System.Collections.Hashtable(); Skybound.VisualTips.VisualTipTracker.Timers = new System.Collections.Hashtable(); } bool System.Windows.Forms.IMessageFilter.PreFilterMessage(ref System.Windows.Forms.Message m) { if (m.Msg == 512) { Skybound.VisualTips.VisualTipTracker.ResetTimers(); Skybound.VisualTips.VisualTipTracker._LastMouseEventHwnd = m.HWnd; Skybound.VisualTips.VisualTipTracker._LastMouseEventControl = null; } else if (((m.Msg != 675) && (m.Msg != 513)) || Skybound.VisualTips.VisualTipTracker._LastMouseEventHwnd == m.HWnd) { Skybound.VisualTips.VisualTipTracker._LastMouseEventHwnd = System.IntPtr.Zero; Skybound.VisualTips.VisualTipTracker._LastMouseEventControl = null; } if (Skybound.VisualTips.VisualTipTracker.TrackingProvider == null) goto label_1; switch (m.Msg) { case 512: System.IntPtr intPtr1 = m.LParam; System.Drawing.Point point = new System.Drawing.Point(intPtr1.ToInt32()); Skybound.VisualTips.VisualTipTracker.TrackingProvider.TrackMouseMove(new System.Windows.Forms.MouseEventArgs(System.Windows.Forms.Control.MouseButtons, 0, point.X, point.Y, 0)); break; case 513: case 514: Skybound.VisualTips.VisualTipTracker.TrackingProvider.TrackMouseDownUp(); break; case 675: Skybound.VisualTips.VisualTipTracker.TrackingProvider.TrackMouseLeave(System.EventArgs.Empty); break; case 256: System.IntPtr intPtr2 = m.WParam; System.Windows.Forms.KeyEventArgs keyEventArgs = new System.Windows.Forms.KeyEventArgs((System.Windows.Forms.Keys)intPtr2.ToInt32()); Skybound.VisualTips.VisualTipTracker.TrackingProvider.TrackKeyDown(keyEventArgs); return keyEventArgs.Handled; break; } label_1: if (m.Msg == 512) { Skybound.VisualTips.VisualTipTracker.ResetTimers(); } else if ((m.Msg == 256) && (Skybound.VisualTips.VisualTipProvider.WindowStack.Count > 0)) { System.IntPtr intPtr3 = m.WParam; return Skybound.VisualTips.VisualTipProvider.WindowStack.ProcessKeyDown((System.Windows.Forms.Keys)intPtr3.ToInt32()); } return false; } public static void AddHandler(int duration, System.EventHandler elapsed) { if (Skybound.VisualTips.VisualTipTracker.TimerSynchronizingObject == null) { Skybound.VisualTips.VisualTipTracker.TimerSynchronizingObject = new System.Windows.Forms.Control(); Skybound.VisualTips.VisualTipTracker.TimerSynchronizingObject.CreateControl(); } System.EventHandler eventHandler = (System.EventHandler)Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration]; if (eventHandler == null) { System.Timers.Timer timer = new System.Timers.Timer(); timer.SynchronizingObject = Skybound.VisualTips.VisualTipTracker.TimerSynchronizingObject; timer.Interval = (double)duration; timer.Elapsed += new System.Timers.ElapsedEventHandler(Skybound.VisualTips.VisualTipTracker.timer_Elapsed); timer.Start(); Skybound.VisualTips.VisualTipTracker.Timers[duration] = timer; Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration] = elapsed; return; } Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration] = (System.EventHandler)System.Delegate.Combine(eventHandler, elapsed); } public static void Disable() { if (Skybound.VisualTips.VisualTipTracker.Instance != null) { System.Windows.Forms.Application.RemoveMessageFilter(Skybound.VisualTips.VisualTipTracker.Instance); Skybound.VisualTips.VisualTipTracker.Instance = null; } } public static void Enable() { if (Skybound.VisualTips.VisualTipTracker.Instance == null) { Skybound.VisualTips.VisualTipTracker.Instance = new Skybound.VisualTips.VisualTipTracker(); System.Windows.Forms.Application.AddMessageFilter(new Skybound.VisualTips.VisualTipTracker()); } } public static void RemoveHandler(int duration, System.EventHandler elapsed) { System.EventHandler eventHandler = (System.EventHandler)Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration]; if (eventHandler != null) Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration] = (System.EventHandler)System.Delegate.Remove(eventHandler, elapsed); if (Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[duration] == null) { System.Timers.Timer timer = Skybound.VisualTips.VisualTipTracker.Timers[duration] as System.Timers.Timer; if (timer != null) { Skybound.VisualTips.VisualTipTracker.Timers[duration] = null; timer.Dispose(); } } } private static void ResetTimers() { if ((Skybound.VisualTips.VisualTipTracker.Timers != null) && (Skybound.VisualTips.VisualTipTracker.Timers.Values != null)) { foreach (System.Timers.Timer timer in Skybound.VisualTips.VisualTipTracker.Timers.Values) { if (timer != null) { timer.Stop(); timer.Start(); } } } } public static void SetTimeoutHandler(int duration, System.EventHandler callback) { lock (typeof(Skybound.VisualTips.VisualTipTracker)) { Skybound.VisualTips.VisualTipTracker.TimeoutHandlerCallback = callback; if (Skybound.VisualTips.VisualTipTracker.TimeoutHandler == null) { Skybound.VisualTips.VisualTipTracker.TimeoutHandler = new System.Timers.Timer(); Skybound.VisualTips.VisualTipTracker.TimeoutHandler.SynchronizingObject = Skybound.VisualTips.VisualTipTracker.TimerSynchronizingObject; } else { Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Stop(); } Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Interval = (double)duration; Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Elapsed += new System.Timers.ElapsedEventHandler(Skybound.VisualTips.VisualTipTracker.TimeoutHandler_Elapsed); Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Start(); } } private static void TimeoutHandler_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Enabled) { Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Stop(); Skybound.VisualTips.VisualTipTracker.TimeoutHandler.Elapsed -= new System.Timers.ElapsedEventHandler(Skybound.VisualTips.VisualTipTracker.TimeoutHandler_Elapsed); if (Skybound.VisualTips.VisualTipTracker.TimeoutHandlerCallback != null) Skybound.VisualTips.VisualTipTracker.TimeoutHandlerCallback(null, e); } } private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { System.EventHandler eventHandler = (System.EventHandler)Skybound.VisualTips.VisualTipTracker.ElapsedHandlers[(int)(sender as System.Timers.Timer).Interval]; if (eventHandler != null) eventHandler(null, e); } } // class VisualTipTracker }
// 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for FileOperations. /// </summary> public static partial class FileOperationsExtensions { /// <summary> /// Deletes the specified task file from the compute node where the task ran. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to delete. /// </param> /// <param name='fileName'> /// The path to the task file that you want to delete. /// </param> /// <param name='recursive'> /// Whether to delete children of a directory. If the fileName parameter /// represents a directory instead of a file, you can set Recursive to true /// to delete the directory and all of the files and subdirectories in it. If /// Recursive is false then the directory must be empty or deletion will fail. /// </param> /// <param name='fileDeleteFromTaskOptions'> /// Additional parameters for the operation /// </param> public static FileDeleteFromTaskHeaders DeleteFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).DeleteFromTaskAsync(jobId, taskId, fileName, recursive, fileDeleteFromTaskOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified task file from the compute node where the task ran. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to delete. /// </param> /// <param name='fileName'> /// The path to the task file that you want to delete. /// </param> /// <param name='recursive'> /// Whether to delete children of a directory. If the fileName parameter /// represents a directory instead of a file, you can set Recursive to true /// to delete the directory and all of the files and subdirectories in it. If /// Recursive is false then the directory must be empty or deletion will fail. /// </param> /// <param name='fileDeleteFromTaskOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileDeleteFromTaskHeaders> DeleteFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, recursive, fileDeleteFromTaskOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Returns the content of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to retrieve. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the content of. /// </param> /// <param name='fileGetFromTaskOptions'> /// Additional parameters for the operation /// </param> public static System.IO.Stream GetFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).GetFromTaskAsync(jobId, taskId, fileName, fileGetFromTaskOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the content of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to retrieve. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the content of. /// </param> /// <param name='fileGetFromTaskOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.IO.Stream> GetFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, fileGetFromTaskOptions, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return _result.Body; } /// <summary> /// Gets the properties of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to get the properties of. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the properties of. /// </param> /// <param name='fileGetNodeFilePropertiesFromTaskOptions'> /// Additional parameters for the operation /// </param> public static FileGetNodeFilePropertiesFromTaskHeaders GetNodeFilePropertiesFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetNodeFilePropertiesFromTaskOptions fileGetNodeFilePropertiesFromTaskOptions = default(FileGetNodeFilePropertiesFromTaskOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).GetNodeFilePropertiesFromTaskAsync(jobId, taskId, fileName, fileGetNodeFilePropertiesFromTaskOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the properties of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose file you want to get the properties of. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the properties of. /// </param> /// <param name='fileGetNodeFilePropertiesFromTaskOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileGetNodeFilePropertiesFromTaskHeaders> GetNodeFilePropertiesFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetNodeFilePropertiesFromTaskOptions fileGetNodeFilePropertiesFromTaskOptions = default(FileGetNodeFilePropertiesFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetNodeFilePropertiesFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, fileGetNodeFilePropertiesFromTaskOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Deletes the specified task file from the compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node from which you want to delete the file. /// </param> /// <param name='fileName'> /// The path to the file that you want to delete. /// </param> /// <param name='recursive'> /// Whether to delete children of a directory. If the fileName parameter /// represents a directory instead of a file, you can set Recursive to true /// to delete the directory and all of the files and subdirectories in it. If /// Recursive is false then the directory must be empty or deletion will fail. /// </param> /// <param name='fileDeleteFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> public static FileDeleteFromComputeNodeHeaders DeleteFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).DeleteFromComputeNodeAsync(poolId, nodeId, fileName, recursive, fileDeleteFromComputeNodeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified task file from the compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node from which you want to delete the file. /// </param> /// <param name='fileName'> /// The path to the file that you want to delete. /// </param> /// <param name='recursive'> /// Whether to delete children of a directory. If the fileName parameter /// represents a directory instead of a file, you can set Recursive to true /// to delete the directory and all of the files and subdirectories in it. If /// Recursive is false then the directory must be empty or deletion will fail. /// </param> /// <param name='fileDeleteFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileDeleteFromComputeNodeHeaders> DeleteFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, recursive, fileDeleteFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Returns the content of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that contains the file. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the content of. /// </param> /// <param name='fileGetFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> public static System.IO.Stream GetFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).GetFromComputeNodeAsync(poolId, nodeId, fileName, fileGetFromComputeNodeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the content of the specified task file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that contains the file. /// </param> /// <param name='fileName'> /// The path to the task file that you want to get the content of. /// </param> /// <param name='fileGetFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.IO.Stream> GetFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, fileGetFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return _result.Body; } /// <summary> /// Gets the properties of the specified compute node file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that contains the file. /// </param> /// <param name='fileName'> /// The path to the compute node file that you want to get the properties of. /// </param> /// <param name='fileGetNodeFilePropertiesFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> public static FileGetNodeFilePropertiesFromComputeNodeHeaders GetNodeFilePropertiesFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetNodeFilePropertiesFromComputeNodeOptions fileGetNodeFilePropertiesFromComputeNodeOptions = default(FileGetNodeFilePropertiesFromComputeNodeOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).GetNodeFilePropertiesFromComputeNodeAsync(poolId, nodeId, fileName, fileGetNodeFilePropertiesFromComputeNodeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the properties of the specified compute node file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that contains the file. /// </param> /// <param name='fileName'> /// The path to the compute node file that you want to get the properties of. /// </param> /// <param name='fileGetNodeFilePropertiesFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileGetNodeFilePropertiesFromComputeNodeHeaders> GetNodeFilePropertiesFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetNodeFilePropertiesFromComputeNodeOptions fileGetNodeFilePropertiesFromComputeNodeOptions = default(FileGetNodeFilePropertiesFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetNodeFilePropertiesFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, fileGetNodeFilePropertiesFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Lists the files in a task's directory on its compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose files you want to list. /// </param> /// <param name='recursive'> /// Whether to list children of a directory. /// </param> /// <param name='fileListFromTaskOptions'> /// Additional parameters for the operation /// </param> public static IPage<NodeFile> ListFromTask(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).ListFromTaskAsync(jobId, taskId, recursive, fileListFromTaskOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the files in a task's directory on its compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobId'> /// The id of the job that contains the task. /// </param> /// <param name='taskId'> /// The id of the task whose files you want to list. /// </param> /// <param name='recursive'> /// Whether to list children of a directory. /// </param> /// <param name='fileListFromTaskOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NodeFile>> ListFromTaskAsync(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListFromTaskWithHttpMessagesAsync(jobId, taskId, recursive, fileListFromTaskOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the files in task directories on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node whose files you want to list. /// </param> /// <param name='recursive'> /// Whether to list children of a directory. /// </param> /// <param name='fileListFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> public static IPage<NodeFile> ListFromComputeNode(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).ListFromComputeNodeAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the files in task directories on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node whose files you want to list. /// </param> /// <param name='recursive'> /// Whether to list children of a directory. /// </param> /// <param name='fileListFromComputeNodeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NodeFile>> ListFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the files in a task's directory on its compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='fileListFromTaskNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<NodeFile> ListFromTaskNext(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).ListFromTaskNextAsync(nextPageLink, fileListFromTaskNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the files in a task's directory on its compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='fileListFromTaskNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NodeFile>> ListFromTaskNextAsync(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListFromTaskNextWithHttpMessagesAsync(nextPageLink, fileListFromTaskNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the files in task directories on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='fileListFromComputeNodeNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<NodeFile> ListFromComputeNodeNext(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions)) { return Task.Factory.StartNew(s => ((IFileOperations)s).ListFromComputeNodeNextAsync(nextPageLink, fileListFromComputeNodeNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the files in task directories on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='fileListFromComputeNodeNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NodeFile>> ListFromComputeNodeNextAsync(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListFromComputeNodeNextWithHttpMessagesAsync(nextPageLink, fileListFromComputeNodeNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Core; using Orleans.Statistics; namespace Orleans.Runtime { /// <summary> /// Snapshot of current runtime statistics for a silo /// </summary> [Serializable] public class SiloRuntimeStatistics { /// <summary> /// Total number of activations in a silo. /// </summary> public int ActivationCount { get; internal set; } /// <summary> /// Number of activations in a silo that have been recently used. /// </summary> public int RecentlyUsedActivationCount { get; internal set; } /// <summary> /// The size of the sending queue. /// </summary> public int SendQueueLength { get; internal set; } /// <summary> /// The size of the receiving queue. /// </summary> public int ReceiveQueueLength { get; internal set; } /// <summary> /// The CPU utilization. /// </summary> public float? CpuUsage { get; internal set; } /// <summary> /// The amount of memory available in the silo [bytes]. /// </summary> public float? AvailableMemory { get; internal set; } /// <summary> /// The used memory size. /// </summary> public long? MemoryUsage { get; internal set; } /// <summary> /// The total physical memory available [bytes]. /// </summary> public long? TotalPhysicalMemory { get; internal set; } /// <summary> /// Is this silo overloaded. /// </summary> public bool IsOverloaded { get; internal set; } /// <summary> /// The number of clients currently connected to that silo. /// </summary> public long ClientCount { get; internal set; } public long ReceivedMessages { get; internal set; } public long SentMessages { get; internal set; } /// <summary> /// The DateTime when this statistics was created. /// </summary> public DateTime DateTime { get; private set; } internal SiloRuntimeStatistics() { } internal SiloRuntimeStatistics( IMessageCenter messageCenter, int activationCount, int recentlyUsedActivationCount, IAppEnvironmentStatistics appEnvironmentStatistics, IHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions, DateTime dateTime) { ActivationCount = activationCount; RecentlyUsedActivationCount = recentlyUsedActivationCount; SendQueueLength = messageCenter.SendQueueLength; ReceiveQueueLength = messageCenter.ReceiveQueueLength; CpuUsage = hostEnvironmentStatistics.CpuUsage; AvailableMemory = hostEnvironmentStatistics.AvailableMemory; MemoryUsage = appEnvironmentStatistics.MemoryUsage; IsOverloaded = loadSheddingOptions.Value.LoadSheddingEnabled && this.CpuUsage > loadSheddingOptions.Value.LoadSheddingLimit; ClientCount = MessagingStatisticsGroup.ConnectedClientCount.GetCurrentValue(); TotalPhysicalMemory = hostEnvironmentStatistics.TotalPhysicalMemory; ReceivedMessages = MessagingStatisticsGroup.MessagesReceived.GetCurrentValue(); SentMessages = MessagingStatisticsGroup.MessagesSentTotal.GetCurrentValue(); DateTime = dateTime; } public override string ToString() { return "SiloRuntimeStatistics: " + $"ActivationCount={ActivationCount} " + $"RecentlyUsedActivationCount={RecentlyUsedActivationCount} " + $"SendQueueLength={SendQueueLength} " + $"ReceiveQueueLength={ReceiveQueueLength} " + $"CpuUsage={CpuUsage} " + $"AvailableMemory={AvailableMemory} " + $"MemoryUsage={MemoryUsage} " + $"IsOverloaded={IsOverloaded} " + $"ClientCount={ClientCount} " + $"TotalPhysicalMemory={TotalPhysicalMemory} " + $"DateTime={DateTime}"; } } /// <summary> /// Snapshot of current statistics for a given grain type. /// </summary> [Serializable] internal class GrainStatistic { /// <summary> /// The type of the grain for this GrainStatistic. /// </summary> public string GrainType { get; set; } /// <summary> /// Number of grains of a this type. /// </summary> public int GrainCount { get; set; } /// <summary> /// Number of activation of a agrain of this type. /// </summary> public int ActivationCount { get; set; } /// <summary> /// Number of silos that have activations of this grain type. /// </summary> public int SiloCount { get; set; } /// <summary> /// Returns the string representatio of this GrainStatistic. /// </summary> public override string ToString() { return string.Format("GrainStatistic: GrainType={0} NumSilos={1} NumGrains={2} NumActivations={3} ", GrainType, SiloCount, GrainCount, ActivationCount); } } /// <summary> /// Simple snapshot of current statistics for a given grain type on a given silo. /// </summary> [Serializable] public class SimpleGrainStatistic { /// <summary> /// The type of the grain for this SimpleGrainStatistic. /// </summary> public string GrainType { get; set; } /// <summary> /// The silo address for this SimpleGrainStatistic. /// </summary> public SiloAddress SiloAddress { get; set; } /// <summary> /// The number of activations of this grain type on this given silo. /// </summary> public int ActivationCount { get; set; } /// <summary> /// Returns the string representatio of this SimpleGrainStatistic. /// </summary> public override string ToString() { return string.Format("SimpleGrainStatistic: GrainType={0} Silo={1} NumActivations={2} ", GrainType, SiloAddress, ActivationCount); } } [Serializable] public class DetailedGrainStatistic { /// <summary> /// The type of the grain for this DetailedGrainStatistic. /// </summary> public string GrainType { get; set; } /// <summary> /// The silo address for this DetailedGrainStatistic. /// </summary> public SiloAddress SiloAddress { get; set; } /// <summary> /// Unique Id for the grain. /// </summary> public IGrainIdentity GrainIdentity { get; set; } /// <summary> /// The grains Category /// </summary> public string Category { get; set; } } [Serializable] internal class DetailedGrainReport { public GrainId Grain { get; set; } /// <summary>silo on which these statistics come from</summary> public SiloAddress SiloAddress { get; set; } /// <summary>silo on which these statistics come from</summary> public string SiloName { get; set; } /// <summary>activation addresses in the local directory cache</summary> public List<ActivationAddress> LocalCacheActivationAddresses { get; set; } /// <summary>activation addresses in the local directory.</summary> public List<ActivationAddress> LocalDirectoryActivationAddresses { get; set; } /// <summary>primary silo for this grain</summary> public SiloAddress PrimaryForGrain { get; set; } /// <summary>the name of the class that implements this grain.</summary> public string GrainClassTypeName { get; set; } /// <summary>activations on this silo</summary> public List<string> LocalActivations { get; set; } public override string ToString() { return string.Format(Environment.NewLine + "**DetailedGrainReport for grain {0} from silo {1} SiloAddress={2}" + Environment.NewLine + " LocalCacheActivationAddresses={3}" + Environment.NewLine + " LocalDirectoryActivationAddresses={4}" + Environment.NewLine + " PrimaryForGrain={5}" + Environment.NewLine + " GrainClassTypeName={6}" + Environment.NewLine + " LocalActivations:" + Environment.NewLine + "{7}." + Environment.NewLine, Grain.ToDetailedString(), // {0} SiloName, // {1} SiloAddress.ToLongString(), // {2} Utils.EnumerableToString(LocalCacheActivationAddresses), // {3} Utils.EnumerableToString(LocalDirectoryActivationAddresses),// {4} PrimaryForGrain, // {5} GrainClassTypeName, // {6} Utils.EnumerableToString(LocalActivations, // {7} str => string.Format(" {0}", str), "\n")); } } }
using System; /// <summary> /// System.Enum.IConvertibleToUint16(System.Type,IFormatProvider ) /// </summary> public class EnumIConvertibleToUint16 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert an enum of zero to Uint16"); try { color c1 = color.blue; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a system defined enum type"); try { Enum e2 = System.StringComparison.CurrentCultureIgnoreCase; UInt16 l2 = (e2 as IConvertible).ToUInt16(null); if (l2 != 1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an enum of Uint16.maxvalue to uint16"); try { color c1 = color.white; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != UInt16.MaxValue) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an enum of negative zero to Uint16 "); try { color c1 = color.red; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an enum of negative value to Uint16"); try { e_test e1 = e_test.itemA; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: Convert an enum of the value which is bigger than uint16.maxvalue to Uint16"); try { e_test e1 = e_test.itemB; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("103", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EnumIConvertibleToUint16 test = new EnumIConvertibleToUint16(); TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToUint16"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = 0, white = UInt16.MaxValue, red = -0, } enum e_test : long { itemA = -123, itemB = Int32.MaxValue, itemC = Int64.MaxValue, itemD = -0, } }
public static class GlobalMembersGdimageopenpolygon1 { #if __cplusplus #endif #define GD_H #define GD_MAJOR_VERSION #define GD_MINOR_VERSION #define GD_RELEASE_VERSION #define GD_EXTRA_VERSION //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext #define GDXXX_VERSION_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s) #define GDXXX_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s #define GDXXX_SSTR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION #define GD_VERSION_STRING #if _WIN32 || CYGWIN || _WIN32_WCE #if BGDWIN32 #if NONDLL #define BGD_EXPORT_DATA_PROT #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport) #define BGD_EXPORT_DATA_PROT #endif #endif #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport) #define BGD_EXPORT_DATA_PROT #endif #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_STDCALL __stdcall #define BGD_STDCALL #define BGD_EXPORT_DATA_IMPL #else #if HAVE_VISIBILITY #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #else #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #endif #define BGD_STDCALL #endif #if BGD_EXPORT_DATA_PROT_ConditionalDefinition1 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #else #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #endif #if __cplusplus #endif #if __cplusplus #endif #define GD_IO_H #if VMS #endif #if __cplusplus #endif #define gdMaxColors #define gdAlphaMax #define gdAlphaOpaque #define gdAlphaTransparent #define gdRedMax #define gdGreenMax #define gdBlueMax //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24) #define gdTrueColorGetAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16) #define gdTrueColorGetRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8) #define gdTrueColorGetGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF) #define gdTrueColorGetBlue #define gdEffectReplace #define gdEffectAlphaBlend #define gdEffectNormal #define gdEffectOverlay #define GD_TRUE #define GD_FALSE #define GD_EPSILON #define M_PI #define gdDashSize #define gdStyled #define gdBrushed #define gdStyledBrushed #define gdTiled #define gdTransparent #define gdAntiAliased //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate #define gdImageCreatePalette #define gdFTEX_LINESPACE #define gdFTEX_CHARMAP #define gdFTEX_RESOLUTION #define gdFTEX_DISABLE_KERNING #define gdFTEX_XSHOW #define gdFTEX_FONTPATHNAME #define gdFTEX_FONTCONFIG #define gdFTEX_RETURNFONTPATHNAME #define gdFTEX_Unicode #define gdFTEX_Shift_JIS #define gdFTEX_Big5 #define gdFTEX_Adobe_Custom //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b)) #define gdTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) #define gdTrueColorAlpha #define gdArc //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdPie gdArc #define gdPie #define gdChord #define gdNoFill #define gdEdged //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor) #define gdImageTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx) #define gdImageSX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy) #define gdImageSY //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal) #define gdImageColorsTotal //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)]) #define gdImageRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)]) #define gdImageGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)]) #define gdImageBlue //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)]) #define gdImageAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent) #define gdImageGetTransparent //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace) #define gdImageGetInterlaced //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)] #define gdImagePalettePixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)] #define gdImageTrueColorPixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x #define gdImageResolutionX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y #define gdImageResolutionY #define GD2_CHUNKSIZE #define GD2_CHUNKSIZE_MIN #define GD2_CHUNKSIZE_MAX #define GD2_VERS #define GD2_ID #define GD2_FMT_RAW #define GD2_FMT_COMPRESSED #define GD_FLIP_HORINZONTAL #define GD_FLIP_VERTICAL #define GD_FLIP_BOTH #define GD_CMP_IMAGE #define GD_CMP_NUM_COLORS #define GD_CMP_COLOR #define GD_CMP_SIZE_X #define GD_CMP_SIZE_Y #define GD_CMP_TRANSPARENT #define GD_CMP_BACKGROUND #define GD_CMP_INTERLACE #define GD_CMP_TRUECOLOR #define GD_RESOLUTION #if __cplusplus #endif #if __cplusplus #endif #define GDFX_H #if __cplusplus #endif #if __cplusplus #endif #if __cplusplus #endif #define GDHELPERS_H #if ! _WIN32_WCE #else #endif #if _WIN32 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) CRITICAL_SECTION x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) InitializeCriticalSection(&x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) DeleteCriticalSection(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) EnterCriticalSection(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) LeaveCriticalSection(&x) #define gdMutexUnlock #elif HAVE_PTHREAD //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) pthread_mutex_t x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) pthread_mutex_init(&x, 0) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) pthread_mutex_destroy(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) pthread_mutex_lock(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) pthread_mutex_unlock(&x) #define gdMutexUnlock #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) #define gdMutexUnlock #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5) #define DPCM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5) #define DPM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5) #define DPI2DPCM //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5) #define DPI2DPM #if __cplusplus #endif #define GDTEST_TOP_DIR #define GDTEST_STRING_MAX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEqualsToFile //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageFileEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEquals //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond)) #define gdTestAssert //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__) #define gdTestErrorMsg static int Main() { gdImageStruct im; int white; int black; int r; gdPoint points; im = gd.gdImageCreate(100, 100); if (im == null) Environment.Exit(1); white = gd.gdImageColorAllocate(im, 0xff, 0xff, 0xff); black = gd.gdImageColorAllocate(im, 0, 0, 0); gd.gdImageFilledRectangle(im, 0, 0, 99, 99, white); //C++ TO C# CONVERTER TODO TASK: The memory management function 'calloc' has no equivalent in C#: points = (gdPoint)calloc(3, sizeof(gdPoint)); if (points == null) { gd.gdImageDestroy(im); Environment.Exit(1); } points[0].x = 10; points[0].y = 10; gd.gdImageOpenPolygon(im, points, 1, black); //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro: r = GlobalMembersGdtest.gd.gdTestImageCompareToFile(__FILE__, __LINE__, null, (DefineConstants.GDTEST_TOP_DIR "/gdimageopenpolygon/gdimageopenpolygon1.png"), (im)); //C++ TO C# CONVERTER TODO TASK: The memory management function 'free' has no equivalent in C#: free(points); gd.gdImageDestroy(im); if (r == 0) Environment.Exit(1); return EXIT_SUCCESS; } }
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Windows.Forms; using System.Threading; using System.ComponentModel; namespace OnlabNeuralis { class SerialComm { SerialPort serial; TextBox textbox; public StringBuilder readText; bool can_read; bool[] acknowledge_mode; byte lastCommandByte; public bool lastCommandReturned; public bool LastCommandReturned { get { return lastCommandReturned; } } public const byte MOTOR_OFORWARD = 0x64; //left speed right speed public const byte MOTOR_CFORWARD = 0x67; //left speed right speed left distance right distance public const byte MOTOR_LFORWARD = 0x66; //speed distance public const byte MOTOR_RFORWARD = 0x65; //speed distance public const byte MOTOR_STOP = 0x63; // public const byte MOTOR_LSTOP = 0x62; // public const byte MOTOR_RSTOP = 0x61; //- public const byte MOTOR_GET_DIST = 0x71; //left distance right distance public const byte MOTOR_SET_HEAD_ANGLE = 0x68; //angle public const byte MOTOR_GET_HEAD_ANGLE = 0x78;//angle public const byte DISP_SET = 0x41; //display 1 display 2 display 3 4 LED public const byte DISP_DLS = 0x51; //display 1 display 2 display 3 LED & Switch public const byte DISP_BUTTONS = 0x52; //buttons public const byte DISP_TEMP = 0x53; //temperature public const byte SENSOR_COMP_LED_ON = 0x91; //threshold level status of 13 sensors public const byte SENSOR_COMP_LED_OFF = 0x92; //threshold level status of 13 sensors public const byte SENSOR_LEVEL_LED_ON = 0x93; //sensor ID sensor level public const byte SENSOR_LEVEL_LED_OFF = 0x94; //sensor ID sensor level public const byte SENSOR_DIFF_MES = 0x95; //sensor ID sensor level public const byte MOTOR_I2C_FORWARD = 0x69; //i2c closed control public const byte MOTOR_I2C_SET_PID_PARAMS = 0x6A; public const byte MOTOR_I2C_GET_PID_PARAMS = 0x6B; public const byte COMM_SET_ACKNOWLEDGE_MODE = 0x20; public SerialComm(string portname, TextBox textbox) { acknowledge_mode = new bool[16]; for (int i = 0; i < acknowledge_mode.Length; ++i) acknowledge_mode[i] = false; serial = new SerialPort(portname,38400,Parity.None,8,StopBits.One); serial.Open(); serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived); can_read = true; this.textbox = textbox; readText = new StringBuilder(); } void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (can_read) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string sss = serial.ReadExisting(); byte[] bytes = encoding.GetBytes(sss); readText.Append(sss); } } public void SendCommand(byte[] buf, byte address, bool waitForAnswer) { SendCommand(buf, address, waitForAnswer, 0); } public void SendCommand(byte[] buf, byte address, bool waitForAnswer, int bytesToRead) { lastCommandByte = buf[0]; lastCommandReturned = false; byte header = (byte)(((buf.Length - 1) % 8) + (waitForAnswer ? 1 : 0) * 8 + (address % 16) * 16); byte[] buf2 = new byte[buf.Length + 1]; buf2[0] = header; for (int i = 1; i < buf2.Length; ++i) { buf2[i] = buf[i - 1]; } while (serial.BytesToWrite > 0) { Thread.Sleep(1); } can_read = false; serial.Write(buf2,0,buf2.Length); textbox.AppendText(ByteArrayToHexString(buf2) + "\r\n"); if (acknowledge_mode[address] && !waitForAnswer) { int i = 0; while ((serial.BytesToRead < 2) && (i < 1000)) { Thread.Sleep(10); i += 1; } byte[] bb = new byte[2]; serial.Read(bb, 0, 2); if (bb[1] != lastCommandByte) { throw new Exception("Invalid or no acknowledge!"); } else { lastCommandReturned = true; } } if (waitForAnswer) { int i = 0; while ((serial.BytesToRead < bytesToRead) && (i < 100)) { Thread.Sleep(10); i += 1; } lastCommandReturned = true; } can_read = true; } private static string ByteArrayToHexString(byte[] buf) { string s = ""; foreach (byte b in buf) { s += String.Format("{0:x}", b) + " "; } return s; } public void Motor_OForward(byte address, byte leftSpeed, byte rightSpeed) { SendCommand(new byte[] { MOTOR_OFORWARD, leftSpeed, rightSpeed }, address, false); } public void Motor_CForward(byte address, byte leftSpeed, byte rightSpeed) { SendCommand(new byte[] { MOTOR_CFORWARD, leftSpeed, rightSpeed }, address, false); } public void Motor_CForward(byte address, byte leftSpeed, byte rightSpeed, short leftDistance, short rightDistance) { SendCommand(new byte[] { MOTOR_CFORWARD, leftSpeed, rightSpeed, (byte)(leftDistance/256), (byte)(leftDistance%256), (byte)(rightDistance/256), (byte)(rightDistance%256) }, address, false); } public void Motor_LForward(byte address, byte leftSpeed, short leftDistance) { SendCommand(new byte[] { MOTOR_LFORWARD, leftSpeed, (byte)(leftDistance / 256), (byte)(leftDistance % 256) }, address, false); } public void Motor_LForward(byte address, byte leftSpeed) { SendCommand(new byte[] { MOTOR_LFORWARD, leftSpeed}, address, false); } public void Motor_RForward(byte address, byte rightSpeed, short rightDistance) { SendCommand(new byte[] { MOTOR_RFORWARD, rightSpeed, (byte)(rightDistance / 256), (byte)(rightDistance % 256) }, address, false); } public void Motor_RForward(byte address, byte rightSpeed) { SendCommand(new byte[] { MOTOR_RFORWARD, rightSpeed }, address, false); } public void Motor_Stop(byte address) { SendCommand(new byte[] { MOTOR_STOP }, address, false); } public void Motor_I2C_Forward(byte address, byte leftSpeed, byte rightSpeed) { SendCommand(new byte[] { MOTOR_I2C_FORWARD, leftSpeed, rightSpeed }, address, false); } public void Motor_I2C_Forward(byte address, byte leftSpeed, byte rightSpeed, short leftDistance, short rightDistance) { SendCommand(new byte[] { MOTOR_I2C_FORWARD, leftSpeed, rightSpeed, (byte)(leftDistance/256), (byte)(leftDistance%256), (byte)(rightDistance/256), (byte)(rightDistance%256) }, address, false); } public void Motor_I2C_Set_Kp(byte address, float Kp) { byte code = 0; byte[] bb = BitConverter.GetBytes(Kp); SendCommand(new byte[] { MOTOR_I2C_SET_PID_PARAMS, code, bb[0], bb[1], bb[2], bb[3] }, address, false); } public float Motor_I2C_Get_Kp(byte address) { byte code = 0; SendCommand(new byte[] { MOTOR_I2C_GET_PID_PARAMS, code}, address, true, 7); byte[] bb = new byte[7]; serial.Read(bb, 0, 7); if ((bb[1] == MOTOR_I2C_GET_PID_PARAMS) && (bb[2] == code)) return BitConverter.ToSingle(bb, 3); else return float.NaN; } public void Motor_I2C_Set_Ki(byte address, float Ki) { byte code = 1; byte[] bb = BitConverter.GetBytes(Ki); SendCommand(new byte[] { MOTOR_I2C_SET_PID_PARAMS, code, bb[0], bb[1], bb[2], bb[3] }, address, false); } public float Motor_I2C_Get_Ki(byte address) { byte code = 1; SendCommand(new byte[] { MOTOR_I2C_GET_PID_PARAMS, code }, address, true, 7); byte[] bb = new byte[7]; serial.Read(bb, 0, 7); if ((bb[1] == MOTOR_I2C_GET_PID_PARAMS) && (bb[2] == code)) return BitConverter.ToSingle(bb, 3); else return float.NaN; } public void Motor_I2C_Set_Kd(byte address, float Kd) { byte code = 2; byte[] bb = BitConverter.GetBytes(Kd); SendCommand(new byte[] { MOTOR_I2C_SET_PID_PARAMS, code, bb[0], bb[1], bb[2], bb[3] }, address, false); } public float Motor_I2C_Get_Kd(byte address) { byte code = 2; SendCommand(new byte[] { MOTOR_I2C_GET_PID_PARAMS, code }, address, true, 7); byte[] bb = new byte[7]; serial.Read(bb, 0, 7); if ((bb[1] == MOTOR_I2C_GET_PID_PARAMS) && (bb[2] == code)) return BitConverter.ToSingle(bb, 3); else return float.NaN; } public void Motor_I2C_Set_Dt(byte address, float Dt) { byte code = 3; byte[] bb = BitConverter.GetBytes(Dt); SendCommand(new byte[] { MOTOR_I2C_SET_PID_PARAMS, code, bb[0], bb[1], bb[2], bb[3] }, address, false); } public float Motor_I2C_Get_Dt(byte address) { byte code = 3; SendCommand(new byte[] { MOTOR_I2C_GET_PID_PARAMS, code }, address, true, 7); byte[] bb = new byte[7]; serial.Read(bb, 0, 7); if ((bb[1] == MOTOR_I2C_GET_PID_PARAMS) && (bb[2] == code)) return BitConverter.ToSingle(bb, 3); else return float.NaN; } public void Comm_Set_Acknowledge(byte address, bool ack) { acknowledge_mode[address] = ack; SendCommand(new byte[] { COMM_SET_ACKNOWLEDGE_MODE, (byte)(ack?1:0) }, address, false); } public void Close() { serial.Close(); } } }
namespace RRLab.PhysiologyWorkbench.Daq { partial class MultiLaserFlashConfigurationControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param genotype="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.FilterWheelChooserControl = new RRLab.PhysiologyWorkbench.GUI.DeviceChooserControl(); this.label2 = new System.Windows.Forms.Label(); this.PostFlashCollectionTimeTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.PreFlashCollectionTimeTextBox = new System.Windows.Forms.TextBox(); this.LaserChooser = new RRLab.PhysiologyWorkbench.GUI.DeviceChooserControl(); this.CompactFilterWheelConfigurationControl = new RRLab.PhysiologyWorkbench.GUI.CompactFilterWheelConfigurationControl(); this.ProgramBindingSource = new System.Windows.Forms.BindingSource(this.components); this.ProtocolBindingSource = new System.Windows.Forms.BindingSource(this.components); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ProtocolBindingSource)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.FilterWheelChooserControl, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 4); this.tableLayoutPanel1.Controls.Add(this.PostFlashCollectionTimeTextBox, 1, 4); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 3); this.tableLayoutPanel1.Controls.Add(this.PreFlashCollectionTimeTextBox, 1, 3); this.tableLayoutPanel1.Controls.Add(this.LaserChooser, 0, 0); this.tableLayoutPanel1.Controls.Add(this.CompactFilterWheelConfigurationControl, 0, 2); this.tableLayoutPanel1.Controls.Add(this.label3, 0, 5); this.tableLayoutPanel1.Controls.Add(this.textBox1, 1, 5); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 7; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(263, 180); this.tableLayoutPanel1.TabIndex = 0; // // FilterWheelChooserControl // this.FilterWheelChooserControl.AutoSize = true; this.FilterWheelChooserControl.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.FilterWheelChooserControl.ChoiceLabel = "Filter Wheel"; this.tableLayoutPanel1.SetColumnSpan(this.FilterWheelChooserControl, 2); this.FilterWheelChooserControl.DataBindings.Add(new System.Windows.Forms.Binding("DeviceManager", this.ProgramBindingSource, "DeviceManager", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.FilterWheelChooserControl.DataBindings.Add(new System.Windows.Forms.Binding("SelectedDevice", this.ProtocolBindingSource, "FilterWheel", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.FilterWheelChooserControl.DeviceManager = null; this.FilterWheelChooserControl.DeviceType = typeof(RRLab.PhysiologyWorkbench.Devices.FilterWheelDevice); this.FilterWheelChooserControl.Dock = System.Windows.Forms.DockStyle.Fill; this.FilterWheelChooserControl.Location = new System.Drawing.Point(3, 34); this.FilterWheelChooserControl.MinimumSize = new System.Drawing.Size(200, 25); this.FilterWheelChooserControl.Name = "FilterWheelChooserControl"; this.FilterWheelChooserControl.SelectedDevice = null; this.FilterWheelChooserControl.Size = new System.Drawing.Size(257, 25); this.FilterWheelChooserControl.TabIndex = 9; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(3, 119); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(95, 26); this.label2.TabIndex = 1; this.label2.Text = "PostFlash (ms)"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // PostFlashCollectionTimeTextBox // this.PostFlashCollectionTimeTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ProtocolBindingSource, "PostFlashCollectionTime", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "N0")); this.PostFlashCollectionTimeTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PostFlashCollectionTimeTextBox.Location = new System.Drawing.Point(104, 122); this.PostFlashCollectionTimeTextBox.Name = "PostFlashCollectionTimeTextBox"; this.PostFlashCollectionTimeTextBox.Size = new System.Drawing.Size(156, 20); this.PostFlashCollectionTimeTextBox.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(3, 93); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(95, 26); this.label1.TabIndex = 0; this.label1.Text = "PreFlash (ms)"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // PreFlashCollectionTimeTextBox // this.PreFlashCollectionTimeTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ProtocolBindingSource, "PreFlashCollectionTime", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "N0")); this.PreFlashCollectionTimeTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PreFlashCollectionTimeTextBox.Location = new System.Drawing.Point(104, 96); this.PreFlashCollectionTimeTextBox.Name = "PreFlashCollectionTimeTextBox"; this.PreFlashCollectionTimeTextBox.Size = new System.Drawing.Size(156, 20); this.PreFlashCollectionTimeTextBox.TabIndex = 2; // // LaserChooser // this.LaserChooser.AutoSize = true; this.LaserChooser.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.LaserChooser.ChoiceLabel = "Laser"; this.tableLayoutPanel1.SetColumnSpan(this.LaserChooser, 2); this.LaserChooser.DataBindings.Add(new System.Windows.Forms.Binding("DeviceManager", this.ProgramBindingSource, "DeviceManager", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.LaserChooser.DataBindings.Add(new System.Windows.Forms.Binding("SelectedDevice", this.ProtocolBindingSource, "Laser", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.LaserChooser.DeviceManager = null; this.LaserChooser.DeviceType = typeof(RRLab.PhysiologyWorkbench.Devices.SpectraPhysicsNitrogenLaser); this.LaserChooser.Dock = System.Windows.Forms.DockStyle.Fill; this.LaserChooser.Location = new System.Drawing.Point(3, 3); this.LaserChooser.MinimumSize = new System.Drawing.Size(200, 25); this.LaserChooser.Name = "LaserChooser"; this.LaserChooser.SelectedDevice = null; this.LaserChooser.Size = new System.Drawing.Size(257, 25); this.LaserChooser.TabIndex = 7; this.LaserChooser.SelectedDeviceChanged += new System.EventHandler(this.OnSelectedLaserChanged); // // CompactFilterWheelConfigurationControl // this.CompactFilterWheelConfigurationControl.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this.CompactFilterWheelConfigurationControl, 2); this.CompactFilterWheelConfigurationControl.DataBindings.Add(new System.Windows.Forms.Binding("FilterWheel", this.ProtocolBindingSource, "FilterWheel", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.CompactFilterWheelConfigurationControl.Dock = System.Windows.Forms.DockStyle.Fill; this.CompactFilterWheelConfigurationControl.FilterWheel = null; this.CompactFilterWheelConfigurationControl.Location = new System.Drawing.Point(3, 65); this.CompactFilterWheelConfigurationControl.MinimumSize = new System.Drawing.Size(0, 25); this.CompactFilterWheelConfigurationControl.Name = "CompactFilterWheelConfigurationControl"; this.CompactFilterWheelConfigurationControl.Size = new System.Drawing.Size(257, 25); this.CompactFilterWheelConfigurationControl.TabIndex = 10; // // ProgramBindingSource // this.ProgramBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.PhysiologyWorkbenchProgram); // // ProtocolBindingSource // this.ProtocolBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Daq.MultiFlashProtocol); // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(3, 145); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(95, 26); this.label3.TabIndex = 11; this.label3.Text = "Number of Flashes"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // textBox1 // this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ProtocolBindingSource, "NumberOfFlashes", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox1.Location = new System.Drawing.Point(104, 148); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(156, 20); this.textBox1.TabIndex = 12; // // MultiLaserFlashConfigurationControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.tableLayoutPanel1); this.Name = "MultiLaserFlashConfigurationControl"; this.Size = new System.Drawing.Size(263, 180); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ProtocolBindingSource)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TextBox PostFlashCollectionTimeTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox PreFlashCollectionTimeTextBox; private RRLab.PhysiologyWorkbench.GUI.DeviceChooserControl LaserChooser; private RRLab.PhysiologyWorkbench.GUI.DeviceChooserControl FilterWheelChooserControl; private System.Windows.Forms.BindingSource ProtocolBindingSource; private System.Windows.Forms.BindingSource ProgramBindingSource; private RRLab.PhysiologyWorkbench.GUI.CompactFilterWheelConfigurationControl CompactFilterWheelConfigurationControl; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox1; } }
using System; namespace ASMMath { public class Matrix { public double[,] m_MatArr; private int m_Rows,m_Cols; //****************************Constructors************************ public Matrix() { m_MatArr = new double[2,2]; m_Rows = 2; m_Cols = 2; } public Matrix(int rows,int cols) { if(rows>0 && cols>0) { m_MatArr = new double[rows,cols]; m_Rows = rows; m_Cols = cols; } else{ throw new Exception("Rows and Columns must be greater than 0."); } } public Matrix(int rowscols) { if(rowscols>0) { m_MatArr = new double[rowscols,rowscols]; m_Rows = rowscols; m_Cols = rowscols; } else { throw new Exception("Rows and Columns must be greater than 0."); } } //***************************************************************** //*************************Properties****************************** public int Rows{ get{ return m_Rows; } } public int Columns { get { return m_Cols; } } public int Size{ get { return m_Cols * m_Rows; } } public bool SquareMatrix{ get { if (Rows == Columns)return true; return false; } } //**************************************************************** //****************************Methods***************************** public void Initialize(){ Initialize(0); } public void Initialize(double iValue){ for (int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) m_MatArr[rw,cl] = iValue; } public void SetValue(int row,int column,double Value){ if (row>0 && row<=Rows && column>0 && column<=Columns) { m_MatArr[row-1,column-1]= Value; } else{ throw new Exception("Index out of bounds."); } } public double GetValue(int row,int column) { if (row>0 && row<=Rows && column>0 && column<=Columns) { return m_MatArr[row-1,column-1]; } else { throw new Exception("Index out of bounds."); } } public void Transpose(){ double[,] tempArr = new double[Columns,Rows]; for(int rw=0;rw<Columns;rw++) for(int cl=0;cl<Rows;cl++) tempArr[rw,cl] = m_MatArr[cl,rw]; m_MatArr = tempArr; int temp = m_Rows; m_Rows = m_Cols; m_Cols = temp; } public Matrix ReturnTranspose(){ Matrix tempMat = new Matrix(Rows,Columns); tempMat.CopyMatrix(this); tempMat.Transpose(); return tempMat; } public void CopyMatrix(Matrix sMat){ if(Rows == sMat.Rows && Columns == sMat.Columns) { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) m_MatArr[rw,cl] = sMat.m_MatArr[rw,cl]; } else { throw new Exception ("Number of Rows and Columns must be equal."); } } public Matrix ReturnClone() { Matrix temp = new Matrix(this.Rows,this.Columns); temp.CopyMatrix(this); return temp; } public Matrix ReturnNegative(){ Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = -m_MatArr[rw,cl]; return temp; } public Matrix ReturnSquareRoot() { Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Sqrt(m_MatArr[rw,cl]); return temp; } public void SquareRoot() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) m_MatArr[rw,cl] = Math.Sqrt(m_MatArr[rw,cl]); } public Matrix EliminateRC(int row,int col) { if (Rows > 1 && Columns>1 && row>0 && row<=Rows && col>0 && col<=Columns) { Matrix temp = new Matrix(Rows-1,Columns-1); row--;col--; int rwt=0,clt; for(int rw=0;rw<Rows;rw++) if(rw!=row) { clt=0; for(int cl=0;cl<Columns;cl++) if(cl!=col) { temp.m_MatArr[rwt,clt] = m_MatArr[rw,cl]; clt++; } rwt++; } return temp; } else{ return this; } } public Matrix ReturnSin(){ Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Sin(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnCos() { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Cos(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnTan() { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Tan(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnArcSin() { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Asin(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnArcCos() { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Acos(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnArcTan() { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) temp.m_MatArr[rw,cl] = Math.Atan(this.m_MatArr[rw,cl]); return temp; } public Matrix ReturnAdjoint(){ if(SquareMatrix == true) { if(Columns>1) { Matrix temp =new Matrix(Rows,Columns); for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) { Matrix temp2=EliminateRC(rw+1,cl+1); temp.m_MatArr[rw,cl] = Math.Pow(-1,rw+cl) * FindDeterminant(temp2); } temp.Transpose(); return temp; } else{ return this.ReturnClone(); } } else{ throw new Exception("Only applicable to square Matrix."); } } public void Cos() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Cos(this.m_MatArr[rw,cl]); } public void Sin() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Sin(this.m_MatArr[rw,cl]); } public void Tan() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Tan(this.m_MatArr[rw,cl]); } public void ArcCos() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Acos(this.m_MatArr[rw,cl]); } public void ArcSin() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Asin(this.m_MatArr[rw,cl]); } public void ArcTan() { for(int rw=0;rw<Rows;rw++) for(int cl=0;cl<Columns;cl++) this.m_MatArr[rw,cl] = Math.Atan(this.m_MatArr[rw,cl]); } public string Display(){ string temp="\r\n"; for(int rw=0;rw<Rows;rw++){ for(int cl=0;cl<Columns;cl++) temp = temp + m_MatArr[rw,cl] + " "; temp += "\r\n"; } return temp; } public static Matrix NewIdentityMatrix(int rowcols){ Matrix temp = new Matrix(rowcols); for(int a=0;a<rowcols;a++) temp.m_MatArr[a,a] = 1; return temp; } public static double FindDeterminant(Matrix Mat) { if (Mat.SquareMatrix == true) { if (Mat.Columns==1) { return Mat.m_MatArr[0,0]; } else { double tvar=0; for(int cl=0;cl<Mat.Columns;cl++){ Matrix temp = Mat.EliminateRC(1,cl+1); tvar+=(Math.Pow(-1,cl)*Mat.m_MatArr[0,cl]*FindDeterminant(temp)); } return tvar; } } else { Console.Error.WriteLine("Only applicable to square Matrix."); return 0; } } public byte[] GetBytes(){ byte[] temp = new byte[Buffer.ByteLength(m_MatArr)]; Buffer.BlockCopy(m_MatArr,0,temp,0,Buffer.ByteLength(m_MatArr)); return temp; } public void SetBytes(byte[] bytedata){ Buffer.BlockCopy(bytedata,0,m_MatArr,0,Buffer.ByteLength(m_MatArr)); } public Matrix ReturnInvExp(double Value){ Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = System.Math.Pow(Value,this.m_MatArr[rw,cl]); return temp; } public void InvExp(double Value) { for(int rw=0;rw<this.Rows;rw++) for(int cl=0;cl<this.Columns;cl++) this.m_MatArr[rw,cl] = System.Math.Pow(Value,this.m_MatArr[rw,cl]); } public Matrix ReturnInvMod(double Value) { Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = Value % this.m_MatArr[rw,cl]; return temp; } public void InvMod(double Value) { for(int rw=0;rw<this.Rows;rw++) for(int cl=0;cl<this.Columns;cl++) this.m_MatArr[rw,cl] = Value % this.m_MatArr[rw,cl]; } public Matrix ReturnInvSub(double Value) { Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = Value - this.m_MatArr[rw,cl]; return temp; } public void InvSub(double Value) { for(int rw=0;rw<this.Rows;rw++) for(int cl=0;cl<this.Columns;cl++) this.m_MatArr[rw,cl] = Value - this.m_MatArr[rw,cl]; } public Matrix ReturnInvDiv(double Value) { Matrix temp = new Matrix(this.Rows,this.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = Value / this.m_MatArr[rw,cl]; return temp; } public void InvDiv(double Value) { for(int rw=0;rw<this.Rows;rw++) for(int cl=0;cl<this.Columns;cl++) this.m_MatArr[rw,cl] = Value / this.m_MatArr[rw,cl]; } //**************************************************************** //******************************Overloaded Operators********************* public static Matrix operator+(Matrix lMat,Matrix rMat) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); if(lMat.Rows == rMat.Rows && lMat.Columns == rMat.Columns) { for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] + rMat.m_MatArr[rw,cl]; } else{ throw new Exception("Two matrices should be equal in order to perform the operation."); } return temp; } public static Matrix operator+(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] + Value; return temp; } public static Matrix operator-(Matrix lMat,Matrix rMat) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); if(lMat.Rows == rMat.Rows && lMat.Columns == rMat.Columns) { for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] - rMat.m_MatArr[rw,cl]; } else { throw new Exception("Two matrices should be equal in order to perform the operation."); } return temp; } public static Matrix operator-(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] - Value; return temp; } public static Matrix operator*(Matrix lMat,Matrix rMat) { if(lMat.Columns == rMat.Rows) { Matrix temp = new Matrix(lMat.Rows,rMat.Columns); temp.Initialize(); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) for(int cl2=0;cl2<lMat.Columns;cl2++) temp.m_MatArr[rw,cl] =temp.m_MatArr[rw,cl] + lMat.m_MatArr[rw,cl2] * rMat.m_MatArr[cl2,cl]; return temp; } else { throw new Exception("Number of Columns of Left Matrix must be equal to Rows of Right Matrix."); } } public static Matrix operator*(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] * Value; return temp; } public static Matrix operator/(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] / Value; return temp; } public static Matrix operator/(Matrix lMat,Matrix rMat) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); if(lMat.Rows == rMat.Rows && lMat.Columns == rMat.Columns) { for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] / rMat.m_MatArr[rw,cl]; } else { throw new Exception("Two matrices should be equal in order to perform the operation."); } return temp; } public static Matrix operator^(Matrix lMat,Matrix rMat) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); if(lMat.Rows == rMat.Rows && lMat.Columns == rMat.Columns) { for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = System.Math.Pow(lMat.m_MatArr[rw,cl],rMat.m_MatArr[rw,cl]); } else { throw new Exception("Two matrices should be equal in order to perform the operation."); } return temp; } public static Matrix operator^(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = System.Math.Pow(lMat.m_MatArr[rw,cl],Value); return temp; } public static Matrix operator%(Matrix lMat,Matrix rMat) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); if(lMat.Rows == rMat.Rows && lMat.Columns == rMat.Columns) { for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] % rMat.m_MatArr[rw,cl]; } else { throw new Exception("Two matrices should be equal in order to perform the operation."); } return temp; } public static Matrix operator%(Matrix lMat,double Value) { Matrix temp = new Matrix(lMat.Rows,lMat.Columns); for(int rw=0;rw<temp.Rows;rw++) for(int cl=0;cl<temp.Columns;cl++) temp.m_MatArr[rw,cl] = lMat.m_MatArr[rw,cl] % Value; return temp; } public static bool operator ==(Matrix lMat,Matrix rMat){ if(lMat.Rows != rMat.Rows || lMat.Columns != rMat.Columns)return false; for(int rw=0;rw<rMat.Rows;rw++) for(int cl=0;cl<rMat.Columns;cl++) if(lMat.m_MatArr[rw,cl]!= rMat.m_MatArr[rw,cl])return false; return true; } public static bool operator !=(Matrix lMat,Matrix rMat) { return !(lMat==rMat); } public static Matrix operator++(Matrix Mat) { for(int rw=0;rw<Mat.Rows;rw++) for(int cl=0;cl<Mat.Columns;cl++) Mat.m_MatArr[rw,cl]++; return Mat; } public static Matrix operator--(Matrix Mat) { for(int rw=0;rw<Mat.Rows;rw++) for(int cl=0;cl<Mat.Columns;cl++) Mat.m_MatArr[rw,cl]--; return Mat; } //**************************************************************** } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.Regions.Behaviors; using Microsoft.Practices.Prism.Composition.Tests.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Microsoft.Practices.Prism.Composition.Tests.Regions.Behaviors { [TestClass] public class RegionMemberLifetimeBehaviorFixture { protected Region Region { get; set; } protected RegionMemberLifetimeBehavior Behavior { get; set; } [TestInitialize] public void TestInitialize() { Arrange(); } protected virtual void Arrange() { this.Region = new Region(); this.Behavior = new RegionMemberLifetimeBehavior(); this.Behavior.Region = this.Region; this.Behavior.Attach(); } [TestMethod] public void WhenBehaviorAttachedThenReportsIsAttached() { Assert.IsTrue(Behavior.IsAttached); } [TestMethod] public void WhenIRegionMemberLifetimeItemReturnsKeepAliveFalseRemovesWhenInactive() { // Arrange var regionItemMock = new Mock<IRegionMemberLifetime>(); regionItemMock.Setup(i => i.KeepAlive).Returns(false); Region.Add(regionItemMock.Object); Region.Activate(regionItemMock.Object); // Act Region.Deactivate(regionItemMock.Object); // Assert Assert.IsFalse(Region.Views.Contains(regionItemMock.Object)); } [TestMethod] public void WhenIRegionMemberLifetimeItemReturnsKeepAliveTrueDoesNotRemoveOnDeactivation() { // Arrange var regionItemMock = new Mock<IRegionMemberLifetime>(); regionItemMock.Setup(i => i.KeepAlive).Returns(true); Region.Add(regionItemMock.Object); Region.Activate(regionItemMock.Object); // Act Region.Deactivate(regionItemMock.Object); // Assert Assert.IsTrue(Region.Views.Contains(regionItemMock.Object)); } [TestMethod] public void WhenRegionContainsMultipleMembers_OnlyRemovesThoseDeactivated() { // Arrange var firstMockItem = new Mock<IRegionMemberLifetime>(); firstMockItem.Setup(i => i.KeepAlive).Returns(true); var secondMockItem = new Mock<IRegionMemberLifetime>(); secondMockItem.Setup(i => i.KeepAlive).Returns(false); Region.Add(firstMockItem.Object); Region.Activate(firstMockItem.Object); Region.Add(secondMockItem.Object); Region.Activate(secondMockItem.Object); // Act Region.Deactivate(secondMockItem.Object); // Assert Assert.IsTrue(Region.Views.Contains(firstMockItem.Object)); Assert.IsFalse(Region.Views.Contains(secondMockItem.Object)); } [TestMethod] public void WhenMemberNeverActivatedThenIsNotRemovedOnAnothersDeactivation() { // Arrange var firstMockItem = new Mock<IRegionMemberLifetime>(); firstMockItem.Setup(i => i.KeepAlive).Returns(false); var secondMockItem = new Mock<IRegionMemberLifetime>(); secondMockItem.Setup(i => i.KeepAlive).Returns(false); Region.Add(firstMockItem.Object); // Never activated Region.Add(secondMockItem.Object); Region.Activate(secondMockItem.Object); // Act Region.Deactivate(secondMockItem.Object); // Assert Assert.IsTrue(Region.Views.Contains(firstMockItem.Object)); Assert.IsFalse(Region.Views.Contains(secondMockItem.Object)); } [TestMethod] public virtual void RemovesRegionItemIfDataContextReturnsKeepAliveFalse() { // Arrange var regionItemMock = new Mock<IRegionMemberLifetime>(); regionItemMock.Setup(i => i.KeepAlive).Returns(false); var regionItem = new MockFrameworkElement(); regionItem.DataContext = regionItemMock.Object; Region.Add(regionItem); Region.Activate(regionItem); // Act Region.Deactivate(regionItem); // Assert Assert.IsFalse(Region.Views.Contains(regionItem)); } [TestMethod] public virtual void RemovesOnlyDeactivatedItemsInRegionBasedOnDataContextKeepAlive() { // Arrange var retionItemDataContextToKeepAlive = new Mock<IRegionMemberLifetime>(); retionItemDataContextToKeepAlive.Setup(i => i.KeepAlive).Returns(true); var regionItemToKeepAlive = new MockFrameworkElement(); regionItemToKeepAlive.DataContext = retionItemDataContextToKeepAlive.Object; Region.Add(regionItemToKeepAlive); Region.Activate(regionItemToKeepAlive); var regionItemMock = new Mock<IRegionMemberLifetime>(); regionItemMock.Setup(i => i.KeepAlive).Returns(false); var regionItem = new MockFrameworkElement(); regionItem.DataContext = regionItemMock.Object; Region.Add(regionItem); Region.Activate(regionItem); // Act Region.Deactivate(regionItem); // Assert Assert.IsFalse(Region.Views.Contains(regionItem)); Assert.IsTrue(Region.Views.Contains(regionItemToKeepAlive)); } [TestMethod] public virtual void WillRemoveDeactivatedItemIfKeepAliveAttributeFalse() { // Arrange var regionItem = new RegionMemberNotKeptAlive(); Region.Add(regionItem); Region.Activate(regionItem); // Act Region.Deactivate(regionItem); // Assert Assert.IsFalse(Region.Views.Contains((object)regionItem)); } [TestMethod] public virtual void WillNotRemoveDeactivatedItemIfKeepAliveAttributeTrue() { // Arrange var regionItem = new RegionMemberKeptAlive(); Region.Add(regionItem); Region.Activate(regionItem); // Act Region.Deactivate(regionItem); // Assert Assert.IsTrue(Region.Views.Contains((object)regionItem)); } [TestMethod] public virtual void WillRemoveDeactivatedItemIfDataContextKeepAliveAttributeFalse() { // Arrange var regionItemDataContext = new RegionMemberNotKeptAlive(); var regionItem = new MockFrameworkElement() { DataContext = regionItemDataContext }; Region.Add(regionItem); Region.Activate(regionItem); // Act Region.Deactivate(regionItem); // Assert Assert.IsFalse(Region.Views.Contains(regionItem)); } [RegionMemberLifetime(KeepAlive = false)] public class RegionMemberNotKeptAlive { } [RegionMemberLifetime(KeepAlive = true)] public class RegionMemberKeptAlive { } } [TestClass] public class RegionMemberLifetimeBehaviorAgainstSingleActiveRegionFixture : RegionMemberLifetimeBehaviorFixture { protected override void Arrange() { this.Region = new SingleActiveRegion(); this.Behavior = new RegionMemberLifetimeBehavior(); this.Behavior.Region = this.Region; this.Behavior.Attach(); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) // Copyright (c) 2012-2013 Rotorz Limited. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using UnityEngine; using UnityEditor; using System; using Rotorz.ReorderableList; namespace Fungus.EditorUtils { public class CommandListAdaptor : IReorderableListAdaptor { protected SerializedProperty _arrayProperty; public float fixedItemHeight; public Rect nodeRect = new Rect(); public SerializedProperty this[int index] { get { return _arrayProperty.GetArrayElementAtIndex(index); } } public SerializedProperty arrayProperty { get { return _arrayProperty; } } public CommandListAdaptor(SerializedProperty arrayProperty, float fixedItemHeight) { if (arrayProperty == null) throw new ArgumentNullException("Array property was null."); if (!arrayProperty.isArray) throw new InvalidOperationException("Specified serialized propery is not an array."); this._arrayProperty = arrayProperty; this.fixedItemHeight = fixedItemHeight; } public CommandListAdaptor(SerializedProperty arrayProperty) : this(arrayProperty, 0f) { } public int Count { get { return _arrayProperty.arraySize; } } public virtual bool CanDrag(int index) { return true; } public virtual bool CanRemove(int index) { return true; } public void Add() { Command newCommand = AddNewCommand(); if (newCommand == null) { return; } int newIndex = _arrayProperty.arraySize; ++_arrayProperty.arraySize; _arrayProperty.GetArrayElementAtIndex(newIndex).objectReferenceValue = newCommand; } public void Insert(int index) { Command newCommand = AddNewCommand(); if (newCommand == null) { return; } _arrayProperty.InsertArrayElementAtIndex(index); _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue = newCommand; } Command AddNewCommand() { Flowchart flowchart = FlowchartWindow.GetFlowchart(); if (flowchart == null) { return null; } var block = flowchart.SelectedBlock; if (block == null) { return null; } var newCommand = Undo.AddComponent<Comment>(block.gameObject) as Command; newCommand.ItemId = flowchart.NextItemId(); flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(newCommand); return newCommand; } public void Duplicate(int index) { Command command = _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue as Command; // Add the command as a new component var parentBlock = command.GetComponent<Block>(); System.Type type = command.GetType(); Command newCommand = Undo.AddComponent(parentBlock.gameObject, type) as Command; newCommand.ItemId = newCommand.GetFlowchart().NextItemId(); System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(newCommand, field.GetValue(command)); } _arrayProperty.InsertArrayElementAtIndex(index); _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue = newCommand; } public void Remove(int index) { // Remove the Fungus Command component Command command = _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue as Command; if (command != null) { Undo.DestroyObjectImmediate(command); } _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue = null; _arrayProperty.DeleteArrayElementAtIndex(index); } public void Move(int sourceIndex, int destIndex) { if (destIndex > sourceIndex) --destIndex; _arrayProperty.MoveArrayElement(sourceIndex, destIndex); } public void Clear() { while (Count > 0) { Remove(0); } } public void BeginGUI() {} public void EndGUI() {} public void DrawItemBackground(Rect position, int index) { } public void DrawItem(Rect position, int index) { Command command = this[index].objectReferenceValue as Command; if (command == null) { return; } CommandInfoAttribute commandInfoAttr = CommandEditor.GetCommandInfo(command.GetType()); if (commandInfoAttr == null) { return; } var flowchart = (Flowchart)command.GetFlowchart(); if (flowchart == null) { return; } bool isComment = command.GetType() == typeof(Comment); bool isLabel = (command.GetType() == typeof(Label)); bool error = false; string summary = command.GetSummary(); if (summary == null) { summary = ""; } else { summary = summary.Replace("\n", "").Replace("\r", ""); } if (summary.StartsWith("Error:")) { error = true; } if (isComment || isLabel) { summary = "<b> " + summary + "</b>"; } else { summary = "<i>" + summary + "</i>"; } bool commandIsSelected = false; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (selectedCommand == command) { commandIsSelected = true; break; } } string commandName = commandInfoAttr.CommandName; GUIStyle commandLabelStyle = new GUIStyle(GUI.skin.box); commandLabelStyle.normal.background = FungusEditorResources.CommandBackground; int borderSize = 5; commandLabelStyle.border.top = borderSize; commandLabelStyle.border.bottom = borderSize; commandLabelStyle.border.left = borderSize; commandLabelStyle.border.right = borderSize; commandLabelStyle.alignment = TextAnchor.MiddleLeft; commandLabelStyle.richText = true; commandLabelStyle.fontSize = 11; commandLabelStyle.padding.top -= 1; float indentSize = 20; for (int i = 0; i < command.IndentLevel; ++i) { Rect indentRect = position; indentRect.x += i * indentSize - 21; indentRect.width = indentSize + 1; indentRect.y -= 2; indentRect.height += 5; GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 1f); GUI.Box(indentRect, "", commandLabelStyle); } float commandNameWidth = Mathf.Max(commandLabelStyle.CalcSize(new GUIContent(commandName)).x, 90f); float indentWidth = command.IndentLevel * indentSize; Rect commandLabelRect = position; commandLabelRect.x += indentWidth - 21; commandLabelRect.y -= 2; commandLabelRect.width -= (indentSize * command.IndentLevel - 22); commandLabelRect.height += 5; // There's a weird incompatibility between the Reorderable list control used for the command list and // the UnityEvent list control used in some commands. In play mode, if you click on the reordering grabber // for a command in the list it causes the UnityEvent list to spew null exception errors. // The workaround for now is to hide the reordering grabber from mouse clicks by extending the command // selection rectangle to cover it. We are planning to totally replace the command list display system. Rect clickRect = position; clickRect.x -= 20; clickRect.width += 20; // Select command via left click if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && clickRect.Contains(Event.current.mousePosition)) { if (flowchart.SelectedCommands.Contains(command) && Event.current.button == 0) { // Left click on already selected command // Command key and shift key is not pressed if (!EditorGUI.actionKey && !Event.current.shift) { BlockEditor.actionList.Add ( delegate { flowchart.SelectedCommands.Remove(command); flowchart.ClearSelectedCommands(); }); } // Command key pressed if (EditorGUI.actionKey) { BlockEditor.actionList.Add ( delegate { flowchart.SelectedCommands.Remove(command); }); Event.current.Use(); } } else { bool shift = Event.current.shift; // Left click and no command key if (!shift && !EditorGUI.actionKey && Event.current.button == 0) { BlockEditor.actionList.Add ( delegate { flowchart.ClearSelectedCommands(); }); Event.current.Use(); } BlockEditor.actionList.Add ( delegate { flowchart.AddSelectedCommand(command); }); // Find first and last selected commands int firstSelectedIndex = -1; int lastSelectedIndex = -1; if (flowchart.SelectedCommands.Count > 0) { if ( flowchart.SelectedBlock != null) { for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++) { Command commandInBlock = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (commandInBlock == selectedCommand) { firstSelectedIndex = i; break; } } } for (int i = flowchart.SelectedBlock.CommandList.Count - 1; i >=0; i--) { Command commandInBlock = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (commandInBlock == selectedCommand) { lastSelectedIndex = i; break; } } } } } if (shift) { int currentIndex = command.CommandIndex; if (firstSelectedIndex == -1 || lastSelectedIndex == -1) { // No selected command found - select entire list firstSelectedIndex = 0; lastSelectedIndex = currentIndex; } else { if (currentIndex < firstSelectedIndex) { firstSelectedIndex = currentIndex; } if (currentIndex > lastSelectedIndex) { lastSelectedIndex = currentIndex; } } for (int i = Math.Min(firstSelectedIndex, lastSelectedIndex); i < Math.Max(firstSelectedIndex, lastSelectedIndex); ++i) { var selectedCommand = flowchart.SelectedBlock.CommandList[i]; BlockEditor.actionList.Add ( delegate { flowchart.AddSelectedCommand(selectedCommand); }); } } Event.current.Use(); } GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus) } Color commandLabelColor = Color.white; if (flowchart.ColorCommands) { commandLabelColor = command.GetButtonColor(); } if (commandIsSelected) { commandLabelColor = Color.green; } else if (!command.enabled) { commandLabelColor = Color.grey; } else if (error) { // TODO: Show warning icon } GUI.backgroundColor = commandLabelColor; if (isComment) { GUI.Label(commandLabelRect, "", commandLabelStyle); } else { string commandNameLabel; if (flowchart.ShowLineNumbers) { commandNameLabel = command.CommandIndex.ToString() + ": " + commandName; } else { commandNameLabel = commandName; } GUI.Label(commandLabelRect, commandNameLabel, commandLabelStyle); } if (command.ExecutingIconTimer > Time.realtimeSinceStartup) { Rect iconRect = new Rect(commandLabelRect); iconRect.x += iconRect.width - commandLabelRect.width - 20; iconRect.width = 20; iconRect.height = 20; Color storeColor = GUI.color; float alpha = (command.ExecutingIconTimer - Time.realtimeSinceStartup) / FungusConstants.ExecutingIconFadeTime; alpha = Mathf.Clamp01(alpha); GUI.color = new Color(1f, 1f, 1f, alpha); GUI.Label(iconRect, FungusEditorResources.PlaySmall, new GUIStyle()); GUI.color = storeColor; } Rect summaryRect = new Rect(commandLabelRect); if (isComment) { summaryRect.x += 5; } else { summaryRect.x += commandNameWidth + 5; summaryRect.width -= commandNameWidth + 5; } GUIStyle summaryStyle = new GUIStyle(); summaryStyle.fontSize = 10; summaryStyle.padding.top += 5; summaryStyle.richText = true; summaryStyle.wordWrap = false; summaryStyle.clipping = TextClipping.Clip; commandLabelStyle.alignment = TextAnchor.MiddleLeft; GUI.Label(summaryRect, summary, summaryStyle); if (error) { GUISkin editorSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector); Rect errorRect = new Rect(summaryRect); errorRect.x += errorRect.width - 20; errorRect.y += 2; errorRect.width = 20; GUI.Label(errorRect, editorSkin.GetStyle("CN EntryError").normal.background); summaryRect.width -= 20; } GUI.backgroundColor = Color.white; } public virtual float GetItemHeight(int index) { return fixedItemHeight != 0f ? fixedItemHeight : EditorGUI.GetPropertyHeight(this[index], GUIContent.none, false) ; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Xml.Xsl.Qil; #if FEATURE_COMPILED_XSL using System.Xml.Xsl.IlGen; #endif using System.ComponentModel; using MS.Internal.Xml.XPath; using System.Runtime.Versioning; namespace System.Xml.Xsl.Runtime { /// <summary> /// XmlQueryRuntime is passed as the first parameter to all generated query methods. /// /// XmlQueryRuntime contains runtime support for generated ILGen queries: /// 1. Stack of output writers (stack handles nested document construction) /// 2. Manages list of all xml types that are used within the query /// 3. Manages list of all atomized names that are used within the query /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class XmlQueryRuntime { // Early-Bound Library Objects private XmlQueryContext _ctxt; private XsltLibrary _xsltLib; private EarlyBoundInfo[] _earlyInfo; private object[] _earlyObjects; // Global variables and parameters private string[] _globalNames; private object[] _globalValues; // Names, prefix mappings, and name filters private XmlNameTable _nameTableQuery; private string[] _atomizedNames; // Names after atomization private XmlNavigatorFilter[] _filters; // Name filters (contain atomized names) private StringPair[][] _prefixMappingsList; // Lists of prefix mappings (used to resolve computed names) // Xml types private XmlQueryType[] _types; // Collations private XmlCollation[] _collations; // Document ordering private DocumentOrderComparer _docOrderCmp; // Indexes private ArrayList[] _indexes; // Output construction private XmlQueryOutput _output; private Stack<XmlQueryOutput> _stkOutput; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { Debug.Assert(data != null); string[] names = data.Names; Int32Pair[] filters = data.Filters; WhitespaceRuleLookup wsRules; int i; // Early-Bound Library Objects wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; _ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); _xsltLib = null; _earlyInfo = data.EarlyBound; _earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null; // Global variables and parameters _globalNames = data.GlobalNames; _globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null; // Names _nameTableQuery = _ctxt.QueryNameTable; _atomizedNames = null; if (names != null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = _ctxt.DefaultNameTable; _atomizedNames = new string[names.Length]; if (nameTableDefault != _nameTableQuery && nameTableDefault != null) { // Ensure that atomized names from the default data source are added to the // name table used in this query for (i = 0; i < names.Length; i++) { string name = nameTableDefault.Get(names[i]); _atomizedNames[i] = _nameTableQuery.Add(name ?? names[i]); } } else { // Enter names into nametable used in this query for (i = 0; i < names.Length; i++) _atomizedNames[i] = _nameTableQuery.Add(names[i]); } } // Name filters _filters = null; if (filters != null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. _filters = new XmlNavigatorFilter[filters.Length]; for (i = 0; i < filters.Length; i++) _filters[i] = XmlNavNameFilter.Create(_atomizedNames[filters[i].Left], _atomizedNames[filters[i].Right]); } // Prefix maping lists _prefixMappingsList = data.PrefixMappingsList; // Xml types _types = data.Types; // Xml collations _collations = data.Collations; // Document ordering _docOrderCmp = new DocumentOrderComparer(); // Indexes _indexes = null; // Output construction _stkOutput = new Stack<XmlQueryOutput>(16); _output = new XmlQueryOutput(this, seqWrt); } //----------------------------------------------- // Debugger Utility Methods //----------------------------------------------- /// <summary> /// Return array containing the names of all the global variables and parameters used in this query, in this format: /// {namespace}prefix:local-name /// </summary> public string[] DebugGetGlobalNames() { return _globalNames; } /// <summary> /// Get the value of a global value having the specified name. Always return the global value as a list of XPathItem. /// Return null if there is no global value having the specified name. /// </summary> public IList DebugGetGlobalValue(string name) { for (int idx = 0; idx < _globalNames.Length; idx++) { if (_globalNames[idx] == name) { Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed."); Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios."); return (IList)_globalValues[idx]; } } return null; } /// <summary> /// Set the value of a global value having the specified name. If there is no such value, this method is a no-op. /// </summary> public void DebugSetGlobalValue(string name, object value) { for (int idx = 0; idx < _globalNames.Length; idx++) { if (_globalNames[idx] == name) { Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed."); Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios."); // Always convert "value" to a list of XPathItem using the item* converter _globalValues[idx] = (IList<XPathItem>)XmlAnyListConverter.ItemList.ChangeType(value, typeof(XPathItem[]), null); break; } } } /// <summary> /// Convert sequence to it's appropriate XSLT type and return to caller. /// </summary> public object DebugGetXsltValue(IList seq) { if (seq != null && seq.Count == 1) { XPathItem item = seq[0] as XPathItem; if (item != null && !item.IsNode) { return item.TypedValue; } else if (item is RtfNavigator) { return ((RtfNavigator)item).ToNavigator(); } } return seq; } //----------------------------------------------- // Early-Bound Library Objects //----------------------------------------------- internal const BindingFlags EarlyBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; internal const BindingFlags LateBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; /// <summary> /// Return the object that manages external user context information such as data sources, parameters, extension objects, etc. /// </summary> public XmlQueryContext ExternalContext { get { return _ctxt; } } /// <summary> /// Return the object that manages the state needed to implement various Xslt functions. /// </summary> public XsltLibrary XsltFunctions { get { if (_xsltLib == null) { _xsltLib = new XsltLibrary(this); } return _xsltLib; } } /// <summary> /// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the /// corresponding ConstructorInfo. /// </summary> public object GetEarlyBoundObject(int index) { object obj; Debug.Assert(_earlyObjects != null && index < _earlyObjects.Length, "Early bound object does not exist"); obj = _earlyObjects[index]; if (obj == null) { // Early-bound object does not yet exist, so create it now obj = _earlyInfo[index].CreateObject(); _earlyObjects[index] = obj; } return obj; } /// <summary> /// Return true if the early bound object identified by "namespaceUri" contains a method that matches "name". /// </summary> public bool EarlyBoundFunctionExists(string name, string namespaceUri) { if (_earlyInfo == null) return false; for (int idx = 0; idx < _earlyInfo.Length; idx++) { if (namespaceUri == _earlyInfo[idx].NamespaceUri) return new XmlExtensionFunction(name, namespaceUri, -1, _earlyInfo[idx].EarlyBoundType, EarlyBoundFlags).CanBind(); } return false; } //----------------------------------------------- // Global variables and parameters //----------------------------------------------- /// <summary> /// Return true if the global value specified by idxValue was previously computed. /// </summary> public bool IsGlobalComputed(int index) { return _globalValues[index] != null; } /// <summary> /// Return the value that is bound to the global variable or parameter specified by idxValue. /// If the value has not yet been computed, then compute it now and store it in this.globalValues. /// </summary> public object GetGlobalValue(int index) { Debug.Assert(IsGlobalComputed(index), "Cannot get the value of a global value until it has been computed."); return _globalValues[index]; } /// <summary> /// Return the value that is bound to the global variable or parameter specified by idxValue. /// If the value has not yet been computed, then compute it now and store it in this.globalValues. /// </summary> public void SetGlobalValue(int index, object value) { Debug.Assert(!IsGlobalComputed(index), "Global value should only be set once."); _globalValues[index] = value; } //----------------------------------------------- // Names, prefix mappings, and name filters //----------------------------------------------- /// <summary> /// Return the name table used to atomize all names used by the query. /// </summary> public XmlNameTable NameTable { get { return _nameTableQuery; } } /// <summary> /// Get the atomized name at the specified index in the array of names. /// </summary> public string GetAtomizedName(int index) { Debug.Assert(_atomizedNames != null); return _atomizedNames[index]; } /// <summary> /// Get the name filter at the specified index in the array of filters. /// </summary> public XmlNavigatorFilter GetNameFilter(int index) { Debug.Assert(_filters != null); return _filters[index]; } /// <summary> /// XPathNodeType.All: Filters all nodes /// XPathNodeType.Attribute: Filters attributes /// XPathNodeType.Namespace: Not allowed /// XPathNodeType.XXX: Filters all nodes *except* those having XPathNodeType.XXX /// </summary> public XmlNavigatorFilter GetTypeFilter(XPathNodeType nodeType) { if (nodeType == XPathNodeType.All) return XmlNavNeverFilter.Create(); if (nodeType == XPathNodeType.Attribute) return XmlNavAttrFilter.Create(); return XmlNavTypeFilter.Create(nodeType); } /// <summary> /// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved, /// then throw an error. Return an XmlQualifiedName. /// </summary> public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings) { string prefix, localName, ns; // Parse the tagName as a prefix, localName pair and resolve the prefix ParseTagName(tagName, indexPrefixMappings, out prefix, out localName, out ns); return new XmlQualifiedName(localName, ns); } /// <summary> /// Parse the specified tag name (foo:bar). Return an XmlQualifiedName consisting of the parsed local name /// and the specified namespace. /// </summary> public XmlQualifiedName ParseTagName(string tagName, string ns) { string prefix, localName; // Parse the tagName as a prefix, localName pair ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); return new XmlQualifiedName(localName, ns); } /// <summary> /// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved, /// then throw an error. Return the prefix, localName, and namespace URI. /// </summary> internal void ParseTagName(string tagName, int idxPrefixMappings, out string prefix, out string localName, out string ns) { Debug.Assert(_prefixMappingsList != null); // Parse the tagName as a prefix, localName pair ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); // Map the prefix to a namespace URI ns = null; foreach (StringPair pair in _prefixMappingsList[idxPrefixMappings]) { if (prefix == pair.Left) { ns = pair.Right; break; } } // Throw exception if prefix could not be resolved if (ns == null) { // Check for mappings that are always in-scope if (prefix.Length == 0) ns = ""; else if (prefix.Equals("xml")) ns = XmlReservedNs.NsXml; // It is not correct to resolve xmlns prefix in XPath but removing it would be a breaking change. else if (prefix.Equals("xmlns")) ns = XmlReservedNs.NsXmlNs; else throw new XslTransformException(SR.Xslt_InvalidPrefix, prefix); } } /// <summary> /// Return true if the nav1's LocalName and NamespaceURI properties equal nav2's corresponding properties. /// </summary> public bool IsQNameEqual(XPathNavigator n1, XPathNavigator n2) { if ((object)n1.NameTable == (object)n2.NameTable) { // Use atomized comparison return (object)n1.LocalName == (object)n2.LocalName && (object)n1.NamespaceURI == (object)n2.NamespaceURI; } return (n1.LocalName == n2.LocalName) && (n1.NamespaceURI == n2.NamespaceURI); } /// <summary> /// Return true if the specified navigator's LocalName and NamespaceURI properties equal the argument names. /// </summary> public bool IsQNameEqual(XPathNavigator navigator, int indexLocalName, int indexNamespaceUri) { if ((object)navigator.NameTable == (object)_nameTableQuery) { // Use atomized comparison return ((object)GetAtomizedName(indexLocalName) == (object)navigator.LocalName && (object)GetAtomizedName(indexNamespaceUri) == (object)navigator.NamespaceURI); } // Use string comparison return (GetAtomizedName(indexLocalName) == navigator.LocalName) && (GetAtomizedName(indexNamespaceUri) == navigator.NamespaceURI); } /// <summary> /// Get the Xml query type at the specified index in the array of types. /// </summary> internal XmlQueryType GetXmlType(int idxType) { Debug.Assert(_types != null); return _types[idxType]; } /// <summary> /// Forward call to ChangeTypeXsltArgument(XmlQueryType, object, Type). /// </summary> public object ChangeTypeXsltArgument(int indexType, object value, Type destinationType) { return ChangeTypeXsltArgument(GetXmlType(indexType), value, destinationType); } /// <summary> /// Convert from the Clr type of "value" to Clr type "destinationType" using V1 Xslt rules. /// These rules include converting any Rtf values to Nodes. /// </summary> internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType) { #if FEATURE_COMPILED_XSL Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation."); #endif Debug.Assert(destinationType == XsltConvert.ObjectType || !destinationType.IsAssignableFrom(value.GetType()), "No need to call ChangeTypeXsltArgument since value is already assignable to destinationType " + destinationType); switch (xmlType.TypeCode) { case XmlTypeCode.String: if (destinationType == XsltConvert.DateTimeType) value = XsltConvert.ToDateTime((string)value); break; case XmlTypeCode.Double: if (destinationType != XsltConvert.DoubleType) value = Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); break; case XmlTypeCode.Node: Debug.Assert(xmlType != XmlQueryTypeFactory.Node && xmlType != XmlQueryTypeFactory.NodeS, "Rtf values should have been eliminated by caller."); if (destinationType == XsltConvert.XPathNodeIteratorType) { value = new XPathArrayIterator((IList)value); } else if (destinationType == XsltConvert.XPathNavigatorArrayType) { // Copy sequence to XPathNavigator[] IList<XPathNavigator> seq = (IList<XPathNavigator>)value; XPathNavigator[] navArray = new XPathNavigator[seq.Count]; for (int i = 0; i < seq.Count; i++) navArray[i] = seq[i]; value = navArray; } break; case XmlTypeCode.Item: { // Only typeof(object) is supported as a destination type if (destinationType != XsltConvert.ObjectType) throw new XslTransformException(SR.Xslt_UnsupportedClrType, destinationType.Name); // Convert to default, backwards-compatible representation // 1. NodeSet: System.Xml.XPath.XPathNodeIterator // 2. Rtf: System.Xml.XPath.XPathNavigator // 3. Other: Default V1 representation IList<XPathItem> seq = (IList<XPathItem>)value; if (seq.Count == 1) { XPathItem item = seq[0]; if (item.IsNode) { // Node or Rtf RtfNavigator rtf = item as RtfNavigator; if (rtf != null) value = rtf.ToNavigator(); else value = new XPathArrayIterator((IList)value); } else { // Atomic value value = item.TypedValue; } } else { // Nodeset value = new XPathArrayIterator((IList)value); } break; } } Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), "ChangeType from type " + value.GetType().Name + " to type " + destinationType.Name + " failed"); return value; } /// <summary> /// Forward call to ChangeTypeXsltResult(XmlQueryType, object) /// </summary> public object ChangeTypeXsltResult(int indexType, object value) { return ChangeTypeXsltResult(GetXmlType(indexType), value); } /// <summary> /// Convert from the Clr type of "value" to the default Clr type that ILGen uses to represent the xml type, using /// the conversion rules of the xml type. /// </summary> internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) { if (value == null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); switch (xmlType.TypeCode) { case XmlTypeCode.String: if (value.GetType() == XsltConvert.DateTimeType) value = XsltConvert.ToString((DateTime)value); break; case XmlTypeCode.Double: if (value.GetType() != XsltConvert.DoubleType) value = ((IConvertible)value).ToDouble(null); break; case XmlTypeCode.Node: if (!xmlType.IsSingleton) { XPathArrayIterator iter = value as XPathArrayIterator; // Special-case XPathArrayIterator in order to avoid copies if (iter != null && iter.AsList is XmlQueryNodeSequence) { value = iter.AsList as XmlQueryNodeSequence; } else { // Iterate over list and ensure it only contains nodes XmlQueryNodeSequence seq = new XmlQueryNodeSequence(); IList list = value as IList; if (list != null) { for (int i = 0; i < list.Count; i++) seq.Add(EnsureNavigator(list[i])); } else { foreach (object o in (IEnumerable)value) seq.Add(EnsureNavigator(o)); } value = seq; } // Always sort node-set by document order value = ((XmlQueryNodeSequence)value).DocOrderDistinct(_docOrderCmp); } break; case XmlTypeCode.Item: { Type sourceType = value.GetType(); IXPathNavigable navigable; // If static type is item, then infer type based on dynamic value switch (XsltConvert.InferXsltType(sourceType).TypeCode) { case XmlTypeCode.Boolean: value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), value)); break; case XmlTypeCode.Double: value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), ((IConvertible)value).ToDouble(null))); break; case XmlTypeCode.String: if (sourceType == XsltConvert.DateTimeType) value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), XsltConvert.ToString((DateTime)value))); else value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), value)); break; case XmlTypeCode.Node: // Support XPathNavigator[] value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value); break; case XmlTypeCode.Item: // Support XPathNodeIterator if (value is XPathNodeIterator) { value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value); break; } // Support IXPathNavigable and XPathNavigator navigable = value as IXPathNavigable; if (navigable != null) { if (value is XPathNavigator) value = new XmlQueryNodeSequence((XPathNavigator)value); else value = new XmlQueryNodeSequence(navigable.CreateNavigator()); break; } throw new XslTransformException(SR.Xslt_UnsupportedClrType, sourceType.Name); } break; } } #if FEATURE_COMPILED_XSL Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Xml type " + xmlType + " is not represented in ILGen as " + value.GetType().Name); #endif return value; } /// <summary> /// Ensure that "value" is a navigator and not null. /// </summary> private static XPathNavigator EnsureNavigator(object value) { XPathNavigator nav = value as XPathNavigator; if (nav == null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); return nav; } /// <summary> /// Return true if the type of every item in "seq" matches the xml type identified by "idxType". /// </summary> public bool MatchesXmlType(IList<XPathItem> seq, int indexType) { XmlQueryType typBase = GetXmlType(indexType); XmlQueryCardinality card; switch (seq.Count) { case 0: card = XmlQueryCardinality.Zero; break; case 1: card = XmlQueryCardinality.One; break; default: card = XmlQueryCardinality.More; break; } if (!(card <= typBase.Cardinality)) return false; typBase = typBase.Prime; for (int i = 0; i < seq.Count; i++) { if (!CreateXmlType(seq[0]).IsSubtypeOf(typBase)) return false; } return true; } /// <summary> /// Return true if the type of "item" matches the xml type identified by "idxType". /// </summary> public bool MatchesXmlType(XPathItem item, int indexType) { return CreateXmlType(item).IsSubtypeOf(GetXmlType(indexType)); } /// <summary> /// Return true if the type of "seq" is a subtype of a singleton type identified by "code". /// </summary> public bool MatchesXmlType(IList<XPathItem> seq, XmlTypeCode code) { if (seq.Count != 1) return false; return MatchesXmlType(seq[0], code); } /// <summary> /// Return true if the type of "item" is a subtype of the type identified by "code". /// </summary> public bool MatchesXmlType(XPathItem item, XmlTypeCode code) { // All atomic type codes appear after AnyAtomicType if (code > XmlTypeCode.AnyAtomicType) return !item.IsNode && item.XmlType.TypeCode == code; // Handle node code and AnyAtomicType switch (code) { case XmlTypeCode.AnyAtomicType: return !item.IsNode; case XmlTypeCode.Node: return item.IsNode; case XmlTypeCode.Item: return true; default: if (!item.IsNode) return false; switch (((XPathNavigator)item).NodeType) { case XPathNodeType.Root: return code == XmlTypeCode.Document; case XPathNodeType.Element: return code == XmlTypeCode.Element; case XPathNodeType.Attribute: return code == XmlTypeCode.Attribute; case XPathNodeType.Namespace: return code == XmlTypeCode.Namespace; case XPathNodeType.Text: return code == XmlTypeCode.Text; case XPathNodeType.SignificantWhitespace: return code == XmlTypeCode.Text; case XPathNodeType.Whitespace: return code == XmlTypeCode.Text; case XPathNodeType.ProcessingInstruction: return code == XmlTypeCode.ProcessingInstruction; case XPathNodeType.Comment: return code == XmlTypeCode.Comment; } break; } Debug.Fail("XmlTypeCode " + code + " was not fully handled."); return false; } /// <summary> /// Create an XmlQueryType that represents the type of "item". /// </summary> private XmlQueryType CreateXmlType(XPathItem item) { if (item.IsNode) { // Rtf RtfNavigator rtf = item as RtfNavigator; if (rtf != null) return XmlQueryTypeFactory.Node; // Node XPathNavigator nav = (XPathNavigator)item; switch (nav.NodeType) { case XPathNodeType.Root: case XPathNodeType.Element: if (nav.XmlType == null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), XmlSchemaComplexType.UntypedAnyType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, nav.SchemaInfo.SchemaElement.IsNillable); case XPathNodeType.Attribute: if (nav.XmlType == null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), DatatypeImplementation.UntypedAtomicType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, false); } return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.Wildcard, XmlSchemaComplexType.AnyType, false); } // Atomic value return XmlQueryTypeFactory.Type((XmlSchemaSimpleType)item.XmlType, true); } //----------------------------------------------- // Xml collations //----------------------------------------------- /// <summary> /// Get a collation that was statically created. /// </summary> public XmlCollation GetCollation(int index) { Debug.Assert(_collations != null); return _collations[index]; } /// <summary> /// Create a collation from a string. /// </summary> public XmlCollation CreateCollation(string collation) { return XmlCollation.Create(collation); } //----------------------------------------------- // Document Ordering and Identity //----------------------------------------------- /// <summary> /// Compare the relative positions of two navigators. Return -1 if navThis is before navThat, 1 if after, and /// 0 if they are positioned to the same node. /// </summary> public int ComparePosition(XPathNavigator navigatorThis, XPathNavigator navigatorThat) { return _docOrderCmp.Compare(navigatorThis, navigatorThat); } /// <summary> /// Get a comparer which guarantees a stable ordering among nodes, even those from different documents. /// </summary> public IList<XPathNavigator> DocOrderDistinct(IList<XPathNavigator> seq) { if (seq.Count <= 1) return seq; XmlQueryNodeSequence nodeSeq = (XmlQueryNodeSequence)seq; if (nodeSeq == null) nodeSeq = new XmlQueryNodeSequence(seq); return nodeSeq.DocOrderDistinct(_docOrderCmp); } /// <summary> /// Generate a unique string identifier for the specified node. Do this by asking the navigator for an identifier /// that is unique within the document, and then prepend a document index. /// </summary> public string GenerateId(XPathNavigator navigator) { return string.Concat("ID", _docOrderCmp.GetDocumentIndex(navigator).ToString(CultureInfo.InvariantCulture), navigator.UniqueId); } //----------------------------------------------- // Indexes //----------------------------------------------- /// <summary> /// If an index having the specified Id has already been created over the "context" document, then return it /// in "index" and return true. Otherwise, create a new, empty index and return false. /// </summary> public bool FindIndex(XPathNavigator context, int indexId, out XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; Debug.Assert(context != null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Search pre-existing indexes in order to determine whether the specified index has already been created if (_indexes != null && indexId < _indexes.Length) { docIndexes = (ArrayList)_indexes[indexId]; if (docIndexes != null) { // Search for an index defined over the specified document for (int i = 0; i < docIndexes.Count; i += 2) { // If we find a matching document, then return the index saved in the next slot if (((XPathNavigator)docIndexes[i]).IsSamePosition(navRoot)) { index = (XmlILIndex)docIndexes[i + 1]; return true; } } } } // Return a new, empty index index = new XmlILIndex(); return false; } /// <summary> /// Add a newly built index over the specified "context" document to the existing collection of indexes. /// </summary> public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; Debug.Assert(context != null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Ensure that a slot exists for the new index if (_indexes == null) { _indexes = new ArrayList[indexId + 4]; } else if (indexId >= _indexes.Length) { // Resize array ArrayList[] indexesNew = new ArrayList[indexId + 4]; Array.Copy(_indexes, 0, indexesNew, 0, _indexes.Length); _indexes = indexesNew; } docIndexes = (ArrayList)_indexes[indexId]; if (docIndexes == null) { docIndexes = new ArrayList(); _indexes[indexId] = docIndexes; } docIndexes.Add(navRoot); docIndexes.Add(index); } //----------------------------------------------- // Output construction //----------------------------------------------- /// <summary> /// Get output writer object. /// </summary> public XmlQueryOutput Output { get { return _output; } } /// <summary> /// Start construction of a nested sequence of items. Return a new XmlQueryOutput that will be /// used to construct this new sequence. /// </summary> public void StartSequenceConstruction(out XmlQueryOutput output) { // Push current writer _stkOutput.Push(_output); // Create new writers output = _output = new XmlQueryOutput(this, new XmlCachedSequenceWriter()); } /// <summary> /// End construction of a nested sequence of items and return the items as an IList{XPathItem} /// internal class. Return previous XmlQueryOutput. /// </summary> public IList<XPathItem> EndSequenceConstruction(out XmlQueryOutput output) { IList<XPathItem> seq = ((XmlCachedSequenceWriter)_output.SequenceWriter).ResultSequence; // Restore previous XmlQueryOutput output = _output = _stkOutput.Pop(); return seq; } /// <summary> /// Start construction of an Rtf. Return a new XmlQueryOutput object that will be used to construct this Rtf. /// </summary> public void StartRtfConstruction(string baseUri, out XmlQueryOutput output) { // Push current writer _stkOutput.Push(_output); // Create new XmlQueryOutput over an Rtf writer output = _output = new XmlQueryOutput(this, new XmlEventCache(baseUri, true)); } /// <summary> /// End construction of an Rtf and return it as an RtfNavigator. Return previous XmlQueryOutput object. /// </summary> public XPathNavigator EndRtfConstruction(out XmlQueryOutput output) { XmlEventCache events; events = (XmlEventCache)_output.Writer; // Restore previous XmlQueryOutput output = _output = _stkOutput.Pop(); // Return Rtf as an RtfNavigator events.EndEvents(); return new RtfTreeNavigator(events, _nameTableQuery); } /// <summary> /// Construct a new RtfTextNavigator from the specified "text". This is much more efficient than calling /// StartNodeConstruction(), StartRtf(), WriteString(), EndRtf(), and EndNodeConstruction(). /// </summary> public XPathNavigator TextRtfConstruction(string text, string baseUri) { return new RtfTextNavigator(text, baseUri); } //----------------------------------------------- // Miscellaneous //----------------------------------------------- /// <summary> /// Report query execution information to event handler. /// </summary> public void SendMessage(string message) { _ctxt.OnXsltMessageEncountered(message); } /// <summary> /// Throw an Xml exception having the specified message text. /// </summary> public void ThrowException(string text) { throw new XslTransformException(text); } /// <summary> /// Position navThis to the same location as navThat. /// </summary> internal static XPathNavigator SyncToNavigator(XPathNavigator navigatorThis, XPathNavigator navigatorThat) { if (navigatorThis == null || !navigatorThis.MoveTo(navigatorThat)) return navigatorThat.Clone(); return navigatorThis; } /// <summary> /// Function is called in Debug mode on each time context node change. /// </summary> public static int OnCurrentNodeChanged(XPathNavigator currentNode) { IXmlLineInfo lineInfo = currentNode as IXmlLineInfo; // In case of a namespace node, check whether it is inherited or locally defined if (lineInfo != null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) { OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition); } return 0; } // 'true' if current Namespace "inherited" from it's parent. Not defined locally. private static bool IsInheritedNamespace(XPathNavigator node) { Debug.Assert(node.NodeType == XPathNodeType.Namespace); XPathNavigator nav = node.Clone(); if (nav.MoveToParent()) { if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { do { if ((object)nav.LocalName == (object)node.LocalName) { return false; } } while (nav.MoveToNextNamespace(XPathNamespaceScope.Local)); } } return true; } private static void OnCurrentNodeChanged2(string baseUri, int lineNumber, int linePosition) { } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define USE_TRACING using System; using System.Xml; using System.IO; using System.Collections; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Extensions.MediaRss; using Google.GData.Extensions.Exif; using Google.GData.Extensions.Location; using System.ComponentModel; namespace Google.GData.Photos { ////////////////////////////////////////////////////////////////////// /// <summary> /// A photoEntry is a shallow subclass for a PicasaEntry to ease /// access for photospecific properties /// </summary> ////////////////////////////////////////////////////////////////////// public class PhotoEntry : PicasaEntry { /// <summary> /// Constructs a new EventEntry instance with the appropriate category /// to indicate that it is an event. /// </summary> public PhotoEntry() : base() { Tracing.TraceMsg("Created PhotoEntry"); Categories.Add(PHOTO_CATEGORY); } } /// <summary> /// this is a pure accessor class that can either take a photoentry or work with /// a picasaentry to get you convienience accessors /// </summary> [Obsolete("Use Google.Picasa.Photo instead. This code will be removed soon")] public class PhotoAccessor { private PicasaEntry entry; /// <summary> /// constructs a photo accessor for the passed in entry /// </summary> /// <param name="entry"></param> public PhotoAccessor(PicasaEntry entry) { this.entry = entry; if (!entry.IsPhoto) { throw new ArgumentException("Entry is not a photo", "entry"); } } /// <summary> /// The title of the photo /// </summary> [Category("Base Photo Data"), Description("Specifies the name of the photo.")] public string PhotoTitle { get { return this.entry.Title.Text; } set { this.entry.Title.Text = value; } } /// <summary> /// The summary of the Photo /// </summary> [Category("Base Photo Data"), Description("Specifies the summary of the Photo.")] public string PhotoSummary { get { return this.entry.Summary.Text; } set { this.entry.Summary.Text = value; } } /// <summary> /// The checksum on the photo. This optional field can be used by /// uploaders to associate a checksum with a photo to ease duplicate detection /// </summary> [Category("Meta Photo Data"), Description("The checksum on the photo.")] public string Checksum { get { return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Checksum); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Checksum, value); } } /// <summary> /// The height of the photo in pixels /// </summary> [Category("Basic Photo Data"), Description("The height of the photo in pixels.")] public int Height { get { return Convert.ToInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.Height)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Height, Convert.ToString(value)); } } /// <summary> /// The width of the photo in pixels /// </summary> [Category("Basic Photo Data"), Description("The width of the photo in pixels.")] public int Width { get { return Convert.ToInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.Width)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Width, Convert.ToString(value)); } } /// <summary> /// The rotation of the photo in degrees, used to change the rotation of the photo. Will only be shown if /// the rotation has not already been applied to the requested images. /// </summary> [Category("Basic Photo Data"), Description("The rotation of the photo in degrees.")] public int Rotation { get { return Convert.ToInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.Rotation)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Rotation, Convert.ToString(value)); } } /// <summary> /// The size of the photo in bytes /// </summary> [Category("Basic Photo Data"), Description("The size of the photo in bytes.")] public long Size { get { return Convert.ToInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.Size)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Size, Convert.ToString(value)); } } /// <summary> /// The photo's timestamp, represented as the number of milliseconds since /// January 1st, 1970. Contains the date of the photo either set externally /// or retrieved from the Exif data. /// </summary> [Category("Meta Photo Data"), Description("The photo's timestamp")] [CLSCompliant(false)] public ulong Timestamp { get { return Convert.ToUInt64(this.entry.GetPhotoExtensionValue(GPhotoNameTable.Timestamp)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Timestamp, Convert.ToString(value)); } } /// <summary> /// The albums ID /// </summary> [Category("Meta Photo Data"), Description("The albums ID.")] public string AlbumId { get { return this.entry.GetPhotoExtensionValue(GPhotoNameTable.AlbumId); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.AlbumId, value); } } /// <summary> /// the number of comments on a photo /// </summary> [Category("Commenting"), Description("the number of comments on a photo.")] [CLSCompliant(false)] public uint CommentCount { get { return Convert.ToUInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.CommentCount)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.CommentCount, Convert.ToString(value)); } } /// <summary> /// is commenting enabled on a photo /// </summary> [Category("Commenting"), Description("is commenting enabled on a photo.")] public bool CommentingEnabled { get { return Convert.ToBoolean(this.entry.GetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled)); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled, Utilities.ConvertBooleanToXSDString(value)); } } /// <summary> /// the id of the photo /// </summary> [Category("Meta Photo Data"), Description("the id of the photo.")] public string Id { get { return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Id); } set { this.entry.SetPhotoExtensionValue(GPhotoNameTable.Id, value); } } /// <summary> /// the Longitude of the photo /// </summary> [Category("Location Photo Data"), Description("The longitude of the photo.")] public double Longitude { get { GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; if (where != null) { return where.Longitude; } return -1; } set { GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; if (where == null) { where = entry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; this.entry.ExtensionElements.Add(where); } where.Longitude = value; } } /// <summary> /// the Longitude of the photo /// </summary> [Category("Location Photo Data"), Description("The Latitude of the photo.")] public double Latitude { get { GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; if (where != null) { return where.Latitude; } return -1; } set { GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; if (where == null) { where = entry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; this.entry.ExtensionElements.Add(where); } where.Latitude = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Drawing { internal static class KnownColorTable { // All non system colors (in order of definition in the KnownColor enum). private static readonly uint[] s_colorTable = new uint[] { 0x00FFFFFF, // Transparent 0xFFF0F8FF, // AliceBlue 0xFFFAEBD7, // AntiqueWhite 0xFF00FFFF, // Aqua 0xFF7FFFD4, // Aquamarine 0xFFF0FFFF, // Azure 0xFFF5F5DC, // Beige 0xFFFFE4C4, // Bisque 0xFF000000, // Black 0xFFFFEBCD, // BlanchedAlmond 0xFF0000FF, // Blue 0xFF8A2BE2, // BlueViolet 0xFFA52A2A, // Brown 0xFFDEB887, // BurlyWood 0xFF5F9EA0, // CadetBlue 0xFF7FFF00, // Chartreuse 0xFFD2691E, // Chocolate 0xFFFF7F50, // Coral 0xFF6495ED, // CornflowerBlue 0xFFFFF8DC, // Cornsilk 0xFFDC143C, // Crimson 0xFF00FFFF, // Cyan 0xFF00008B, // DarkBlue 0xFF008B8B, // DarkCyan 0xFFB8860B, // DarkGoldenrod 0xFFA9A9A9, // DarkGray 0xFF006400, // DarkGreen 0xFFBDB76B, // DarkKhaki 0xFF8B008B, // DarkMagenta 0xFF556B2F, // DarkOliveGreen 0xFFFF8C00, // DarkOrange 0xFF9932CC, // DarkOrchid 0xFF8B0000, // DarkRed 0xFFE9967A, // DarkSalmon 0xFF8FBC8F, // DarkSeaGreen 0xFF483D8B, // DarkSlateBlue 0xFF2F4F4F, // DarkSlateGray 0xFF00CED1, // DarkTurquoise 0xFF9400D3, // DarkViolet 0xFFFF1493, // DeepPink 0xFF00BFFF, // DeepSkyBlue 0xFF696969, // DimGray 0xFF1E90FF, // DodgerBlue 0xFFB22222, // Firebrick 0xFFFFFAF0, // FloralWhite 0xFF228B22, // ForestGreen 0xFFFF00FF, // Fuchsia 0xFFDCDCDC, // Gainsboro 0xFFF8F8FF, // GhostWhite 0xFFFFD700, // Gold 0xFFDAA520, // Goldenrod 0xFF808080, // Gray 0xFF008000, // Green 0xFFADFF2F, // GreenYellow 0xFFF0FFF0, // Honeydew 0xFFFF69B4, // HotPink 0xFFCD5C5C, // IndianRed 0xFF4B0082, // Indigo 0xFFFFFFF0, // Ivory 0xFFF0E68C, // Khaki 0xFFE6E6FA, // Lavender 0xFFFFF0F5, // LavenderBlush 0xFF7CFC00, // LawnGreen 0xFFFFFACD, // LemonChiffon 0xFFADD8E6, // LightBlue 0xFFF08080, // LightCoral 0xFFE0FFFF, // LightCyan 0xFFFAFAD2, // LightGoldenrodYellow 0xFFD3D3D3, // LightGray 0xFF90EE90, // LightGreen 0xFFFFB6C1, // LightPink 0xFFFFA07A, // LightSalmon 0xFF20B2AA, // LightSeaGreen 0xFF87CEFA, // LightSkyBlue 0xFF778899, // LightSlateGray 0xFFB0C4DE, // LightSteelBlue 0xFFFFFFE0, // LightYellow 0xFF00FF00, // Lime 0xFF32CD32, // LimeGreen 0xFFFAF0E6, // Linen 0xFFFF00FF, // Magenta 0xFF800000, // Maroon 0xFF66CDAA, // MediumAquamarine 0xFF0000CD, // MediumBlue 0xFFBA55D3, // MediumOrchid 0xFF9370DB, // MediumPurple 0xFF3CB371, // MediumSeaGreen 0xFF7B68EE, // MediumSlateBlue 0xFF00FA9A, // MediumSpringGreen 0xFF48D1CC, // MediumTurquoise 0xFFC71585, // MediumVioletRed 0xFF191970, // MidnightBlue 0xFFF5FFFA, // MintCream 0xFFFFE4E1, // MistyRose 0xFFFFE4B5, // Moccasin 0xFFFFDEAD, // NavajoWhite 0xFF000080, // Navy 0xFFFDF5E6, // OldLace 0xFF808000, // Olive 0xFF6B8E23, // OliveDrab 0xFFFFA500, // Orange 0xFFFF4500, // OrangeRed 0xFFDA70D6, // Orchid 0xFFEEE8AA, // PaleGoldenrod 0xFF98FB98, // PaleGreen 0xFFAFEEEE, // PaleTurquoise 0xFFDB7093, // PaleVioletRed 0xFFFFEFD5, // PapayaWhip 0xFFFFDAB9, // PeachPuff 0xFFCD853F, // Peru 0xFFFFC0CB, // Pink 0xFFDDA0DD, // Plum 0xFFB0E0E6, // PowderBlue 0xFF800080, // Purple 0xFFFF0000, // Red 0xFFBC8F8F, // RosyBrown 0xFF4169E1, // RoyalBlue 0xFF8B4513, // SaddleBrown 0xFFFA8072, // Salmon 0xFFF4A460, // SandyBrown 0xFF2E8B57, // SeaGreen 0xFFFFF5EE, // SeaShell 0xFFA0522D, // Sienna 0xFFC0C0C0, // Silver 0xFF87CEEB, // SkyBlue 0xFF6A5ACD, // SlateBlue 0xFF708090, // SlateGray 0xFFFFFAFA, // Snow 0xFF00FF7F, // SpringGreen 0xFF4682B4, // SteelBlue 0xFFD2B48C, // Tan 0xFF008080, // Teal 0xFFD8BFD8, // Thistle 0xFFFF6347, // Tomato 0xFF40E0D0, // Turquoise 0xFFEE82EE, // Violet 0xFFF5DEB3, // Wheat 0xFFFFFFFF, // White 0xFFF5F5F5, // WhiteSmoke 0xFFFFFF00, // Yellow 0xFF9ACD32, // YellowGreen }; internal static Color ArgbToKnownColor(uint argb) { // Should be fully opaque (and as such we can skip the first entry // which is transparent). Debug.Assert((argb & Color.ARGBAlphaMask) == Color.ARGBAlphaMask); for (int index = 1; index < s_colorTable.Length; ++index) { if (s_colorTable[index] == argb) { return Color.FromKnownColor((KnownColor)(index + (int)KnownColor.Transparent)); } } // Not a known color return Color.FromArgb((int)argb); } public static uint KnownColorToArgb(KnownColor color) { Debug.Assert(color > 0 && color <= KnownColor.MenuHighlight); return Color.IsKnownColorSystem(color) ? GetSystemColorArgb(color) : s_colorTable[(int)color - (int)KnownColor.Transparent]; } #if FEATURE_WINDOWS_SYSTEM_COLORS private static ReadOnlySpan<byte> SystemColorIdTable => new byte[] { // In order of definition in KnownColor enum // The original group of contiguous system KnownColors (byte)Interop.User32.Win32SystemColors.ActiveBorder, (byte)Interop.User32.Win32SystemColors.ActiveCaption, (byte)Interop.User32.Win32SystemColors.ActiveCaptionText, (byte)Interop.User32.Win32SystemColors.AppWorkspace, (byte)Interop.User32.Win32SystemColors.Control, (byte)Interop.User32.Win32SystemColors.ControlDark, (byte)Interop.User32.Win32SystemColors.ControlDarkDark, (byte)Interop.User32.Win32SystemColors.ControlLight, (byte)Interop.User32.Win32SystemColors.ControlLightLight, (byte)Interop.User32.Win32SystemColors.ControlText, (byte)Interop.User32.Win32SystemColors.Desktop, (byte)Interop.User32.Win32SystemColors.GrayText, (byte)Interop.User32.Win32SystemColors.Highlight, (byte)Interop.User32.Win32SystemColors.HighlightText, (byte)Interop.User32.Win32SystemColors.HotTrack, (byte)Interop.User32.Win32SystemColors.InactiveBorder, (byte)Interop.User32.Win32SystemColors.InactiveCaption, (byte)Interop.User32.Win32SystemColors.InactiveCaptionText, (byte)Interop.User32.Win32SystemColors.Info, (byte)Interop.User32.Win32SystemColors.InfoText, (byte)Interop.User32.Win32SystemColors.Menu, (byte)Interop.User32.Win32SystemColors.MenuText, (byte)Interop.User32.Win32SystemColors.ScrollBar, (byte)Interop.User32.Win32SystemColors.Window, (byte)Interop.User32.Win32SystemColors.WindowFrame, (byte)Interop.User32.Win32SystemColors.WindowText, // The appended group of SystemColors (i.e. not sequential with WindowText above) (byte)Interop.User32.Win32SystemColors.ButtonFace, (byte)Interop.User32.Win32SystemColors.ButtonHighlight, (byte)Interop.User32.Win32SystemColors.ButtonShadow, (byte)Interop.User32.Win32SystemColors.GradientActiveCaption, (byte)Interop.User32.Win32SystemColors.GradientInactiveCaption, (byte)Interop.User32.Win32SystemColors.MenuBar, (byte)Interop.User32.Win32SystemColors.MenuHighlight }; public static uint GetSystemColorArgb(KnownColor color) => ColorTranslator.COLORREFToARGB(Interop.User32.GetSysColor(GetSystemColorId(color))); private static int GetSystemColorId(KnownColor color) { Debug.Assert(Color.IsKnownColorSystem(color)); return color < KnownColor.Transparent ? SystemColorIdTable[(int)color - (int)KnownColor.ActiveBorder] : SystemColorIdTable[(int)color - (int)KnownColor.ButtonFace + (int)KnownColor.WindowText]; } #else private static readonly uint[] s_staticSystemColors = new uint[] { // Hard-coded constants, based on default Windows settings. // (In order of definition in KnownColor enum.) // First contiguous set. 0xFFD4D0C8, // ActiveBorder 0xFF0054E3, // ActiveCaption 0xFFFFFFFF, // ActiveCaptionText 0xFF808080, // AppWorkspace 0xFFECE9D8, // Control 0xFFACA899, // ControlDark 0xFF716F64, // ControlDarkDark 0xFFF1EFE2, // ControlLight 0xFFFFFFFF, // ControlLightLight 0xFF000000, // ControlText 0xFF004E98, // Desktop 0xFFACA899, // GrayText 0xFF316AC5, // Highlight 0xFFFFFFFF, // HighlightText 0xFF000080, // HotTrack 0xFFD4D0C8, // InactiveBorder 0xFF7A96DF, // InactiveCaption 0xFFD8E4F8, // InactiveCaptionText 0xFFFFFFE1, // Info 0xFF000000, // InfoText 0xFFFFFFFF, // Menu 0xFF000000, // MenuText 0xFFD4D0C8, // ScrollBar 0xFFFFFFFF, // Window 0xFF000000, // WindowFrame 0xFF000000, // WindowText // Second contiguous set. 0xFFF0F0F0, // ButtonFace 0xFFFFFFFF, // ButtonHighlight 0xFFA0A0A0, // ButtonShadow 0xFFB9D1EA, // GradientActiveCaption 0xFFD7E4F2, // GradientInactiveCaption 0xFFF0F0F0, // MenuBar 0xFF3399FF, // MenuHighlight }; public static uint GetSystemColorArgb(KnownColor color) { Debug.Assert(Color.IsKnownColorSystem(color)); return color < KnownColor.Transparent ? s_staticSystemColors[(int)color - (int)KnownColor.ActiveBorder] : s_staticSystemColors[(int)color - (int)KnownColor.ButtonFace + (int)KnownColor.WindowText]; } #endif } }
/* * CP863.cs - French Canadian (DOS) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-863.ucm". namespace I18N.West { using System; using I18N.Common; public class CP863 : ByteEncoding { public CP863() : base(863, ToChars, "French Canadian (DOS)", "IBM863", "IBM863", "IBM863", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u001A', '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00C2', '\u00E0', '\u00B6', '\u00E7', '\u00EA', '\u00EB', '\u00E8', '\u00EF', '\u00EE', '\u2017', '\u00C0', '\u00A7', '\u00C9', '\u00C8', '\u00CA', '\u00F4', '\u00CB', '\u00CF', '\u00FB', '\u00F9', '\u00A4', '\u00D4', '\u00DC', '\u00A2', '\u00A3', '\u00D9', '\u00DB', '\u0192', '\u00A6', '\u00B4', '\u00F3', '\u00FA', '\u00A8', '\u00B8', '\u00B3', '\u00AF', '\u00CE', '\u2310', '\u00AC', '\u00BD', '\u00BC', '\u00BE', '\u00AB', '\u00BB', '\u2591', '\u2592', '\u2593', '\u2502', '\u2524', '\u2561', '\u2562', '\u2556', '\u2555', '\u2563', '\u2551', '\u2557', '\u255D', '\u255C', '\u255B', '\u2510', '\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C', '\u255E', '\u255F', '\u255A', '\u2554', '\u2569', '\u2566', '\u2560', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564', '\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B', '\u256A', '\u2518', '\u250C', '\u2588', '\u2584', '\u258C', '\u2590', '\u2580', '\u03B1', '\u00DF', '\u0393', '\u03C0', '\u03A3', '\u03C3', '\u03BC', '\u03C4', '\u03A6', '\u0398', '\u03A9', '\u03B4', '\u221E', '\u03C6', '\u03B5', '\u2229', '\u2261', '\u00B1', '\u2265', '\u2264', '\u2320', '\u2321', '\u00F7', '\u2248', '\u00B0', '\u2219', '\u00B7', '\u221A', '\u207F', '\u00B2', '\u25A0', '\u00A0', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A2: ch = 0x9B; break; case 0x00A3: ch = 0x9C; break; case 0x00A4: ch = 0x98; break; case 0x00A6: ch = 0xA0; break; case 0x00A7: ch = 0x8F; break; case 0x00A8: ch = 0xA4; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0xAA; break; case 0x00AF: ch = 0xA7; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0xFD; break; case 0x00B3: ch = 0xA6; break; case 0x00B4: ch = 0xA1; break; case 0x00B6: ch = 0x86; break; case 0x00B7: ch = 0xFA; break; case 0x00B8: ch = 0xA5; break; case 0x00BB: ch = 0xAF; break; case 0x00BC: ch = 0xAC; break; case 0x00BD: ch = 0xAB; break; case 0x00BE: ch = 0xAD; break; case 0x00C0: ch = 0x8E; break; case 0x00C2: ch = 0x84; break; case 0x00C7: ch = 0x80; break; case 0x00C8: ch = 0x91; break; case 0x00C9: ch = 0x90; break; case 0x00CA: ch = 0x92; break; case 0x00CB: ch = 0x94; break; case 0x00CE: ch = 0xA8; break; case 0x00CF: ch = 0x95; break; case 0x00D4: ch = 0x99; break; case 0x00D9: ch = 0x9D; break; case 0x00DB: ch = 0x9E; break; case 0x00DC: ch = 0x9A; break; case 0x00DF: ch = 0xE1; break; case 0x00E0: ch = 0x85; break; case 0x00E2: ch = 0x83; break; case 0x00E7: ch = 0x87; break; case 0x00E8: ch = 0x8A; break; case 0x00E9: ch = 0x82; break; case 0x00EA: ch = 0x88; break; case 0x00EB: ch = 0x89; break; case 0x00EE: ch = 0x8C; break; case 0x00EF: ch = 0x8B; break; case 0x00F3: ch = 0xA2; break; case 0x00F4: ch = 0x93; break; case 0x00F7: ch = 0xF6; break; case 0x00F9: ch = 0x97; break; case 0x00FA: ch = 0xA3; break; case 0x00FB: ch = 0x96; break; case 0x00FC: ch = 0x81; break; case 0x0192: ch = 0x9F; break; case 0x0393: ch = 0xE2; break; case 0x0398: ch = 0xE9; break; case 0x03A3: ch = 0xE4; break; case 0x03A6: ch = 0xE8; break; case 0x03A9: ch = 0xEA; break; case 0x03B1: ch = 0xE0; break; case 0x03B4: ch = 0xEB; break; case 0x03B5: ch = 0xEE; break; case 0x03BC: ch = 0xE6; break; case 0x03C0: ch = 0xE3; break; case 0x03C3: ch = 0xE5; break; case 0x03C4: ch = 0xE7; break; case 0x03C6: ch = 0xED; break; case 0x2017: ch = 0x8D; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x203E: ch = 0xA7; break; case 0x207F: ch = 0xFC; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x2219: ch = 0xF9; break; case 0x221A: ch = 0xFB; break; case 0x221E: ch = 0xEC; break; case 0x221F: ch = 0x1C; break; case 0x2229: ch = 0xEF; break; case 0x2248: ch = 0xF7; break; case 0x2261: ch = 0xF0; break; case 0x2264: ch = 0xF3; break; case 0x2265: ch = 0xF2; break; case 0x2302: ch = 0x7F; break; case 0x2310: ch = 0xA9; break; case 0x2320: ch = 0xF4; break; case 0x2321: ch = 0xF5; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2552: ch = 0xD5; break; case 0x2553: ch = 0xD6; break; case 0x2554: ch = 0xC9; break; case 0x2555: ch = 0xB8; break; case 0x2556: ch = 0xB7; break; case 0x2557: ch = 0xBB; break; case 0x2558: ch = 0xD4; break; case 0x2559: ch = 0xD3; break; case 0x255A: ch = 0xC8; break; case 0x255B: ch = 0xBE; break; case 0x255C: ch = 0xBD; break; case 0x255D: ch = 0xBC; break; case 0x255E: ch = 0xC6; break; case 0x255F: ch = 0xC7; break; case 0x2560: ch = 0xCC; break; case 0x2561: ch = 0xB5; break; case 0x2562: ch = 0xB6; break; case 0x2563: ch = 0xB9; break; case 0x2564: ch = 0xD1; break; case 0x2565: ch = 0xD2; break; case 0x2566: ch = 0xCB; break; case 0x2567: ch = 0xCF; break; case 0x2568: ch = 0xD0; break; case 0x2569: ch = 0xCA; break; case 0x256A: ch = 0xD8; break; case 0x256B: ch = 0xD7; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x258C: ch = 0xDD; break; case 0x2590: ch = 0xDE; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266B: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A2: ch = 0x9B; break; case 0x00A3: ch = 0x9C; break; case 0x00A4: ch = 0x98; break; case 0x00A6: ch = 0xA0; break; case 0x00A7: ch = 0x8F; break; case 0x00A8: ch = 0xA4; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0xAA; break; case 0x00AF: ch = 0xA7; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0xFD; break; case 0x00B3: ch = 0xA6; break; case 0x00B4: ch = 0xA1; break; case 0x00B6: ch = 0x86; break; case 0x00B7: ch = 0xFA; break; case 0x00B8: ch = 0xA5; break; case 0x00BB: ch = 0xAF; break; case 0x00BC: ch = 0xAC; break; case 0x00BD: ch = 0xAB; break; case 0x00BE: ch = 0xAD; break; case 0x00C0: ch = 0x8E; break; case 0x00C2: ch = 0x84; break; case 0x00C7: ch = 0x80; break; case 0x00C8: ch = 0x91; break; case 0x00C9: ch = 0x90; break; case 0x00CA: ch = 0x92; break; case 0x00CB: ch = 0x94; break; case 0x00CE: ch = 0xA8; break; case 0x00CF: ch = 0x95; break; case 0x00D4: ch = 0x99; break; case 0x00D9: ch = 0x9D; break; case 0x00DB: ch = 0x9E; break; case 0x00DC: ch = 0x9A; break; case 0x00DF: ch = 0xE1; break; case 0x00E0: ch = 0x85; break; case 0x00E2: ch = 0x83; break; case 0x00E7: ch = 0x87; break; case 0x00E8: ch = 0x8A; break; case 0x00E9: ch = 0x82; break; case 0x00EA: ch = 0x88; break; case 0x00EB: ch = 0x89; break; case 0x00EE: ch = 0x8C; break; case 0x00EF: ch = 0x8B; break; case 0x00F3: ch = 0xA2; break; case 0x00F4: ch = 0x93; break; case 0x00F7: ch = 0xF6; break; case 0x00F9: ch = 0x97; break; case 0x00FA: ch = 0xA3; break; case 0x00FB: ch = 0x96; break; case 0x00FC: ch = 0x81; break; case 0x0192: ch = 0x9F; break; case 0x0393: ch = 0xE2; break; case 0x0398: ch = 0xE9; break; case 0x03A3: ch = 0xE4; break; case 0x03A6: ch = 0xE8; break; case 0x03A9: ch = 0xEA; break; case 0x03B1: ch = 0xE0; break; case 0x03B4: ch = 0xEB; break; case 0x03B5: ch = 0xEE; break; case 0x03BC: ch = 0xE6; break; case 0x03C0: ch = 0xE3; break; case 0x03C3: ch = 0xE5; break; case 0x03C4: ch = 0xE7; break; case 0x03C6: ch = 0xED; break; case 0x2017: ch = 0x8D; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x203E: ch = 0xA7; break; case 0x207F: ch = 0xFC; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x2219: ch = 0xF9; break; case 0x221A: ch = 0xFB; break; case 0x221E: ch = 0xEC; break; case 0x221F: ch = 0x1C; break; case 0x2229: ch = 0xEF; break; case 0x2248: ch = 0xF7; break; case 0x2261: ch = 0xF0; break; case 0x2264: ch = 0xF3; break; case 0x2265: ch = 0xF2; break; case 0x2302: ch = 0x7F; break; case 0x2310: ch = 0xA9; break; case 0x2320: ch = 0xF4; break; case 0x2321: ch = 0xF5; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2552: ch = 0xD5; break; case 0x2553: ch = 0xD6; break; case 0x2554: ch = 0xC9; break; case 0x2555: ch = 0xB8; break; case 0x2556: ch = 0xB7; break; case 0x2557: ch = 0xBB; break; case 0x2558: ch = 0xD4; break; case 0x2559: ch = 0xD3; break; case 0x255A: ch = 0xC8; break; case 0x255B: ch = 0xBE; break; case 0x255C: ch = 0xBD; break; case 0x255D: ch = 0xBC; break; case 0x255E: ch = 0xC6; break; case 0x255F: ch = 0xC7; break; case 0x2560: ch = 0xCC; break; case 0x2561: ch = 0xB5; break; case 0x2562: ch = 0xB6; break; case 0x2563: ch = 0xB9; break; case 0x2564: ch = 0xD1; break; case 0x2565: ch = 0xD2; break; case 0x2566: ch = 0xCB; break; case 0x2567: ch = 0xCF; break; case 0x2568: ch = 0xD0; break; case 0x2569: ch = 0xCA; break; case 0x256A: ch = 0xD8; break; case 0x256B: ch = 0xD7; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x258C: ch = 0xDD; break; case 0x2590: ch = 0xDE; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266B: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP863 public class ENCibm863 : CP863 { public ENCibm863() : base() {} }; // class ENCibm863 }; // namespace I18N.West
// <copyright file="TangoPoseController.cs" company="Google"> // // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using Tango; using UnityEngine; /// <summary> /// This is a basic movement controller based on /// pose estimation returned from the Tango Service. /// </summary> public class TangoPoseController : MonoBehaviour, ITangoPose { // Tango pose data for debug logging and transform update. [HideInInspector] public string m_tangoServiceVersionName = string.Empty; [HideInInspector] public float m_frameDeltaTime; [HideInInspector] public int m_frameCount; [HideInInspector] public TangoEnums.TangoPoseStatusType m_status; private float m_prevFrameTimestamp; // Tango pose data. private Quaternion m_tangoRotation; private Vector3 m_tangoPosition; // We use couple of matrix transformation to convert the pose from Tango coordinate // frame to Unity coordinate frame. // The full equation is: // Matrix4x4 matrixuwTuc = m_matrixuwTss * matrixssTd * m_matrixdTuc; // // matrixuwTuc: Unity camera with respect to Unity world, this is the desired matrix. // m_matrixuwTss: Constant matrix converting start of service frame to Unity world frame. // matrixssTd: Device frame with repect to start of service frame, this matrix denotes the // pose transform we get from pose callback. // m_matrixdTuc: Constant matrix converting Unity world frame frame to device frame. // // Please see the coordinate system section online for more information: // https://developers.google.com/project-tango/overview/coordinate-systems private Matrix4x4 m_matrixuwTss; private Matrix4x4 m_matrixdTuc; /// @cond /// <summary> /// Initialize the controller. /// </summary> public void Awake() { // Constant matrix converting start of service frame to Unity world frame. m_matrixuwTss = new Matrix4x4(); m_matrixuwTss.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_matrixuwTss.SetColumn(1, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_matrixuwTss.SetColumn(2, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_matrixuwTss.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Constant matrix converting Unity world frame frame to device frame. m_matrixdTuc = new Matrix4x4(); m_matrixdTuc.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_matrixdTuc.SetColumn(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_matrixdTuc.SetColumn(2, new Vector4(0.0f, 0.0f, -1.0f, 0.0f)); m_matrixdTuc.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); m_frameDeltaTime = -1.0f; m_prevFrameTimestamp = -1.0f; m_frameCount = -1; m_status = TangoEnums.TangoPoseStatusType.NA; m_tangoRotation = Quaternion.identity; m_tangoPosition = Vector3.zero; } /// <summary> /// Start this instance. /// </summary> public void Start() { m_tangoServiceVersionName = TangoApplication.GetTangoServiceVersion(); TangoApplication tangoApplication = FindObjectOfType<TangoApplication>(); if (tangoApplication != null) { tangoApplication.Register(this); } else { Debug.Log("No Tango Manager found in scene."); } } /// <summary> /// Unity callback when application is paused. /// </summary> /// <param name="pauseStatus">The pauseStatus as reported by Unity.</param> public void OnApplicationPause(bool pauseStatus) { m_frameDeltaTime = -1.0f; m_prevFrameTimestamp = -1.0f; m_frameCount = -1; m_status = TangoEnums.TangoPoseStatusType.NA; m_tangoRotation = Quaternion.identity; m_tangoPosition = Vector3.zero; } /// <summary> /// Unity callback when the component gets destroyed. /// </summary> public void OnDestroy() { TangoApplication tangoApplication = FindObjectOfType<TangoApplication>(); if (tangoApplication != null) { tangoApplication.Unregister(this); } } /// <summary> /// Handle the callback sent by the Tango Service /// when a new pose is sampled. /// </summary> /// <param name="pose">Pose from Tango.</param> public void OnTangoPoseAvailable(Tango.TangoPoseData pose) { // Get out of here if the pose is null if (pose == null) { Debug.Log("TangoPoseDate is null."); return; } // The callback pose is for device with respect to start of service pose. if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE && pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE) { // Update the stats for the pose for the debug text if (pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { // Create new Quaternion and Vec3 from the pose data received in the event. m_tangoPosition = new Vector3((float)pose.translation[0], (float)pose.translation[1], (float)pose.translation[2]); m_tangoRotation = new Quaternion((float)pose.orientation[0], (float)pose.orientation[1], (float)pose.orientation[2], (float)pose.orientation[3]); // Reset the current status frame count if the status code changed. if (pose.status_code != m_status) { m_frameCount = 0; } m_frameCount++; // Compute delta frame timestamp. m_frameDeltaTime = (float)pose.timestamp - m_prevFrameTimestamp; m_prevFrameTimestamp = (float)pose.timestamp; // Construct the start of service with respect to device matrix from the pose. Matrix4x4 matrixssTd = Matrix4x4.TRS(m_tangoPosition, m_tangoRotation, Vector3.one); // Converting from Tango coordinate frame to Unity coodinate frame. Matrix4x4 matrixuwTuc = m_matrixuwTss * matrixssTd * m_matrixdTuc * TangoSupport.m_devicePoseRotation; // Extract new local position transform.position = matrixuwTuc.GetColumn(3); // Extract new local rotation transform.rotation = Quaternion.LookRotation(matrixuwTuc.GetColumn(2), matrixuwTuc.GetColumn(1)); } else { // if the current pose is not valid we set the pose to identity m_tangoPosition = Vector3.zero; m_tangoRotation = Quaternion.identity; } // Finally, apply the new pose status m_status = pose.status_code; } } /// @endcond }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using Cassandra.Data.Linq; using Cassandra.IntegrationTests.Linq.Structures; using Cassandra.IntegrationTests.SimulacronAPI; using Cassandra.IntegrationTests.SimulacronAPI.Models.Logs; using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then; using Cassandra.IntegrationTests.SimulacronAPI.SystemTables; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Mapping; using Cassandra.Tests.Mapping.Pocos; using NUnit.Framework; #pragma warning disable 612 #pragma warning disable 618 namespace Cassandra.IntegrationTests.Linq.LinqTable { public class CreateTable : SimulacronTest { private const string CreateCqlColumns = "\"boolean_type\" boolean, " + "\"date_time_offset_type\" timestamp, " + "\"date_time_type\" timestamp, " + "\"decimal_type\" decimal, " + "\"double_type\" double, " + "\"float_type\" float, " + "\"guid_type\" uuid, " + "\"int64_type\" bigint, " + "\"int_type\" int, " + "\"list_of_guids_type\" list<uuid>, " + "\"list_of_strings_type\" list<text>, " + "\"map_type_string_long_type\" map<text, bigint>, " + "\"map_type_string_string_type\" map<text, text>, " + "\"nullable_date_time_type\" timestamp, " + "\"nullable_int_type\" int, " + "\"nullable_time_uuid_type\" timeuuid, " + "\"string_type\" text, " + "\"time_uuid_type\" timeuuid"; private const string CreateCqlDefaultColumns = "BooleanType boolean, " + "DateTimeOffsetType timestamp, " + "DateTimeType timestamp, " + "DecimalType decimal, " + "DictionaryStringLongType map<text, bigint>, " + "DictionaryStringStringType map<text, text>, " + "DoubleType double, " + "FloatType float, " + "GuidType uuid, " + "Int64Type bigint, " + "IntType int, " + "ListOfGuidsType list<uuid>, " + "ListOfStringsType list<text>, " + "NullableDateTimeType timestamp, " + "NullableIntType int, " + "NullableTimeUuidType timeuuid, " + "StringType text, " + "TimeUuidType timeuuid"; private const string CreateCqlDefaultColumnsCaseSensitive = "\"BooleanType\" boolean, " + "\"DateTimeOffsetType\" timestamp, " + "\"DateTimeType\" timestamp, " + "\"DecimalType\" decimal, " + "\"DictionaryStringLongType\" map<text, bigint>, " + "\"DictionaryStringStringType\" map<text, text>, " + "\"DoubleType\" double, " + "\"FloatType\" float, " + "\"GuidType\" uuid, " + "\"Int64Type\" bigint, " + "\"IntType\" int, " + "\"ListOfGuidsType\" list<uuid>, " + "\"ListOfStringsType\" list<text>, " + "\"NullableDateTimeType\" timestamp, " + "\"NullableIntType\" int, " + "\"NullableTimeUuidType\" timeuuid, " + "\"StringType\" text, " + "\"TimeUuidType\" timeuuid"; private static readonly string CreateCql = $"CREATE TABLE \"{AllDataTypesEntity.TableName}\" (" + CreateTable.CreateCqlColumns + ", " + "PRIMARY KEY (\"string_type\", \"guid_type\"))"; private static readonly string CreateCqlFormatStr = "CREATE TABLE {0} (" + CreateTable.CreateCqlColumns + ", " + "PRIMARY KEY (\"string_type\", \"guid_type\"))"; private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant(); /// <summary> /// Create a table using the method CreateIfNotExists /// /// @Jira CSHARP-42 https://datastax-oss.atlassian.net/browse/CSHARP-42 /// - Jira detail: CreateIfNotExists causes InvalidOperationException /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateIfNotExist() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); table.CreateIfNotExists(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_CreateIfNotExistAsync() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); table.CreateIfNotExistsAsync().GetAwaiter().GetResult(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } /// <summary> /// Successfully create a table using the method Create /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_Create() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); table.Create(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } [Test, TestCassandraVersion(4, 0, Comparison.LessThan)] public void Should_CreateTable_WhenClusteringOrderAndCompactOptionsAreSet() { var config = new MappingConfiguration().Define( new Map<Tweet>() .PartitionKey(a => a.TweetId) .ClusteringKey(a => a.AuthorId, SortOrder.Descending) .CompactStorage()); var table = new Table<Tweet>(Session, config); table.Create(); VerifyStatement( QueryType.Query, "CREATE TABLE Tweet (AuthorId text, Body text, TweetId uuid, PRIMARY KEY (TweetId, AuthorId)) " + "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", 1); } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_Create() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } [Test, TestCassandraVersion(4, 0, Comparison.LessThan)] public void Should_CreateTableAsync_WhenClusteringOrderAndCompactOptionsAreSet() { var config = new MappingConfiguration().Define( new Map<Tweet>() .PartitionKey(a => a.TweetId) .ClusteringKey(a => a.AuthorId, SortOrder.Descending) .CompactStorage()); var table = new Table<Tweet>(Session, config); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( QueryType.Query, "CREATE TABLE Tweet (AuthorId text, Body text, TweetId uuid, PRIMARY KEY (TweetId, AuthorId)) " + "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", 1); } /// <summary> /// Successfully create a table using the method Create, /// overriding the default table name given via the class' "name" meta-tag /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_Create_NameOverride() { var uniqueTableName = TestUtils.GetUniqueTableName(); var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName); Assert.AreEqual(uniqueTableName, table.Name); table.Create(); VerifyStatement( QueryType.Query, CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), 1); } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_Create_NameOverride() { var uniqueTableName = TestUtils.GetUniqueTableName(); var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName); Assert.AreEqual(uniqueTableName, table.Name); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( QueryType.Query, CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), 1); } /// <summary> /// Attempt to create the same table using the method Create twice, validate expected failure message /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateTable_AlreadyExists() { var tableName = "tbl_already_exists_1"; var config = new MappingConfiguration().Define( new Map<AllDataTypesEntity>().TableName(tableName).PartitionKey(a => a.TimeUuidType)); var table = new Table<AllDataTypesEntity>(Session, config); table.Create(); VerifyStatement( QueryType.Query, $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", 1); TestCluster.PrimeFluent( b => b.WhenQuery( $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))") .ThenAlreadyExists(_uniqueKsName, tableName)); var ex = Assert.Throws<AlreadyExistsException>(() => table.Create()); Assert.AreEqual(tableName, ex.Table); Assert.AreEqual(_uniqueKsName, ex.Keyspace); } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_CreateTable_AlreadyExists() { var tableName = "tbl_already_exists_1"; var config = new MappingConfiguration().Define( new Map<AllDataTypesEntity>().TableName(tableName).PartitionKey(a => a.TimeUuidType)); var table = new Table<AllDataTypesEntity>(Session, config); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( QueryType.Query, $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", 1); TestCluster.PrimeFluent( b => b.WhenQuery( $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))") .ThenAlreadyExists(_uniqueKsName, tableName)); var ex = Assert.Throws<AlreadyExistsException>(() => table.Create()); Assert.AreEqual(tableName, ex.Table); Assert.AreEqual(_uniqueKsName, ex.Keyspace); } /// <summary> /// Attempt to create two tables of different types but with the same name using the Create method. /// Validate expected failure message /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateTable_SameNameDifferentTypeAlreadyExists() { // First table name creation works as expected const string staticTableName = "staticTableName_1"; var mappingConfig1 = new MappingConfiguration().Define(new Map<AllDataTypesEntity>().TableName(staticTableName).CaseSensitive().PartitionKey(c => c.StringType)); var allDataTypesTable = new Table<AllDataTypesEntity>(Session, mappingConfig1); allDataTypesTable.Create(); VerifyStatement( QueryType.Query, $"CREATE TABLE \"{staticTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))", 1); // Second creation attempt with same table name should fail TestCluster.PrimeFluent( b => b.WhenQuery( $"CREATE TABLE \"{staticTableName}\" (\"Director\" text, " + "\"ExampleSet\" list<text>, \"MainActor\" text, " + "\"MovieMaker\" text, \"Title\" text, \"Year\" int, " + "PRIMARY KEY (\"Title\"))") .ThenAlreadyExists(_uniqueKsName, staticTableName)); var mappingConfig2 = new MappingConfiguration().Define(new Map<Movie>().TableName(staticTableName).CaseSensitive().PartitionKey(c => c.Title)); var movieTable = new Table<Movie>(Session, mappingConfig2); Assert.Throws<AlreadyExistsException>(() => movieTable.Create()); } /// <summary> /// Attempt to create two tables of different types but with the same name using the Create method, /// setting table name of second create request via table name override option in constructor /// Validate expected failure message /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateTable_SameNameDifferentTypeAlreadyExists_TableNameOverride() { // First table name creation works as expected const string staticTableName = "staticTableName_2"; var mappingConfig = new MappingConfiguration().Define(new Map<AllDataTypesEntity>().TableName(staticTableName).CaseSensitive().PartitionKey(c => c.StringType)); var allDataTypesTable = new Table<AllDataTypesEntity>(Session, mappingConfig); allDataTypesTable.Create(); VerifyStatement( QueryType.Query, $"CREATE TABLE \"{staticTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))", 1); // Second creation attempt with same table name should fail TestCluster.PrimeFluent( b => b.WhenQuery( $"CREATE TABLE \"{staticTableName}\" (" + "\"director\" text, \"list\" list<text>, \"mainGuy\" text, " + "\"movie_maker\" text, \"unique_movie_title\" text, " + "\"yearMade\" int, " + "PRIMARY KEY ((\"unique_movie_title\", \"movie_maker\"), \"director\"))") .ThenAlreadyExists(_uniqueKsName, staticTableName)); var movieTable = new Table<Movie>(Session, new MappingConfiguration(), staticTableName); Assert.Throws<AlreadyExistsException>(() => movieTable.Create()); } /// <summary> /// Attempt to create a table in a non-existent keyspace, specifying the keyspace name in Table constructor's override option /// Validate error message. /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_Create_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); } else { TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.Invalid, "msg")); } var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); if(!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { Assert.Throws<InvalidConfigurationInQueryException>(() => table.Create()); } else { Assert.Throws<InvalidQueryException>(() => table.Create()); } } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_Create_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); } else { TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.Invalid, "msg")); } var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); if(!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { Assert.ThrowsAsync<InvalidConfigurationInQueryException>(() => table.CreateAsync()); } else { Assert.ThrowsAsync<InvalidQueryException>(() => table.CreateAsync()); } } /// <summary> /// Attempt to create a table in a non-existent keyspace, specifying the keyspace name in Table constructor's override option /// Validate error message. /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateIfNotExists_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); Assert.Throws<InvalidConfigurationInQueryException>(() => table.CreateIfNotExists()); } [Test, TestCassandraVersion(2, 0)] public void TableCreateAsync_CreateIfNotExists_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); Assert.ThrowsAsync<InvalidConfigurationInQueryException>(() => table.CreateIfNotExistsAsync()); } /// <summary> /// Successfully create two tables with the same name in two different keyspaces using the method Create /// Do not manually change the session to use the different keyspace /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_Create_TwoTablesSameName_TwoKeyspacesDifferentNames_KeyspaceOverride() { // Setup first table var sharedTableName = typeof(AllDataTypesEntity).Name; var mappingConfig = new MappingConfiguration().Define(new Map<AllDataTypesEntity>() .TableName(sharedTableName).CaseSensitive().PartitionKey(c => c.StringType)); var table1 = new Table<AllDataTypesEntity>(Session, mappingConfig); table1.Create(); VerifyStatement( QueryType.Query, $"CREATE TABLE \"{sharedTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))", 1); WriteReadValidate(table1); // Create second table with same name in new keyspace var newUniqueKsName = TestUtils.GetUniqueKeyspaceName(); Session.CreateKeyspace(newUniqueKsName); VerifyStatement( QueryType.Query, $"CREATE KEYSPACE \"{newUniqueKsName}\" " + "WITH replication = {'class' : 'SimpleStrategy', 'replication_factor' : '1'}" + " AND durable_writes = true", 1); Assert.AreNotEqual(_uniqueKsName, newUniqueKsName); var table2 = new Table<AllDataTypesEntity>(Session, mappingConfig, sharedTableName, newUniqueKsName); table2.Create(); VerifyStatement( QueryType.Query, $"CREATE TABLE \"{newUniqueKsName}\".\"{sharedTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))", 1); WriteReadValidate(table2); // also use ChangeKeyspace and validate client functionality Session.ChangeKeyspace(_uniqueKsName); VerifyStatement(QueryType.Query, $"USE \"{_uniqueKsName}\"", 1); WriteReadValidate(table1); Session.ChangeKeyspace(newUniqueKsName); VerifyStatement(QueryType.Query, $"USE \"{newUniqueKsName}\"", 1); WriteReadValidate(table2); } /// <summary> /// Table creation fails because the referenced class is missing a partition key /// This also validates that a private class can be used with the Table.Create() method. /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_ClassMissingPartitionKey() { var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PrivateClassMissingPartitionKey), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PrivateClassMissingPartitionKey))); var table = new Table<PrivateClassMissingPartitionKey>(Session, mappingConfig); try { table.Create(); } catch (InvalidOperationException e) { Assert.AreEqual("No partition key defined", e.Message); } } /// <summary> /// Table creation fails because the referenced class is missing a partition key /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_ClassEmpty() { var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PrivateEmptyClass), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PrivateEmptyClass))); var table = new Table<PrivateEmptyClass>(Session, mappingConfig); try { table.Create(); } catch (InvalidOperationException e) { Assert.AreEqual("No partition key defined", e.Message); } } [Test, TestCassandraVersion(2, 1)] public void CreateTable_With_Frozen_Tuple() { var config = new MappingConfiguration().Define(new Map<UdtAndTuplePoco>() .PartitionKey(p => p.Id1) .Column(p => p.Id1) .Column(p => p.Tuple1, cm => cm.WithName("t").AsFrozen()) .TableName("tbl_frozen_tuple") .ExplicitColumns()); var table = new Table<UdtAndTuplePoco>(Session, config); table.Create(); VerifyStatement( QueryType.Query, "CREATE TABLE tbl_frozen_tuple (Id1 uuid, t frozen<tuple<bigint, bigint, text>>, PRIMARY KEY (Id1))", 1); PrimeSystemSchemaTables( _uniqueKsName, "tbl_frozen_tuple", new [] { new StubTableColumn("Id1", StubColumnKind.PartitionKey, DataType.Uuid), new StubTableColumn("t", StubColumnKind.Regular, DataType.Frozen(DataType.Tuple(DataType.BigInt, DataType.BigInt, DataType.Text))) }); SessionCluster.RefreshSchema(_uniqueKsName, "tbl_frozen_tuple"); var tableMeta = SessionCluster.Metadata.GetTable(_uniqueKsName, "tbl_frozen_tuple"); Assert.NotNull(tableMeta); Assert.AreEqual(2, tableMeta.TableColumns.Length); var column = tableMeta.ColumnsByName["t"]; Assert.AreEqual(ColumnTypeCode.Tuple, column.TypeCode); } [Test, TestCassandraVersion(2, 0, 7)] public void CreateTable_With_Counter_Static() { var config = new MappingConfiguration() .Define(new Map<AllTypesEntity>().ExplicitColumns() .TableName("tbl_with_counter_static") .PartitionKey(t => t.UuidValue) .ClusteringKey(t => t.StringValue) .Column(t => t.UuidValue, cm => cm.WithName("id1")) .Column(t => t.StringValue, cm => cm.WithName("id2")) .Column(t => t.Int64Value, cm => cm.WithName("counter_col1") .AsCounter().AsStatic()) .Column(t => t.IntValue, cm => cm.WithName("counter_col2") .AsCounter())); var table = new Table<AllTypesEntity>(Session, config); table.Create(); VerifyStatement( QueryType.Query, "CREATE TABLE tbl_with_counter_static (" + "counter_col1 counter static, counter_col2 counter, id1 uuid, id2 text, " + "PRIMARY KEY (id1, id2))", 1); PrimeSystemSchemaTables( _uniqueKsName, "tbl_with_counter_static", new [] { new StubTableColumn("counter_col1", StubColumnKind.Regular, DataType.Counter), new StubTableColumn("counter_col2", StubColumnKind.Regular, DataType.Counter), new StubTableColumn("id1", StubColumnKind.PartitionKey, DataType.Uuid), new StubTableColumn("id2", StubColumnKind.ClusteringKey, DataType.Text) }); SessionCluster.RefreshSchema(_uniqueKsName, "tbl_with_counter_static"); var tableMeta = SessionCluster.Metadata.GetTable(_uniqueKsName, "tbl_with_counter_static"); Assert.AreEqual(4, tableMeta.TableColumns.Length); } /// <summary> /// Successfully create a table using the null column name /// </summary> [Test, TestCassandraVersion(2, 0)] public void TableCreate_CreateWithPropertyName() { var table = new Table<TestEmptyClusteringColumnName>(Session, MappingConfiguration.Global); table.CreateIfNotExists(); VerifyStatement( QueryType.Query, "CREATE TABLE \"test_empty_clustering_column_name\" (" + "\"cluster\" text, \"id\" int, \"value\" text, " + "PRIMARY KEY (\"id\", \"cluster\"))", 1); } /////////////////////////////////////////////// // Test Helpers ////////////////////////////////////////////// // AllDataTypes private void WriteReadValidateUsingTableMethods(Table<AllDataTypesEntity> table) { TestCluster.PrimeDelete(); var ksAndTable = table.KeyspaceName == null ? $"\"{table.Name}\"" : $"\"{table.KeyspaceName}\".\"{table.Name}\""; var expectedDataTypesEntityRow = AllDataTypesEntity.GetRandomInstance(); var uniqueKey = expectedDataTypesEntityRow.StringType; // insert record Session.Execute(table.Insert(expectedDataTypesEntityRow)); VerifyStatement( QueryType.Query, string.Format( AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, ksAndTable), 1, expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()); // select record TestCluster.PrimeFluent( b => b.WhenQuery( string.Format(AllDataTypesEntity.SelectCqlDefaultColumnsFormatStr, ksAndTable), p => p.WithParam(uniqueKey)) .ThenRowsSuccess( AllDataTypesEntity.GetDefaultColumns(), r => r.WithRow(expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()))); var listOfAllDataTypesObjects = (from x in table where x.StringType.Equals(uniqueKey) select x) .Execute().ToList(); Assert.NotNull(listOfAllDataTypesObjects); Assert.AreEqual(1, listOfAllDataTypesObjects.Count); var actualDataTypesEntityRow = listOfAllDataTypesObjects.First(); expectedDataTypesEntityRow.AssertEquals(actualDataTypesEntityRow); } private void WriteReadValidateUsingSessionBatch(Table<AllDataTypesEntity> table) { TestCluster.PrimeDelete(); var ksAndTable = table.KeyspaceName == null ? $"\"{table.Name}\"" : $"\"{table.KeyspaceName}\".\"{table.Name}\""; var batch = Session.CreateBatch(); var expectedDataTypesEntityRow = AllDataTypesEntity.GetRandomInstance(); var uniqueKey = expectedDataTypesEntityRow.StringType; batch.Append(table.Insert(expectedDataTypesEntityRow)); batch.Execute(); VerifyBatchStatement( 1, new [] { string.Format( AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, ksAndTable) }, new [] { expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns() }); TestCluster.PrimeFluent( b => b.WhenQuery( string.Format(AllDataTypesEntity.SelectCqlDefaultColumnsFormatStr, ksAndTable), p => p.WithParam(uniqueKey)) .ThenRowsSuccess( AllDataTypesEntity.GetDefaultColumns(), r => r.WithRow(expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()))); var listOfAllDataTypesObjects = (from x in table where x.StringType.Equals(uniqueKey) select x) .Execute().ToList(); Assert.NotNull(listOfAllDataTypesObjects); Assert.AreEqual(1, listOfAllDataTypesObjects.Count); var actualDataTypesEntityRow = listOfAllDataTypesObjects.First(); expectedDataTypesEntityRow.AssertEquals(actualDataTypesEntityRow); } private void WriteReadValidate(Table<AllDataTypesEntity> table) { WriteReadValidateUsingSessionBatch(table); WriteReadValidateUsingTableMethods(table); } private class PrivateClassMissingPartitionKey { //Is never used, but don't mind #pragma warning disable 414, 169 // ReSharper disable once InconsistentNaming private string StringValue = "someStringValue"; #pragma warning restore 414, 169 } private class PrivateEmptyClass { } [Table("test_empty_clustering_column_name")] // ReSharper disable once ClassNeverInstantiated.Local private class TestEmptyClusteringColumnName { [PartitionKey] [Column("id")] // ReSharper disable once UnusedMember.Local public int Id { get; set; } [ClusteringKey(1)] [Column] // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local public string cluster { get; set; } [Column] // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local public string value { get; set; } } } }
using System; using NUnit.Framework; using System.Text.RegularExpressions; using System.Drawing; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Interactions { [TestFixture] [IgnoreBrowser(Browser.Safari, "Not implemented (issue 4136)")] public class BasicMouseInterfaceTest : DriverTestFixture { [SetUp] public void SetupTest() { IActionExecutor actionExecutor = driver as IActionExecutor; if (actionExecutor != null) { actionExecutor.ResetInputState(); } } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDraggingElementWithMouseMovesItToAnotherList() { PerformDragAndDropWithMouse(); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); Assert.AreEqual(6, dragInto.FindElements(By.TagName("li")).Count); } // This test is very similar to DraggingElementWithMouse. The only // difference is that this test also verifies the correct events were fired. [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void DraggingElementWithMouseFiresEvents() { PerformDragAndDropWithMouse(); IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); // This is failing under HtmlUnit. A bug was filed. Assert.IsTrue(Regex.IsMatch(dragReporter.Text, "Nothing happened\\. (?:DragOut *)+DropIn RightItem 3")); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDoubleClickThenNavigate() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); driver.Url = droppableItems; } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDragAndDrop() { driver.Url = droppableItems; DateTime waitEndTime = DateTime.Now.Add(TimeSpan.FromSeconds(15)); while (!IsElementAvailable(driver, By.Id("draggable")) && (DateTime.Now < waitEndTime)) { System.Threading.Thread.Sleep(200); } if (!IsElementAvailable(driver, By.Id("draggable"))) { throw new Exception("Could not find draggable element after 15 seconds."); } IWebElement toDrag = driver.FindElement(By.Id("draggable")); IWebElement dropInto = driver.FindElement(By.Id("droppable")); Actions actionProvider = new Actions(driver); IAction holdDrag = actionProvider.ClickAndHold(toDrag).Build(); IAction move = actionProvider.MoveToElement(dropInto).Build(); IAction drop = actionProvider.Release(dropInto).Build(); holdDrag.Perform(); move.Perform(); drop.Perform(); dropInto = driver.FindElement(By.Id("droppable")); string text = dropInto.FindElement(By.TagName("p")).Text; Assert.AreEqual("Dropped!", text); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDoubleClick() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); Assert.AreEqual("DoubleClicked", toDoubleClick.GetAttribute("value")); } [Test] //[IgnoreBrowser(Browser.Chrome, "ChromeDriver2 does not perform this yet")] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowContextClick() { driver.Url = javascriptPage; IWebElement toContextClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.ContextClick(toContextClick).Build(); contextClick.Perform(); Assert.AreEqual("ContextClicked", toContextClick.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Remote, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Safari, "API not implemented in driver")] public void ShouldAllowMoveAndClick() { driver.Url = javascriptPage; IWebElement toClick = driver.FindElement(By.Id("clickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.MoveToElement(toClick).Click().Build(); contextClick.Perform(); Assert.AreEqual("Clicked", toClick.GetAttribute("value"), "Value should change to Clicked."); } [Test] [IgnoreBrowser(Browser.IE, "Clicking without context is perfectly valid for W3C-compliant remote ends.")] [IgnoreBrowser(Browser.Firefox, "Clicking without context is perfectly valid for W3C-compliant remote ends.")] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Remote, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Safari, "API not implemented in driver")] public void ShouldNotMoveToANullLocator() { driver.Url = javascriptPage; try { IAction contextClick = new Actions(driver).MoveToElement(null).Build(); contextClick.Perform(); Assert.Fail("Shouldn't be allowed to click on null element."); } catch (ArgumentException) { // Expected. } try { new Actions(driver).Click().Build().Perform(); Assert.Fail("Shouldn't be allowed to click without a context."); } catch (Exception) { // expected } } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Opera, "API not implemented in driver")] public void ShouldClickElementInIFrame() { driver.Url = clicksPage; try { driver.SwitchTo().Frame("source"); IWebElement element = driver.FindElement(By.Id("otherframe")); new Actions(driver).MoveToElement(element).Click().Perform(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); WaitFor(() => { return driver.FindElement(By.Id("span")).Text == "An inline element"; }, "Could not find element with text 'An inline element'"); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void ShouldAllowUsersToHoverOverElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("menu1")); if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { Assert.Ignore("Skipping test: Simulating hover needs native events"); } IHasInputDevices inputDevicesDriver = driver as IHasInputDevices; if (inputDevicesDriver == null) { return; } IWebElement item = driver.FindElement(By.Id("item1")); Assert.AreEqual("", item.Text); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element); //element.Hover(); Actions actionBuilder = new Actions(driver); actionBuilder.MoveToElement(element).Perform(); item = driver.FindElement(By.Id("item1")); Assert.AreEqual("Item 1", item.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MovingMouseByRelativeOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 50, 200), "Coordinate matching was not within tolerance"); new Actions(driver).MoveByOffset(10, 20).Build().Perform(); WaitFor(FuzzyMatchingOfCoordinates(reporter, 60, 220), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MovingMouseToRelativeElementOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv, 95, 195).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 95, 195), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MoveRelativeToBody() { driver.Url = mouseTrackerPage; new Actions(driver).MoveByOffset(50, 100).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 40, 20), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void CanMouseOverAndOutOfAnElement() { driver.Url = mouseOverPage; IWebElement greenbox = driver.FindElement(By.Id("greenbox")); IWebElement redbox = driver.FindElement(By.Id("redbox")); Size size = redbox.Size; new Actions(driver).MoveToElement(greenbox, 1, 1).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); new Actions(driver).MoveToElement(redbox).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(255, 0, 0, 1)").Or.EqualTo("rgb(255, 0, 0)")); new Actions(driver).MoveToElement(redbox, size.Width + 2, size.Height + 2).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); } private Func<bool> FuzzyMatchingOfCoordinates(IWebElement element, int x, int y) { return () => { return FuzzyPositionMatching(x, y, element.Text); }; } private bool FuzzyPositionMatching(int expectedX, int expectedY, String locationTuple) { string[] splitString = locationTuple.Split(','); int gotX = int.Parse(splitString[0].Trim()); int gotY = int.Parse(splitString[1].Trim()); // Everything within 5 pixels range is OK const int ALLOWED_DEVIATION = 5; return Math.Abs(expectedX - gotX) < ALLOWED_DEVIATION && Math.Abs(expectedY - gotY) < ALLOWED_DEVIATION; } private void PerformDragAndDropWithMouse() { driver.Url = draggableLists; IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); IWebElement toDrag = driver.FindElement(By.Id("rightitem-3")); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); IAction holdItem = new Actions(driver).ClickAndHold(toDrag).Build(); IAction moveToSpecificItem = new Actions(driver).MoveToElement(driver.FindElement(By.Id("leftitem-4"))).Build(); IAction moveToOtherList = new Actions(driver).MoveToElement(dragInto).Build(); IAction drop = new Actions(driver).Release(dragInto).Build(); Assert.AreEqual("Nothing happened.", dragReporter.Text); holdItem.Perform(); moveToSpecificItem.Perform(); moveToOtherList.Perform(); Assert.IsTrue(Regex.IsMatch(dragReporter.Text, "Nothing happened\\. (?:DragOut *)+")); drop.Perform(); } private bool IsElementAvailable(IWebDriver driver, By locator) { try { driver.FindElement(locator); return true; } catch (NoSuchElementException) { return false; } } } }
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 MusicPickerService.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.Text; namespace Hydra.Framework.ImageProcessing.Analysis.Maths { // //********************************************************************** /// <summary> /// Set of statistics functions /// </summary> //********************************************************************** // public class Statistics { #region Statics // //********************************************************************** /// <summary> /// Calculate mean value /// Input: histogram array /// </summary> /// <param name="values">The values.</param> /// <returns></returns> //********************************************************************** // public static double Mean(int[] values) { int v; int mean = 0; int total = 0; // for all values for (int i = 0, n = values.Length; i < n; i++) { v = values[i]; // accumulate mean mean += i * v; // accumalate total total += v; } return (double) mean / total; } // //********************************************************************** /// <summary> /// Calculate standard deviation /// Input: histogram array /// </summary> /// <param name="values">The values.</param> /// <returns></returns> //********************************************************************** // public static double StdDev(int[] values) { double mean = Mean(values); double stddev = 0; double t; int v; int total = 0; // for all values for (int i = 0, n = values.Length; i < n; i++) { v = values[i]; t = (double) i - mean; // accumulate mean stddev += t * t * v; // accumalate total total += v; } return Math.Sqrt(stddev / total); } // //********************************************************************** /// <summary> /// Calculate median value /// Input: histogram array /// </summary> /// <param name="values">The values.</param> /// <returns></returns> //********************************************************************** // public static int Median(int[] values) { int total = 0, n = values.Length; // for all values for (int i = 0; i < n; i++) { // accumalate total total += values[i]; } int halfTotal = total / 2; int median, v; // find median value for (median = 0, v = 0; median < n; median++) { v += values[median]; if (v >= halfTotal) break; } return median; } // //********************************************************************** /// <summary> /// Get range around median containing specified percentile of values /// Input: histogram array /// </summary> /// <param name="values">The values.</param> /// <param name="percent">The percent.</param> /// <returns></returns> //********************************************************************** // public static Range GetRange(int[] values, double percent) { int total = 0, n = values.Length; // for all values for (int i = 0; i < n; i++) { // accumalate total total += values[i]; } int min, max, v; int h = (int)(total * (percent + (1 - percent) / 2)); // get range min value for (min = 0, v = total; min < n; min++) { v -= values[min]; if (v < h) break; } // get range max value for (max = n - 1, v = total; max >= 0; max--) { v -= values[max]; if (v < h) break; } return new Range(min, max); } // //********************************************************************** /// <summary> /// Calculate an entropy /// Input: histogram array /// </summary> /// <param name="values">The values.</param> /// <returns></returns> //********************************************************************** // public static double Entropy(int[] values) { int total = 0; for (int i = 0, n = values.Length; i < n; i++) { total += values[i]; } return Entropy(values, total); } // //********************************************************************** /// <summary> /// Entropies the specified values. /// </summary> /// <param name="values">The values.</param> /// <param name="total">The total.</param> /// <returns></returns> //********************************************************************** // public static double Entropy(int[] values, int total) { int n = values.Length; double e = 0; double p; // for all values for (int i = 0; i < n; i++) { // get item probability p = (double) values[i] / total; // calculate entropy if (p != 0) e += (-p * Math.Log(p, 2)); } return e; } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2014-2015 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Diagnostics.Contracts; using System.IO; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers { /// <summary> /// <see cref="EnumSerializerEmitter"/> using instance fields to hold serializers for target members. /// </summary> internal sealed class FieldBasedEnumSerializerEmitter : EnumSerializerEmitter { private static readonly Type[] ContextConstructorParameterTypes = { typeof( SerializationContext ) }; private static readonly Type[] ContextAndEnumSerializationMethodConstructorParameterTypes = { typeof( SerializationContext ), typeof( EnumSerializationMethod ) }; private readonly ConstructorBuilder _contextConstructorBuilder; private readonly ConstructorBuilder _contextAndEnumSerializationMethodConstructorBuilder; private readonly EnumSerializationMethod _defaultEnumSerializationMethod; private readonly TypeBuilder _typeBuilder; private readonly MethodBuilder _packUnderlyingValueToMethodBuilder; private readonly MethodBuilder _unpackFromUnderlyingValueMethodBuilder; private readonly bool _isDebuggable; /// <summary> /// Initializes a new instance of the <see cref="FieldBasedSerializerEmitter"/> class. /// </summary> /// <param name="context">A <see cref="SerializationContext"/>.</param> /// <param name="host">The host <see cref="ModuleBuilder"/>.</param> /// <param name="specification">The specification of the serializer.</param> /// <param name="isDebuggable">Set to <c>true</c> when <paramref name="host"/> is debuggable.</param> public FieldBasedEnumSerializerEmitter( SerializationContext context, ModuleBuilder host, SerializerSpecification specification, bool isDebuggable ) { Contract.Requires( host != null ); Contract.Requires( specification != null ); Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, "Create {0}", specification.SerializerTypeFullName ); this._typeBuilder = host.DefineType( specification.SerializerTypeFullName, TypeAttributes.Sealed | TypeAttributes.Public | TypeAttributes.UnicodeClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit, typeof( EnumMessagePackSerializer<> ).MakeGenericType( specification.TargetType ) ); this._contextConstructorBuilder = this._typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, ContextConstructorParameterTypes ); this._defaultEnumSerializationMethod = context.EnumSerializationMethod; this._contextAndEnumSerializationMethodConstructorBuilder = this._typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, ContextAndEnumSerializationMethodConstructorParameterTypes ); this._packUnderlyingValueToMethodBuilder = this._typeBuilder.DefineMethod( "PackUnderlyingValueTo", MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof( void ), new[] { typeof( Packer ), specification.TargetType } ); this._unpackFromUnderlyingValueMethodBuilder = this._typeBuilder.DefineMethod( "UnpackFromUnderlyingValue", MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig, CallingConventions.HasThis, specification.TargetType, UnpackFromUnderlyingValueParameterTypes ); var baseType = this._typeBuilder.BaseType; #if DEBUG Contract.Assert( baseType != null, "baseType != null" ); #endif this._typeBuilder.DefineMethodOverride( this._packUnderlyingValueToMethodBuilder, baseType.GetMethod( this._packUnderlyingValueToMethodBuilder.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) ); this._typeBuilder.DefineMethodOverride( this._unpackFromUnderlyingValueMethodBuilder, baseType.GetMethod( this._unpackFromUnderlyingValueMethodBuilder.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) ); this._isDebuggable = isDebuggable; #if !SILVERLIGHT && !NETFX_35 if ( isDebuggable && SerializerDebugging.DumpEnabled ) { SerializerDebugging.PrepareDump( host.Assembly as AssemblyBuilder ); } #endif } public override TracingILGenerator GetPackUnderyingValueToMethodILGenerator() { if ( SerializerDebugging.TraceEnabled ) { SerializerDebugging.TraceEvent( "{0}->{1}::{2}", MethodBase.GetCurrentMethod(), this._typeBuilder.Name, this._packUnderlyingValueToMethodBuilder ); } return new TracingILGenerator( this._packUnderlyingValueToMethodBuilder, SerializerDebugging.ILTraceWriter, this._isDebuggable ); } public override TracingILGenerator GetUnpackFromUnderlyingValueMethodILGenerator() { if ( SerializerDebugging.TraceEnabled ) { SerializerDebugging.TraceEvent( "{0}->{1}::{2}", MethodBase.GetCurrentMethod(), this._typeBuilder.Name, this._unpackFromUnderlyingValueMethodBuilder ); } return new TracingILGenerator( this._unpackFromUnderlyingValueMethodBuilder, SerializerDebugging.ILTraceWriter, this._isDebuggable ); } public override Func<SerializationContext, EnumSerializationMethod, MessagePackSerializer<T>> CreateConstructor<T>() { if ( !this._typeBuilder.IsCreated() ) { Contract.Assert( this._typeBuilder.BaseType != null ); /* * .ctor( SerializationContext c ) * : this( c, DEFAULT_METHOD ) * { * } */ var il1 = new TracingILGenerator( this._contextConstructorBuilder, TextWriter.Null, this._isDebuggable ); // : this( c, DEFAULT_METHOD ) il1.EmitLdarg_0(); il1.EmitLdarg_1(); il1.EmitAnyLdc_I4( ( int ) this._defaultEnumSerializationMethod ); il1.EmitCallConstructor( this._contextAndEnumSerializationMethodConstructorBuilder ); il1.EmitRet(); /* * .ctor( SerializationContext c, EnumSerializerMethod method ) * : base( c, method ) * { * } */ var il2 = new TracingILGenerator( this._contextAndEnumSerializationMethodConstructorBuilder, TextWriter.Null, this._isDebuggable ); // : base( c, method ) il2.EmitLdarg_0(); il2.EmitLdarg_1(); il2.EmitLdarg_2(); il2.EmitCallConstructor( this._typeBuilder.BaseType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, ContextAndEnumSerializationMethodConstructorParameterTypes, null ) ); il2.EmitRet(); } var ctor = this._typeBuilder.CreateType().GetConstructor( ContextAndEnumSerializationMethodConstructorParameterTypes ); var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" ); var methodParameter = Expression.Parameter( typeof( EnumSerializationMethod ), "method" ); #if DEBUG Contract.Assert( ctor != null, "ctor != null" ); #endif return Expression.Lambda<Func<SerializationContext, EnumSerializationMethod, MessagePackSerializer<T>>>( Expression.New( ctor, contextParameter, methodParameter ), contextParameter, methodParameter ).Compile(); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // ExtensionsTest.cs - NUnit Test Cases for Extensions.cs class under // System.Xml.Schema namespace found in System.Xml.Linq assembly // (System.Xml.Linq.dll) // // Author: // Stefan Prutianu (stefanprutianu@yahoo.com) // // (C) Stefan Prutianu // using System; using System.Xml; using System.IO; using Network = System.Net; using System.Xml.Linq; using System.Xml.Schema; using System.Collections.Generic; using ExtensionsClass = System.Xml.Schema.Extensions; using Xunit; namespace CoreXml.Test.XLinq { public class SchemaExtensionsTests { public static string xsdString; public static XmlSchemaSet schemaSet; public static string xmlString; public static XDocument xmlDocument; public static bool validationSucceded; // initialize values for tests public SchemaExtensionsTests() { xsdString = @"<?xml version='1.0'?> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='note'> <xs:complexType> <xs:sequence> <xs:element name='to' type='xs:string'/> <xs:element name='from' type='xs:string'/> <xs:element name='heading' type='xs:string'/> <xs:element name='ps' type='xs:string' maxOccurs='1' minOccurs = '0' default='Bye!'/> <xs:element name='body'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:minLength value='5'/> <xs:maxLength value='30'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> <xs:attribute name='subject' type='xs:string' default='mono'/> <xs:attribute name='date' type='xs:date' use='required'/> </xs:complexType> </xs:element> </xs:schema>"; schemaSet = new XmlSchemaSet(); schemaSet.Add("", XmlReader.Create(new StringReader(xsdString))); xmlString = @"<?xml version='1.0'?> <note date ='2010-05-26'> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget to call me!</body> </note>"; xmlDocument = XDocument.Load(new StringReader(xmlString)); validationSucceded = false; /* * Use this method to load the above data from disk * Comment the above code when using this method. * Also the arguments for the folowing tests: XAttributeSuccessValidate * XAttributeFailValidate, XAttributeThrowExceptionValidate, XElementSuccessValidate * XElementFailValidate,XElementThrowExceptionValidate, XAttributeGetSchemaInfo * XElementGetSchemaInfo may need to be changed. */ //LoadOutsideDocuments ("c:\\note.xsd", "c:\\note.xml"); } // Use this method to load data from disk public static void LoadOutsideDocuments(string xsdDocumentPath, string xmlDocumentPath) { // Create a resolver with default credentials. XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = Network.CredentialCache.DefaultCredentials; // Set the reader settings object to use the resolver. XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = resolver; // Create the XmlReader object. XmlReader reader = XmlReader.Create(xsdDocumentPath, settings); schemaSet = new XmlSchemaSet(); schemaSet.Add("", reader); reader = XmlReader.Create(xmlDocumentPath, settings); xmlDocument = XDocument.Load(reader); validationSucceded = false; } // this gets called when a validation error occurs public void TestValidationHandler(object sender, ValidationEventArgs e) { validationSucceded = false; } // test succesfull validation [Fact] public void XDocumentSuccessValidate() { validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // test failed validation [Fact] public void XDocumentFailValidate() { string elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema */ [Fact] public void XDocumentThrowExceptionValidate() { string elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate (xmlDocument, schemaSet, null)); } /* * test xml validation populating the XML tree with * the post-schema-validation infoset(PSVI) */ [Fact] public void XDocumentAddSchemaInfoValidate() { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.True(afterNoOfAttributes >= beforeNoOfAttributes, "XDocumentAddSchemaInfoValidate, wrong newAttributes value."); Assert.True(afterNoOfElements >= beforeNoOfElements, "XDocumentAddSchemaInfoValidate, wrong newElements value."); } /* * test xml validation without populating the XML tree with * the post-schema-validation infoset(PSVI). */ [Fact] public void XDocumentNoSchemaInfoValidate () { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // don't populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), false); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.Equal(afterNoOfAttributes, beforeNoOfAttributes); Assert.Equal(afterNoOfElements, beforeNoOfElements); } // attribute validation succeeds after change [Fact] public void XAttributeSuccessValidate () { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-05-27"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute (attributeName); date.SetValue (attributeValue); ExtensionsClass.Validate (date, date.GetSchemaInfo ().SchemaAttribute,schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // attribute validation fails after change [Fact] public void XAttributeFailValidate() { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); ExtensionsClass.Validate(date, date.GetSchemaInfo ().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after attribute value change */ [Fact] public void XAttributeThrowExceptionValidate() { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(date, date.GetSchemaInfo().SchemaAttribute, schemaSet, null)); } // element validation succeeds after change [Fact] public void XElementSuccessValidate() { string parentElementName = "note"; string childElementName = "body"; object childElementValue = "Please call me!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // element validation fails after change [Fact] public void XElementFailValidate() { string parentElementName = "note"; string childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after element value change */ [Fact] public void XElementThrowExceptionValidate() { string parentElementName = "note" ; string childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, null)); } // test attribute schema info [Fact] public void XAttributeGetSchemaInfo () { string elementName = "note"; string attributeName = "date"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate attribute XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); ExtensionsClass.Validate (date, date.GetSchemaInfo().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(date); Assert.NotNull(schemaInfo); } // test element schema info [Fact] public void XElementGetSchemaInfo() { string elementName = "body"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate element XElement body = xmlDocument.Root.Element(elementName); ExtensionsClass.Validate(body, body.GetSchemaInfo ().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(body); Assert.NotNull(schemaInfo); } } }
using Lewis.SST.SecurityMethods; using System; using System.Collections; using System.Data; using System.Data.SqlClient; namespace Lewis.SST.SQLMethods { /// <summary> /// SQL server login security types /// </summary> public enum SecurityType { /// <summary> /// indicates using integrated Windows login security model. /// </summary> Integrated = 0, /// <summary> /// indicates using SQL login security model. /// </summary> Mixed = 1, /// <summary> /// security type not yet determined /// </summary> NULL = 2 } /// <summary> /// SQLConnections Collection class. A class to create and contain multiple SqlConnection objects. /// </summary> [Serializable()] public class SQLConnections : CollectionBase { /// <summary> /// connect format string used by methods to format Secure SQL connection string /// </summary> [NonSerialized()] public static string _secureConnect = @"Connection Timeout=30;Integrated Security=SSPI;Persist Security Info=false;Initial Catalog='{0}';Data Source='{1}'"; /// <summary> /// connect format string used by methods to format NonSecure SQL connection string /// </summary> [NonSerialized()] public static string _unsecureConnect = @"Connection Timeout=30;Integrated Security=false;Persist Security Info=false;Initial Catalog='{0}';Data Source='{1}';User ID='{2}';Password='{3}'"; /// <summary> /// public default ctor /// </summary> public SQLConnections() { // default ctor } /// <summary> /// Instantiates a new SqlConnections class using a connection string. /// The following example illustrates a typical connection string. /// "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer" /// </summary> /// <param name="ConnectionString">The connection string that includes the source database name, and other parameters needed to establish the initial connection.</param> public SQLConnections(string ConnectionString) { this.Add(new SQLConnection(ConnectionString)); } /// <summary> /// Instantiates a new SqlConnections class using a connection string. /// This instantiated class assumes a secure connection using a trusted Windows login. /// </summary> /// <param name="SqlServer">The SqlServer string is the SQL server name to make the connection to.</param> /// <param name="Database">The Database string is the SQL database name to make the connection to.</param> public SQLConnections(string SqlServer, string Database) { string _connectionstr = string.Format(_secureConnect, Database, SqlServer); this.Add(new SQLConnection(_connectionstr)); } /// <summary> /// Instantiates a new SqlConnections class using a connection string. /// This instantiated class assumes a unsecure connection using a valid SQL login. /// </summary> /// <param name="SqlServer">The SqlServer string is the SQL server name to make the connection to.</param> /// <param name="Database">The Database string is the SQL database name to make the connection to.</param> /// <param name="UserID">The UserID string is a SQL server user login name used to validate the connection.</param> /// <param name="Password">The Password string is a SQL server user password name used to validate the connection.</param> /// <param name="savePassword">The true false flag for persisting the password when saving the settings on close.</param> public SQLConnections(string SqlServer, string Database, string UserID, string Password, bool savePassword) { string _connectionstr = string.Format(_unsecureConnect, Database, SqlServer, UserID, Password); this.Add(new SQLConnection(_connectionstr, savePassword)); } /// <summary> /// get the int index value of the server connection object /// </summary> /// <param name="_connection"></param> /// <returns></returns> public virtual int getIndex(SQLConnection _connection) { return this.List.IndexOf(_connection); } /// <summary> /// get the int index value of the server connection /// </summary> /// <param name="ServerName"></param> /// <returns></returns> public virtual int getIndex(string ServerName) { int ii = 0; for (ii = 0; ii < this.List.Count; ii++) { SQLConnection sc = (SQLConnection)this.List[ii]; if (sc.sqlConnection.DataSource.ToLower().Equals(ServerName.ToLower())) { return ii; } } return -1; } /// <summary> /// adds a new SqlConnection object to the SqlConnections class. /// </summary> /// <param name="_connection"></param> /// <returns></returns> public virtual int Add(SQLConnection _connection) { return (this[_connection.Server] == null) ? this.List.Add(_connection) : getIndex(_connection); } /// <summary> /// adds a new SqlConnection object to the SqlConnections class. /// </summary> /// <param name="SqlServer"></param> /// <param name="Database"></param> /// <param name="UserID"></param> /// <param name="Password"></param> /// <param name="savePassword"></param> /// <returns></returns> public virtual int Add(string SqlServer, string Database, string UserID, string Password, bool savePassword) { string _connectionstr = string.Format(_unsecureConnect, Database, SqlServer, UserID, Password); return this.Add(new SQLConnection(_connectionstr, savePassword)); } /// <summary> /// adds a new SqlConnection object to the SqlConnections class. /// </summary> /// <param name="SqlServer"></param> /// <param name="Database"></param> /// <returns></returns> public virtual int Add(string SqlServer, string Database) { string _connectionstr = string.Format(_secureConnect, Database, SqlServer); return this.Add(new SQLConnection(_connectionstr)); } /// <summary> /// adds a new SqlConnection object to the SqlConnections class. /// </summary> /// <param name="ConnectionString"></param> /// <returns></returns> public virtual int Add(string ConnectionString) { return this.Add(new SQLConnection(ConnectionString)); } /// <summary> /// adds a new SqlConnection object to the SqlConnections class with an encrypted connection string /// </summary> /// <param name="encryptedConnectionString"></param> /// <param name="sKey"></param> /// <param name="savePassword"></param> /// <returns></returns> public virtual int AddEncrypted(string encryptedConnectionString, string sKey, bool savePassword) { string connectionString = Security.DecryptString(encryptedConnectionString, sKey); return this.Add(new SQLConnection(connectionString, savePassword)); } /// <summary> /// removes SqlConnection object from the collection /// </summary> /// <param name="_connection"></param> public virtual void Remove(SQLConnection _connection) { if (this[_connection.Server] != null) { this.List.Remove(_connection); } } /// <summary> /// removes SqlConnection object from the collection /// </summary> /// <param name="ServerName"></param> public virtual void Remove(string ServerName) { if (this[ServerName] != null) { this.List.Remove(this[ServerName]); } } /// <summary> /// Gets the index of the current SqlConnection object. /// </summary> public virtual SQLConnection this[int Index] { get { SQLConnection retval = null; if (this.List.Count > 0 && Index > -1) { retval = (SQLConnection)this.List[Index]; } return retval; } } /// <summary> /// returns specified SqlConnection using string name /// </summary> /// <param name="ServerName"></param> /// <returns></returns> public virtual SQLConnection this[string ServerName] { get { foreach (SQLConnection sc in this.List) { if (sc.sqlConnection.DataSource.ToLower().Equals(ServerName.ToLower())) { return sc; } } return null; } } } /// <summary> /// SQLConnection class wraps SqlConnection class to add additional data elements /// </summary> public class SQLConnection { private System.Data.SqlClient.SqlConnection _sqlConnection; private string _connectionString; private string _password; private bool _savePassword; private SQLConnection() { _sqlConnection = new System.Data.SqlClient.SqlConnection(); } /// <summary> /// Constructor with connection string param /// </summary> /// <param name="connectionString"></param> public SQLConnection(String connectionString) { _sqlConnection = new System.Data.SqlClient.SqlConnection(); ConnectionString = connectionString; } /// <summary> /// Constructor with connection string param, and a save the password param /// </summary> /// <param name="connectionString"></param> /// <param name="savePassword"></param> public SQLConnection(String connectionString, bool savePassword) { SavePassword = savePassword; _sqlConnection = new System.Data.SqlClient.SqlConnection(); ConnectionString = connectionString; } /// <summary> /// Property to get the SqlConnection /// </summary> public virtual SqlConnection sqlConnection { get { return _sqlConnection; } } /// <summary> /// Property to get the Connectionstring /// </summary> public virtual string ConnectionString { get { return _connectionString; } set { _connectionString = value; if (_sqlConnection != null) { if (_savePassword && _password != null && _connectionString != null && _connectionString.Trim().Length > 0 && !_connectionString.ToLower().Contains("password") && _connectionString.ToLower().Contains("integrated security=false")) { _sqlConnection.ConnectionString += string.Format("; Password='{0}'", _password); } else if (_savePassword && _connectionString != null && _connectionString.Trim().Length > 0 && _connectionString.ToLower().Contains("password")) { string[] strings = _connectionString.Split(new char[] { ';' }); foreach (string s in strings) { if (s.ToLower().Contains("password")) { string[] words = s.Split(new char[] { '=' }); if (words.Length > 1) { _password = words[1].Replace("'", ""); break; } } } } _sqlConnection.ConnectionString = _connectionString; } } } /// <summary> /// Property to get the security type used by the connection /// </summary> public virtual SecurityType securityType { get { string[] strings = _connectionString.Split(new char[] { ';' }); foreach (string s in strings) { if (s.ToLower().Contains("security")) { string[] words = s.Split(new char[] { '=' }); if (words.Length > 1) { return words[1].ToLower().Replace("'", "").Equals("false") ? SecurityType.Mixed : SecurityType.Integrated; } } } return SecurityType.NULL; } } /// <summary> /// Property to get the user set on the connection /// </summary> public virtual string User { get { string[] strings = _connectionString.Split(new char[] { ';' }); foreach (string s in strings) { if (s.ToLower().Contains("user")) { string[] words = s.Split(new char[] { '=' }); if (words.Length > 1) { return words[1].Replace("'", ""); } } } return null; } } /// <summary> /// Property to get the server name /// </summary> public virtual string Server { get { string[] strings = _connectionString.Split(new char[] { ';' }); foreach (string s in strings) { if (s.ToLower().Contains("source")) { string[] words = s.Split(new char[] { '=' }); if (words.Length > 1) { return words[1].Replace("'", ""); } } } return null; } } /// <summary> /// Property to get the SavePassword setting /// </summary> public virtual bool SavePassword { get { return _savePassword; } set { _savePassword = value; } } /// <summary> /// Property to get the saved password /// </summary> public virtual string Password { get { return _password; } set { if (SavePassword) { _password = value; if (_sqlConnection != null) { if (_password != null && _sqlConnection.ConnectionString != null && _sqlConnection.ConnectionString.Trim().Length > 0 && !_sqlConnection.ConnectionString.ToLower().Contains("Password") && _sqlConnection.ConnectionString.ToLower().Contains("Integrated Security=false")) { _sqlConnection.ConnectionString += string.Format("; Password='{0}'", _password); } } } } } /// <summary> /// Property to get the encrypted connection string - used when saving the connection settings /// </summary> public virtual string EncryptedConnectionString { get { return Security.EncryptString(SavePassword ? _connectionString : _sqlConnection.ConnectionString, "LLEWIS55"); } } } }
// This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------- // These interfaces serve as an extension to the BCL's SymbolStore interfaces. namespace Microsoft.Samples.Debugging.CorSymbolStore { using System.Diagnostics.SymbolStore; using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; [ ComImport, Guid("AA544d42-28CB-11d3-bd22-0000f80849bd"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder { // These methods will often return error HRs in common cases. // If there are no symbols for the given target, a failing hr is returned. // This is pretty common. // // Using PreserveSig and manually handling error cases provides a big performance win. // Far fewer exceptions will be thrown and caught. // Exceptions should be reserved for truely "exceptional" cases. [PreserveSig] int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); } [ ComImport, Guid("ACCEE350-89AF-4ccb-8B40-1C2C4C6F9434"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder2 : ISymUnmanagedBinder { // ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] new int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); // ISymUnmanagedBinder2 methods [PreserveSig] int GetReaderForFile2(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); } [ ComImport, Guid("28AD3D43-B601-4d26-8A1B-25F9165AF9D7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder3 : ISymUnmanagedBinder2 { // ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] new int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); // ISymUnmanagedBinder2 methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile2(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); // ISymUnmanagedBinder3 methods [PreserveSig] int GetReaderFromCallback(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.IUnknown)] object callback, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder"]/*' /> public class SymbolBinder : ISymbolBinder1, ISymbolBinder2 { ISymUnmanagedBinder m_binder; protected static readonly Guid CLSID_CorSymBinder = new Guid("0A29FF9E-7F9C-4437-8B11-F424491E3931"); /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.SymbolBinder"]/*' /> public SymbolBinder() { Type binderType = Type.GetTypeFromCLSID(CLSID_CorSymBinder); object comBinder = (ISymUnmanagedBinder)Activator.CreateInstance(binderType); m_binder = (ISymUnmanagedBinder)comBinder; } /// <summary> /// Create a SymbolBinder given the underling COM object for ISymUnmanagedBinder /// </summary> /// <param name="comBinderObject"></param> /// <remarks>Note that this could be protected, but C# doesn't have a way to express "internal AND /// protected", just "internal OR protected"</remarks> internal SymbolBinder(ISymUnmanagedBinder comBinderObject) { // We should not wrap null instances if (comBinderObject == null) throw new ArgumentNullException("comBinderObject"); m_binder = comBinderObject; } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReader"]/*' /> public ISymbolReader GetReader(IntPtr importer, String filename, String searchPath) { ISymUnmanagedReader reader = null; int hr = m_binder.GetReaderForFile(importer, filename, searchPath, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); return new SymReader(reader); } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String filename, String searchPath) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = m_binder.GetReaderForFile(uImporter, filename, searchPath, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile1"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String fileName, String searchPath, SymSearchPolicies searchPolicy) { ISymUnmanagedReader symReader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderForFile2(uImporter, fileName, searchPath, (int)searchPolicy, out symReader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(symReader); } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile2"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String fileName, String searchPath, SymSearchPolicies searchPolicy, object callback) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder3)m_binder).GetReaderFromCallback(uImporter, fileName, searchPath, (int)searchPolicy, callback, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } /// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderFromStream"]/*' /> public ISymbolReader GetReaderFromStream(Object importer, IStream stream) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderFromStream(uImporter, stream, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } /// <summary> /// Get an ISymbolReader interface given a raw COM symbol reader object. /// </summary> /// <param name="reader">A COM object implementing ISymUnmanagedReader</param> /// <returns>The ISybmolReader interface wrapping the provided COM object</returns> /// <remarks>This method is on SymbolBinder because it's conceptually similar to the /// other methods for creating a reader. It does not, however, actually need to use the underlying /// Binder, so it could be on SymReader instead (but we'd have to make it a public class instead of /// internal).</remarks> public static ISymbolReader GetReaderFromCOM(Object reader) { return new SymReader((ISymUnmanagedReader)reader); } private static bool IsFailingResultNormal(int hr) { // If a pdb is not found, that's a pretty common thing. if (hr == unchecked((int)0x806D0005)) // E_PDB_NOT_FOUND { return true; } // Other fairly common things may happen here, but we don't want to hide // this from the programmer. // You may get 0x806D0014 if the pdb is there, but just old (mismatched) // Or if you ask for the symbol information on something that's not an assembly. // If that may happen for your application, wrap calls to GetReaderForFile in // try-catch(COMException) blocks and use the error code in the COMException to report error. return false; } } }
namespace V1TaskManager { partial class UpdateForm { /// <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.todoPanel = new System.Windows.Forms.Panel(); this.txtToDo = new System.Windows.Forms.TextBox(); this.lblToDo = new System.Windows.Forms.Label(); this.effortPanel = new System.Windows.Forms.Panel(); this.txtEffort = new System.Windows.Forms.TextBox(); this.lblEffort = new System.Windows.Forms.Label(); this.statusPanel = new System.Windows.Forms.Panel(); this.comboStatus = new System.Windows.Forms.ComboBox(); this.lblStatus = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.todoPanel.SuspendLayout(); this.effortPanel.SuspendLayout(); this.statusPanel.SuspendLayout(); this.SuspendLayout(); // // todoPanel // this.todoPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.todoPanel.Controls.Add(this.txtToDo); this.todoPanel.Controls.Add(this.lblToDo); this.todoPanel.Location = new System.Drawing.Point(7, 43); this.todoPanel.Name = "todoPanel"; this.todoPanel.Size = new System.Drawing.Size(243, 28); this.todoPanel.TabIndex = 3; // // txtToDo // this.txtToDo.Location = new System.Drawing.Point(90, 3); this.txtToDo.Name = "txtToDo"; this.txtToDo.Size = new System.Drawing.Size(135, 20); this.txtToDo.TabIndex = 1; // // lblToDo // this.lblToDo.AutoSize = true; this.lblToDo.Location = new System.Drawing.Point(44, 6); this.lblToDo.Name = "lblToDo"; this.lblToDo.Size = new System.Drawing.Size(40, 13); this.lblToDo.TabIndex = 0; this.lblToDo.Text = "To Do:"; // // effortPanel // this.effortPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.effortPanel.AutoSize = true; this.effortPanel.Controls.Add(this.txtEffort); this.effortPanel.Controls.Add(this.lblEffort); this.effortPanel.Location = new System.Drawing.Point(7, 77); this.effortPanel.Name = "effortPanel"; this.effortPanel.Size = new System.Drawing.Size(243, 28); this.effortPanel.TabIndex = 2; // // txtEffort // this.txtEffort.Location = new System.Drawing.Point(90, 3); this.txtEffort.Name = "txtEffort"; this.txtEffort.Size = new System.Drawing.Size(135, 20); this.txtEffort.TabIndex = 1; // // lblEffort // this.lblEffort.AutoSize = true; this.lblEffort.Location = new System.Drawing.Point(49, 6); this.lblEffort.Name = "lblEffort"; this.lblEffort.Size = new System.Drawing.Size(35, 13); this.lblEffort.TabIndex = 0; this.lblEffort.Text = "Effort:"; // // statusPanel // this.statusPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.statusPanel.Controls.Add(this.comboStatus); this.statusPanel.Controls.Add(this.lblStatus); this.statusPanel.Location = new System.Drawing.Point(7, 7); this.statusPanel.Name = "statusPanel"; this.statusPanel.Size = new System.Drawing.Size(243, 30); this.statusPanel.TabIndex = 4; // // comboStatus // this.comboStatus.FormattingEnabled = true; this.comboStatus.ItemHeight = 13; this.comboStatus.Location = new System.Drawing.Point(90, 3); this.comboStatus.Name = "comboStatus"; this.comboStatus.Size = new System.Drawing.Size(135, 21); this.comboStatus.TabIndex = 3; // // lblStatus // this.lblStatus.AutoSize = true; this.lblStatus.Location = new System.Drawing.Point(47, 6); this.lblStatus.Name = "lblStatus"; this.lblStatus.Size = new System.Drawing.Size(37, 13); this.lblStatus.TabIndex = 0; this.lblStatus.Text = "Status"; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(173, 111); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(77, 23); this.btnCancel.TabIndex = 0; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(90, 111); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(77, 23); this.btnOK.TabIndex = 1; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.BtnOkClick); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnClose.Location = new System.Drawing.Point(7, 111); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(77, 23); this.btnClose.TabIndex = 2; this.btnClose.Text = "OK && Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.BtnCloseClick); // // UpdateForm // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(262, 144); this.ControlBox = false; this.Controls.Add(this.statusPanel); this.Controls.Add(this.todoPanel); this.Controls.Add(this.btnClose); this.Controls.Add(this.effortPanel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnCancel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "UpdateForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Update"; this.todoPanel.ResumeLayout(false); this.todoPanel.PerformLayout(); this.effortPanel.ResumeLayout(false); this.effortPanel.PerformLayout(); this.statusPanel.ResumeLayout(false); this.statusPanel.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Panel effortPanel; private System.Windows.Forms.TextBox txtEffort; private System.Windows.Forms.Label lblEffort; private System.Windows.Forms.Panel todoPanel; private System.Windows.Forms.TextBox txtToDo; private System.Windows.Forms.Label lblToDo; private System.Windows.Forms.Panel statusPanel; private System.Windows.Forms.ComboBox comboStatus; private System.Windows.Forms.Label lblStatus; private System.Windows.Forms.Button btnClose; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Graphics.Textures; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Rulesets; using osu.Game.Rulesets.Objects; using osu.Game.Skinning; using Decoder = osu.Game.Beatmaps.Formats.Decoder; namespace osu.Game.Beatmaps { /// <summary> /// Handles ef-core storage of beatmaps. /// </summary> [ExcludeFromDynamicCompile] public class BeatmapModelManager : ArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo>, IBeatmapModelManager { /// <summary> /// Fired when a single difficulty has been hidden. /// </summary> public IBindable<WeakReference<BeatmapInfo>> BeatmapHidden => beatmapHidden; private readonly Bindable<WeakReference<BeatmapInfo>> beatmapHidden = new Bindable<WeakReference<BeatmapInfo>>(); /// <summary> /// Fired when a single difficulty has been restored. /// </summary> public IBindable<WeakReference<BeatmapInfo>> BeatmapRestored => beatmapRestored; /// <summary> /// An online lookup queue component which handles populating online beatmap metadata. /// </summary> public BeatmapOnlineLookupQueue OnlineLookupQueue { private get; set; } /// <summary> /// The game working beatmap cache, used to invalidate entries on changes. /// </summary> public IWorkingBeatmapCache WorkingBeatmapCache { private get; set; } private readonly Bindable<WeakReference<BeatmapInfo>> beatmapRestored = new Bindable<WeakReference<BeatmapInfo>>(); public override IEnumerable<string> HandledExtensions => new[] { ".osz" }; protected override string[] HashableFileTypes => new[] { ".osu" }; protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); private readonly BeatmapStore beatmaps; private readonly RulesetStore rulesets; public BeatmapModelManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, GameHost host = null) : base(storage, contextFactory, new BeatmapStore(contextFactory), host) { this.rulesets = rulesets; beatmaps = (BeatmapStore)ModelStore; beatmaps.BeatmapHidden += b => beatmapHidden.Value = new WeakReference<BeatmapInfo>(b); beatmaps.BeatmapRestored += b => beatmapRestored.Value = new WeakReference<BeatmapInfo>(b); beatmaps.ItemRemoved += b => WorkingBeatmapCache?.Invalidate(b); beatmaps.ItemUpdated += obj => WorkingBeatmapCache?.Invalidate(obj); } protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path)?.ToLowerInvariant() == ".osz"; protected override async Task Populate(BeatmapSetInfo beatmapSet, ArchiveReader archive, CancellationToken cancellationToken = default) { if (archive != null) beatmapSet.Beatmaps = createBeatmapDifficulties(beatmapSet.Files); foreach (BeatmapInfo b in beatmapSet.Beatmaps) { // remove metadata from difficulties where it matches the set if (beatmapSet.Metadata.Equals(b.Metadata)) b.Metadata = null; b.BeatmapSet = beatmapSet; } validateOnlineIds(beatmapSet); bool hadOnlineBeatmapIDs = beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0); if (OnlineLookupQueue != null) await OnlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken).ConfigureAwait(false); // ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID. if (hadOnlineBeatmapIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0)) { if (beatmapSet.OnlineBeatmapSetID != null) { beatmapSet.OnlineBeatmapSetID = null; LogForModel(beatmapSet, "Disassociating beatmap set ID due to loss of all beatmap IDs"); } } } protected override void PreImport(BeatmapSetInfo beatmapSet) { if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null)) throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}."); // check if a set already exists with the same online id, delete if it does. if (beatmapSet.OnlineBeatmapSetID != null) { var existingSetWithSameOnlineID = beatmaps.ConsumableItems.FirstOrDefault(b => b.OnlineBeatmapSetID == beatmapSet.OnlineBeatmapSetID); if (existingSetWithSameOnlineID != null) { Delete(existingSetWithSameOnlineID); // in order to avoid a unique key constraint, immediately remove the online ID from the previous set. existingSetWithSameOnlineID.OnlineBeatmapSetID = null; foreach (var b in existingSetWithSameOnlineID.Beatmaps) b.OnlineBeatmapID = null; LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineBeatmapSetID ({beatmapSet.OnlineBeatmapSetID}). It has been deleted."); } } } private void validateOnlineIds(BeatmapSetInfo beatmapSet) { var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineBeatmapID.HasValue).Select(b => b.OnlineBeatmapID).ToList(); // ensure all IDs are unique if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1)) { LogForModel(beatmapSet, "Found non-unique IDs, resetting..."); resetIds(); return; } // find any existing beatmaps in the database that have matching online ids var existingBeatmaps = QueryBeatmaps(b => beatmapIds.Contains(b.OnlineBeatmapID)).ToList(); if (existingBeatmaps.Count > 0) { // reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set. // we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted. var existing = CheckForExisting(beatmapSet); if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b))) { LogForModel(beatmapSet, "Found existing import with IDs already, resetting..."); resetIds(); } } void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineBeatmapID = null); } /// <summary> /// Delete a beatmap difficulty. /// </summary> /// <param name="beatmapInfo">The beatmap difficulty to hide.</param> public void Hide(BeatmapInfo beatmapInfo) => beatmaps.Hide(beatmapInfo); /// <summary> /// Restore a beatmap difficulty. /// </summary> /// <param name="beatmapInfo">The beatmap difficulty to restore.</param> public void Restore(BeatmapInfo beatmapInfo) => beatmaps.Restore(beatmapInfo); /// <summary> /// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>. /// </summary> /// <param name="beatmapInfo">The <see cref="BeatmapInfo"/> to save the content against. The file referenced by <see cref="BeatmapInfo.Path"/> will be replaced.</param> /// <param name="beatmapContent">The <see cref="IBeatmap"/> content to write.</param> /// <param name="beatmapSkin">The beatmap <see cref="ISkin"/> content to write, null if to be omitted.</param> public virtual void Save(BeatmapInfo beatmapInfo, IBeatmap beatmapContent, ISkin beatmapSkin = null) { var setInfo = beatmapInfo.BeatmapSet; // Difficulty settings must be copied first due to the clone in `Beatmap<>.BeatmapInfo_Set`. // This should hopefully be temporary, assuming said clone is eventually removed. beatmapInfo.BaseDifficulty.CopyFrom(beatmapContent.Difficulty); // All changes to metadata are made in the provided beatmapInfo, so this should be copied to the `IBeatmap` before encoding. beatmapContent.BeatmapInfo = beatmapInfo; using (var stream = new MemoryStream()) { using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true)) new LegacyBeatmapEncoder(beatmapContent, beatmapSkin).Encode(sw); stream.Seek(0, SeekOrigin.Begin); using (ContextFactory.GetForWrite()) { beatmapInfo = setInfo.Beatmaps.Single(b => b.ID == beatmapInfo.ID); var metadata = beatmapInfo.Metadata ?? setInfo.Metadata; // grab the original file (or create a new one if not found). var fileInfo = setInfo.Files.SingleOrDefault(f => string.Equals(f.Filename, beatmapInfo.Path, StringComparison.OrdinalIgnoreCase)) ?? new BeatmapSetFileInfo(); // metadata may have changed; update the path with the standard format. beatmapInfo.Path = $"{metadata.Artist} - {metadata.Title} ({metadata.Author}) [{beatmapInfo.Version}].osu"; beatmapInfo.MD5Hash = stream.ComputeMD5Hash(); // update existing or populate new file's filename. fileInfo.Filename = beatmapInfo.Path; stream.Seek(0, SeekOrigin.Begin); ReplaceFile(setInfo, fileInfo, stream); } } WorkingBeatmapCache?.Invalidate(beatmapInfo); } /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapSetInfo QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().FirstOrDefault(query); protected override bool CanSkipImport(BeatmapSetInfo existing, BeatmapSetInfo import) { if (!base.CanSkipImport(existing, import)) return false; return existing.Beatmaps.Any(b => b.OnlineBeatmapID != null); } protected override bool CanReuseExisting(BeatmapSetInfo existing, BeatmapSetInfo import) { if (!base.CanReuseExisting(existing, import)) return false; var existingIds = existing.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); var importIds = import.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); // force re-import if we are not in a sane state. return existing.OnlineBeatmapSetID == import.OnlineBeatmapSetID && existingIds.SequenceEqual(importIds); } /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. /// </summary> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public List<BeatmapSetInfo> GetAllUsableBeatmapSets(IncludedDetails includes = IncludedDetails.All, bool includeProtected = false) => GetAllUsableBeatmapSetsEnumerable(includes, includeProtected).ToList(); /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. Note that files are not populated. /// </summary> /// <param name="includes">The level of detail to include in the returned objects.</param> /// <param name="includeProtected">Whether to include protected (system) beatmaps. These should not be included for gameplay playable use cases.</param> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public IEnumerable<BeatmapSetInfo> GetAllUsableBeatmapSetsEnumerable(IncludedDetails includes, bool includeProtected = false) { IQueryable<BeatmapSetInfo> queryable; switch (includes) { case IncludedDetails.Minimal: queryable = beatmaps.BeatmapSetsOverview; break; case IncludedDetails.AllButRuleset: queryable = beatmaps.BeatmapSetsWithoutRuleset; break; case IncludedDetails.AllButFiles: queryable = beatmaps.BeatmapSetsWithoutFiles; break; default: queryable = beatmaps.ConsumableItems; break; } // AsEnumerable used here to avoid applying the WHERE in sql. When done so, ef core 2.x uses an incorrect ORDER BY // clause which causes queries to take 5-10x longer. // TODO: remove if upgrading to EF core 3.x. return queryable.AsEnumerable().Where(s => !s.DeletePending && (includeProtected || !s.Protected)); } /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <param name="includes">The level of detail to include in the returned objects.</param> /// <returns>Results from the provided query.</returns> public IEnumerable<BeatmapSetInfo> QueryBeatmapSets(Expression<Func<BeatmapSetInfo, bool>> query, IncludedDetails includes = IncludedDetails.All) { IQueryable<BeatmapSetInfo> queryable; switch (includes) { case IncludedDetails.Minimal: queryable = beatmaps.BeatmapSetsOverview; break; case IncludedDetails.AllButRuleset: queryable = beatmaps.BeatmapSetsWithoutRuleset; break; case IncludedDetails.AllButFiles: queryable = beatmaps.BeatmapSetsWithoutFiles; break; default: queryable = beatmaps.ConsumableItems; break; } return queryable.AsNoTracking().Where(query); } /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapInfo QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().FirstOrDefault(query); /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>Results from the provided query.</returns> public IQueryable<BeatmapInfo> QueryBeatmaps(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().Where(query); public override string HumanisedModelName => "beatmap"; protected override bool CheckLocalAvailability(BeatmapSetInfo model, IQueryable<BeatmapSetInfo> items) => base.CheckLocalAvailability(model, items) || (model.OnlineBeatmapSetID != null && items.Any(b => b.OnlineBeatmapSetID == model.OnlineBeatmapSetID)); protected override BeatmapSetInfo CreateModel(ArchiveReader reader) { // let's make sure there are actually .osu files to import. string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu", StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(mapName)) { Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database); return null; } Beatmap beatmap; using (var stream = new LineBufferedReader(reader.GetStream(mapName))) beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream); return new BeatmapSetInfo { OnlineBeatmapSetID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID, Beatmaps = new List<BeatmapInfo>(), Metadata = beatmap.Metadata, DateAdded = DateTimeOffset.UtcNow }; } /// <summary> /// Create all required <see cref="BeatmapInfo"/>s for the provided archive. /// </summary> private List<BeatmapInfo> createBeatmapDifficulties(List<BeatmapSetFileInfo> files) { var beatmapInfos = new List<BeatmapInfo>(); foreach (var file in files.Where(f => f.Filename.EndsWith(".osu", StringComparison.OrdinalIgnoreCase))) { using (var raw = Files.Store.GetStream(file.FileInfo.StoragePath)) using (var ms = new MemoryStream()) // we need a memory stream so we can seek using (var sr = new LineBufferedReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = Decoder.GetDecoder<Beatmap>(sr); IBeatmap beatmap = decoder.Decode(sr); string hash = ms.ComputeSHA2Hash(); if (beatmapInfos.Any(b => b.Hash == hash)) continue; beatmap.BeatmapInfo.Path = file.Filename; beatmap.BeatmapInfo.Hash = hash; beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash(); var ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID); beatmap.BeatmapInfo.Ruleset = ruleset; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0; beatmap.BeatmapInfo.Length = calculateLength(beatmap); beatmap.BeatmapInfo.BPM = 60000 / beatmap.GetMostCommonBeatLength(); beatmapInfos.Add(beatmap.BeatmapInfo); } } return beatmapInfos; } private double calculateLength(IBeatmap b) { if (!b.HitObjects.Any()) return 0; var lastObject = b.HitObjects.Last(); //TODO: this isn't always correct (consider mania where a non-last object may last for longer than the last in the list). double endTime = lastObject.GetEndTime(); double startTime = b.HitObjects.First().StartTime; return endTime - startTime; } /// <summary> /// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation. /// </summary> private class DummyConversionBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; public DummyConversionBeatmap(IBeatmap beatmap) : base(beatmap.BeatmapInfo, null) { this.beatmap = beatmap; } protected override IBeatmap GetBeatmap() => beatmap; protected override Texture GetBackground() => null; protected override Track GetBeatmapTrack() => null; protected internal override ISkin GetSkin() => null; public override Stream GetStream(string storagePath) => null; } } /// <summary> /// The level of detail to include in database results. /// </summary> public enum IncludedDetails { /// <summary> /// Only include beatmap difficulties and set level metadata. /// </summary> Minimal, /// <summary> /// Include all difficulties, rulesets, difficulty metadata but no files. /// </summary> AllButFiles, /// <summary> /// Include everything except ruleset. Used for cases where we aren't sure the ruleset is present but still want to consume the beatmap. /// </summary> AllButRuleset, /// <summary> /// Include everything. /// </summary> All } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPagingOperations. /// </summary> public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Paging = new PagingOperations(this); BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// *********************************************************************** // Copyright (c) 2007 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.Collections; namespace NUnit.Framework.Constraints { #region PrefixConstraint /// <summary> /// Abstract base class used for prefixes /// </summary> public abstract class PrefixConstraint : Constraint { /// <summary> /// The base constraint /// </summary> protected Constraint baseConstraint; /// <summary> /// Construct given a base constraint /// </summary> /// <param name="resolvable"></param> protected PrefixConstraint(IResolveConstraint resolvable) : base(resolvable) { if ( resolvable != null ) this.baseConstraint = resolvable.Resolve(); } } #endregion #region NotConstraint /// <summary> /// NotConstraint negates the effect of some other constraint /// </summary> public class NotConstraint : PrefixConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:NotConstraint"/> class. /// </summary> /// <param name="baseConstraint">The base constraint to be negated.</param> public NotConstraint(Constraint baseConstraint) : base( baseConstraint ) { } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for if the base constraint fails, false if it succeeds</returns> public override bool Matches(object actual) { this.actual = actual; return !baseConstraint.Matches(actual); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo( MessageWriter writer ) { writer.WritePredicate( "not" ); baseConstraint.WriteDescriptionTo( writer ); } /// <summary> /// Write the actual value for a failing constraint test to a MessageWriter. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { baseConstraint.WriteActualValueTo (writer); } } #endregion #region AllItemsConstraint /// <summary> /// AllItemsConstraint applies another constraint to each /// item in a collection, succeeding if they all succeed. /// </summary> public class AllItemsConstraint : PrefixConstraint { /// <summary> /// Construct an AllItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public AllItemsConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "all"; } /// <summary> /// Apply the item constraint to each item in the collection, /// failing if any item fails. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (!baseConstraint.Matches(item)) return false; return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("all items"); baseConstraint.WriteDescriptionTo(writer); } } #endregion #region SomeItemsConstraint /// <summary> /// SomeItemsConstraint applies another constraint to each /// item in a collection, succeeding if any of them succeeds. /// </summary> public class SomeItemsConstraint : PrefixConstraint { /// <summary> /// Construct a SomeItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public SomeItemsConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "some"; } /// <summary> /// Apply the item constraint to each item in the collection, /// succeeding if any item succeeds. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (baseConstraint.Matches(item)) return true; return false; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("some item"); baseConstraint.WriteDescriptionTo(writer); } } #endregion #region NoItemConstraint /// <summary> /// NoItemConstraint applies another constraint to each /// item in a collection, failing if any of them succeeds. /// </summary> public class NoItemConstraint : PrefixConstraint { /// <summary> /// Construct a SomeItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public NoItemConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "none"; } /// <summary> /// Apply the item constraint to each item in the collection, /// failing if any item fails. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (baseConstraint.Matches(item)) return false; return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("no item"); baseConstraint.WriteDescriptionTo(writer); } } #endregion }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation; namespace Microsoft.PowerShell.Cmdletization { /// <summary> /// Provides common code for processing session-based object models. The common code /// Session, ThrottleLimit, AsJob parameters and delegates creation of jobs to derived classes. /// </summary> /// <typeparam name="TObjectInstance">Type that represents instances of objects from the wrapped object model</typeparam> /// <typeparam name="TSession">Type representing remote sessions</typeparam> [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")] public abstract class SessionBasedCmdletAdapter<TObjectInstance, TSession> : CmdletAdapter<TObjectInstance>, IDisposable where TObjectInstance : class where TSession : class { internal SessionBasedCmdletAdapter() { } #region Constants private const string CIMJobType = "CimJob"; #endregion #region IDisposable Members private bool _disposed; /// <summary> /// Releases resources associated with this object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases resources associated with this object /// </summary> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_parentJob != null) { _parentJob.Dispose(); _parentJob = null; } } _disposed = true; } } #endregion #region Common parameters (AsJob, ThrottleLimit, Session) /// <summary> /// Session to operate on /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected TSession[] Session { get { return _session ?? (_session = new TSession[] {this.DefaultSession}); } set { if (value == null) { throw new ArgumentNullException("value"); } _session = value; _sessionWasSpecified = true; } } private TSession[] _session; private bool _sessionWasSpecified; /// <summary> /// Whether to wrap and emit the whole operation as a background job /// </summary> [Parameter] public SwitchParameter AsJob { get { return _asJob; } set { _asJob = value; } } private bool _asJob; /// <summary> /// Maximum number of remote connections that can remain active at any given time. /// </summary> [Parameter] public virtual int ThrottleLimit { get; set; } #endregion Common CIM-related parameters #region Abstract methods to be overriden in derived classes /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that performs a query against the wrapped object model. /// </summary> /// <param name="session">Remote session to query</param> /// <param name="query">Query parameters</param> /// <remarks> /// <para> /// This method shouldn't do any processing or interact with the remote session. /// Doing so will interfere with ThrottleLimit functionality. /// </para> /// <para> /// <see cref="Job.WriteObject" /> (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further procesing, /// until calls from <see cref="Job.WriteObject" /> (and other methods returning job results) return. /// </para> /// </remarks> internal abstract StartableJob CreateQueryJob(TSession session, QueryBuilder query); private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query, Action<TSession, TObjectInstance> actionAgainstResults) { StartableJob queryJob = this.CreateQueryJob(sessionForJob, query); if (queryJob != null) { if (actionAgainstResults != null) { queryJob.SuppressOutputForwarding = true; } bool discardNonPipelineResults = (actionAgainstResults != null) || !this.AsJob.IsPresent; HandleJobOutput( queryJob, sessionForJob, discardNonPipelineResults, actionAgainstResults == null ? (Action<PSObject>)null : delegate (PSObject pso) { var objectInstance = (TObjectInstance) LanguagePrimitives.ConvertTo(pso, typeof(TObjectInstance), CultureInfo.InvariantCulture); actionAgainstResults(sessionForJob, objectInstance); }); } return queryJob; } /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that invokes an instance method in the wrapped object model. /// </summary> /// <param name="session">Remote session to invoke the method in</param> /// <param name="objectInstance">The object on which to invoke the method</param> /// <param name="methodInvocationInfo">Method invocation details</param> /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the <paramref name="objectInstance"/> being operated on</param> /// <remarks> /// <para> /// This method shouldn't do any processing or interact with the remote session. /// Doing so will interfere with ThrottleLimit functionality. /// </para> /// <para> /// <see cref="Job.WriteObject" /> (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further procesing, /// until calls from <see cref="Job.WriteObject" /> (and other methods returning job results) return. /// </para> /// </remarks> internal abstract StartableJob CreateInstanceMethodInvocationJob(TSession session, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru); private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru, bool asJob) { StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru); if (methodInvocationJob != null) { bool discardNonPipelineResults = !asJob; HandleJobOutput( methodInvocationJob, sessionForJob, discardNonPipelineResults, outputAction: null); } return methodInvocationJob; } /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that invokes a static method in the wrapped object model. /// </summary> /// <param name="session">Remote session to invoke the method in</param> /// <param name="methodInvocationInfo">Method invocation details</param> /// <remarks> /// <para> /// This method shouldn't do any processing or interact with the remote session. /// Doing so will interfere with ThrottleLimit functionality. /// </para> /// <para> /// <see cref="Job.WriteObject" /> (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further procesing, /// until calls from <see cref="Job.WriteObject" /> (and other methods returning job results) return. /// </para> /// </remarks> internal abstract StartableJob CreateStaticMethodInvocationJob(TSession session, MethodInvocationInfo methodInvocationInfo); private StartableJob DoCreateStaticMethodInvocationJob(TSession sessionForJob, MethodInvocationInfo methodInvocationInfo) { StartableJob methodInvocationJob = this.CreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); if (methodInvocationJob != null) { bool discardNonPipelineResults = !this.AsJob.IsPresent; HandleJobOutput( methodInvocationJob, sessionForJob, discardNonPipelineResults, outputAction: null); } return methodInvocationJob; } private void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPipelineResults, Action<PSObject> outputAction) { Action<PSObject> processOutput = delegate (PSObject pso) { if (pso == null) { return; } if (outputAction != null) { outputAction(pso); } }; job.Output.DataAdded += delegate (object sender, DataAddedEventArgs eventArgs) { var dataCollection = (PSDataCollection<PSObject>)sender; if (discardNonPipelineResults) { foreach (PSObject pso in dataCollection.ReadAll()) { // TODO/FIXME - need to make sure that the dataCollection will be throttled // (i.e. it won't accept more items - it will block in Add method) // until this processOutput call completes processOutput(pso); } } else { PSObject pso = dataCollection[eventArgs.Index]; processOutput(pso); } }; if (discardNonPipelineResults) { DiscardJobOutputs(job, JobOutputs.NonPipelineResults & (~JobOutputs.Output)); } } internal virtual TSession GetSessionOfOriginFromInstance(TObjectInstance instance) { return null; } /// <summary> /// Returns default sessions to use when the user doesn't specify the -Session cmdlet parameter. /// </summary> /// <returns>Default sessions to use when the user doesn't specify the -Session cmdlet parameter</returns> protected abstract TSession DefaultSession { get; } /// <summary> /// A new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation. /// </summary> protected abstract string GenerateParentJobName(); #endregion #region Helper methods private static void DiscardJobOutputs<T>(PSDataCollection<T> psDataCollection) { psDataCollection.DataAdded += delegate (object sender, DataAddedEventArgs e) { var localDataCollection = (PSDataCollection<T>)sender; localDataCollection.Clear(); }; } [Flags] private enum JobOutputs { Output = 0x1, Error = 0x2, Warning = 0x4, Verbose = 0x8, Debug = 0x10, Progress = 0x20, Results = 0x40, NonPipelineResults = Output | Error | Warning | Verbose | Debug | Progress, PipelineResults = Results, } private static void DiscardJobOutputs(Job job, JobOutputs jobOutputsToDiscard) { if (JobOutputs.Output == (jobOutputsToDiscard & JobOutputs.Output)) { DiscardJobOutputs(job.Output); } if (JobOutputs.Error == (jobOutputsToDiscard & JobOutputs.Error)) { DiscardJobOutputs(job.Error); } if (JobOutputs.Warning == (jobOutputsToDiscard & JobOutputs.Warning)) { DiscardJobOutputs(job.Warning); } if (JobOutputs.Verbose == (jobOutputsToDiscard & JobOutputs.Verbose)) { DiscardJobOutputs(job.Verbose); } if (JobOutputs.Debug == (jobOutputsToDiscard & JobOutputs.Debug)) { DiscardJobOutputs(job.Debug); } if (JobOutputs.Progress == (jobOutputsToDiscard & JobOutputs.Progress)) { DiscardJobOutputs(job.Progress); } if (JobOutputs.Results == (jobOutputsToDiscard & JobOutputs.Results)) { DiscardJobOutputs(job.Results); } } #endregion Helper methods #region Implementation of ObjectModelWrapper functionality private ThrottlingJob _parentJob; /// <summary> /// Queries for object instances in the object model. /// </summary> /// <param name="query">Query parameters</param> /// <returns>A lazy evaluated collection of object instances</returns> public override void ProcessRecord(QueryBuilder query) { _parentJob.DisableFlowControlForPendingCmdletActionsQueue(); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) { StartableJob childJob = this.DoCreateQueryJob(sessionForJob, query, actionAgainstResults: null); if (childJob != null) { if (!this.AsJob.IsPresent) { _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } } /// <summary> /// Queries for instance and invokes an instance method /// </summary> /// <param name="query">Query parameters</param> /// <param name="methodInvocationInfo">Method invocation details</param> /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the object instance being operated on</param> public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) { _parentJob.DisableFlowControlForPendingJobsQueue(); ThrottlingJob closureOverParentJob = _parentJob; SwitchParameter closureOverAsJob = this.AsJob; foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) { StartableJob queryJob = this.DoCreateQueryJob( sessionForJob, query, delegate (TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) { StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob( sessionForMethodInvocationJob, objectInstance, methodInvocationInfo, passThru, closureOverAsJob.IsPresent); if (methodInvocationJob != null) { closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); } }); if (queryJob != null) { if (!this.AsJob.IsPresent) { _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } else { _parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } } } } private IEnumerable<TSession> GetSessionsToActAgainst(TObjectInstance objectInstance) { if (_sessionWasSpecified) { return this.Session; } TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); if (associatedSession != null) { return new[] { associatedSession }; } return new[] { this.GetImpliedSession() }; } private TSession GetSessionAssociatedWithPipelineObject() { object inputVariableValue = this.Cmdlet.Context.GetVariableValue(SpecialVariables.InputVarPath, null); if (inputVariableValue == null) { return null; } IEnumerable inputEnumerable = LanguagePrimitives.GetEnumerable(inputVariableValue); if (inputEnumerable == null) { return null; } List<object> inputCollection = inputEnumerable.Cast<object>().ToList(); if (inputCollection.Count != 1) { return null; } TObjectInstance inputInstance; if (!LanguagePrimitives.TryConvertTo(inputCollection[0], CultureInfo.InvariantCulture, out inputInstance)) { return null; } TSession associatedSession = this.GetSessionOfOriginFromInstance(inputInstance); return associatedSession; } private IEnumerable<TSession> GetSessionsToActAgainst(QueryBuilder queryBuilder) { if (_sessionWasSpecified) { return this.Session; } var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder<TSession>; if (sessionBoundQueryBuilder != null) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); if (sessionOfTheQueryBuilder != null) { return new[] { sessionOfTheQueryBuilder }; } } TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); if (sessionAssociatedWithPipelineObject != null) { return new[] { sessionAssociatedWithPipelineObject }; } return new[] { this.GetImpliedSession() }; } private IEnumerable<TSession> GetSessionsToActAgainst(MethodInvocationInfo methodInvocationInfo) { if (_sessionWasSpecified) { return this.Session; } var associatedSessions = new HashSet<TSession>(); foreach (TObjectInstance objectInstance in methodInvocationInfo.GetArgumentsOfType<TObjectInstance>()) { TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); if (associatedSession != null) { associatedSessions.Add(associatedSession); } } if (associatedSessions.Count == 1) { return associatedSessions; } TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); if (sessionAssociatedWithPipelineObject != null) { return new[] { sessionAssociatedWithPipelineObject }; } return new[] { this.GetImpliedSession() }; } internal PSModuleInfo PSModuleInfo { get { var scriptCommandInfo = this.Cmdlet.CommandInfo as IScriptCommandInfo; return scriptCommandInfo.ScriptBlock.Module; } } private TSession GetImpliedSession() { TSession sessionFromImportModule; // When being called from a CIM actiivty, this will be invoked as // a function so there will be no module info if (this.PSModuleInfo != null) { if (PSPrimitiveDictionary.TryPathGet( this.PSModuleInfo.PrivateData as IDictionary, out sessionFromImportModule, ScriptWriter.PrivateDataKey_CmdletsOverObjects, ScriptWriter.PrivateDataKey_DefaultSession)) { return sessionFromImportModule; } } return this.DefaultSession; } /// <summary> /// Invokes an instance method in the object model. /// </summary> /// <param name="objectInstance">The object on which to invoke the method</param> /// <param name="methodInvocationInfo">Method invocation details</param> /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the <paramref name="objectInstance"/> being operated on</param> public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { if (objectInstance == null) throw new ArgumentNullException("objectInstance"); if (methodInvocationInfo == null) throw new ArgumentNullException("methodInvocationInfo"); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { StartableJob childJob = this.DoCreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru, this.AsJob.IsPresent); if (childJob != null) { if (!this.AsJob.IsPresent) { _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } } /// <summary> /// Invokes a static method in the object model. /// </summary> /// <param name="methodInvocationInfo">Method invocation details</param> public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { if (methodInvocationInfo == null) throw new ArgumentNullException("methodInvocationInfo"); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { StartableJob childJob = this.DoCreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); if (childJob != null) { if (!this.AsJob.IsPresent) { _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } } /// <summary> /// Performs initialization of cmdlet execution. /// </summary> public override void BeginProcessing() { if (this.AsJob.IsPresent) { MshCommandRuntime commandRuntime = (MshCommandRuntime)this.Cmdlet.CommandRuntime; // PSCmdlet.CommandRuntime is always MshCommandRuntime string conflictingParameter = null; if (commandRuntime.WhatIf.IsPresent) { conflictingParameter = "WhatIf"; } else if (commandRuntime.Confirm.IsPresent) { conflictingParameter = "Confirm"; } if (conflictingParameter != null) { string errorMessage = string.Format( CultureInfo.InvariantCulture, CmdletizationResources.SessionBasedWrapper_ShouldProcessVsJobConflict, conflictingParameter); throw new InvalidOperationException(errorMessage); } } _parentJob = new ThrottlingJob( command: Job.GetCommandTextFromInvocationInfo(this.Cmdlet.MyInvocation), jobName: this.GenerateParentJobName(), jobTypeName: CIMJobType, maximumConcurrentChildJobs: this.ThrottleLimit, cmdletMode: !this.AsJob.IsPresent); } /// <summary> /// Performs cleanup after cmdlet execution. /// </summary> public override void EndProcessing() { _parentJob.EndOfChildJobs(); if (this.AsJob.IsPresent) { this.Cmdlet.WriteObject(_parentJob); this.Cmdlet.JobRepository.Add(_parentJob); _parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world } else { _parentJob.ForwardAllResultsToCmdlet(this.Cmdlet); _parentJob.Finished.WaitOne(); } } /// <summary> /// Stops the parent job when called. /// </summary> public override void StopProcessing() { Job jobToStop = _parentJob; if (jobToStop != null) { jobToStop.StopJob(); } base.StopProcessing(); } #endregion } internal interface ISessionBoundQueryBuilder<out TSession> { TSession GetTargetSession(); } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.Primitives.Popup.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls.Primitives { public partial class Popup : System.Windows.FrameworkElement, System.Windows.Markup.IAddChild { #region Methods and constructors public static void CreateRootPopup(System.Windows.Controls.Primitives.Popup popup, System.Windows.UIElement child) { } protected override System.Windows.DependencyObject GetUIParentCore() { return default(System.Windows.DependencyObject); } protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize) { return default(System.Windows.Size); } protected virtual new void OnClosed(EventArgs e) { } protected virtual new void OnOpened(EventArgs e) { } protected override void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnPreviewMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnPreviewMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnPreviewMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } public Popup() { } void System.Windows.Markup.IAddChild.AddChild(Object value) { } void System.Windows.Markup.IAddChild.AddText(string text) { } #endregion #region Properties and indexers public bool AllowsTransparency { get { return default(bool); } set { } } public System.Windows.UIElement Child { get { return default(System.Windows.UIElement); } set { } } public CustomPopupPlacementCallback CustomPopupPlacementCallback { get { return default(CustomPopupPlacementCallback); } set { } } public bool HasDropShadow { get { return default(bool); } } public double HorizontalOffset { get { return default(double); } set { } } public bool IsOpen { get { return default(bool); } set { } } internal protected override System.Collections.IEnumerator LogicalChildren { get { return default(System.Collections.IEnumerator); } } public PlacementMode Placement { get { return default(PlacementMode); } set { } } public System.Windows.Rect PlacementRectangle { get { return default(System.Windows.Rect); } set { } } public System.Windows.UIElement PlacementTarget { get { return default(System.Windows.UIElement); } set { } } public PopupAnimation PopupAnimation { get { return default(PopupAnimation); } set { } } public bool StaysOpen { get { return default(bool); } set { } } public double VerticalOffset { get { return default(double); } set { } } #endregion #region Events public event EventHandler Closed { add { } remove { } } public event EventHandler Opened { add { } remove { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty AllowsTransparencyProperty; public readonly static System.Windows.DependencyProperty ChildProperty; public readonly static System.Windows.DependencyProperty CustomPopupPlacementCallbackProperty; public readonly static System.Windows.DependencyProperty HasDropShadowProperty; public readonly static System.Windows.DependencyProperty HorizontalOffsetProperty; public readonly static System.Windows.DependencyProperty IsOpenProperty; public readonly static System.Windows.DependencyProperty PlacementProperty; public readonly static System.Windows.DependencyProperty PlacementRectangleProperty; public readonly static System.Windows.DependencyProperty PlacementTargetProperty; public readonly static System.Windows.DependencyProperty PopupAnimationProperty; public readonly static System.Windows.DependencyProperty StaysOpenProperty; public readonly static System.Windows.DependencyProperty VerticalOffsetProperty; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Microsoft.Cci.Extensions; using Microsoft.Cci.Extensions.CSharp; using Microsoft.Cci.Writers.Syntax; namespace Microsoft.Cci.Writers.CSharp { public partial class CSDeclarationWriter { private void WriteMethodDefinition(IMethodDefinition method) { if (method.IsPropertyOrEventAccessor()) return; if (method.IsDestructor()) { WriteDestructor(method); return; } string name = method.GetMethodName(); WriteMethodPseudoCustomAttributes(method); WriteAttributes(method.Attributes); WriteAttributes(method.SecurityAttributes); if (!method.ContainingTypeDefinition.IsInterface) { if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility); WriteMethodModifiers(method); } WriteInterfaceMethodModifiers(method); WriteMethodDefinitionSignature(method, name); WriteMethodBody(method); } private void WriteDestructor(IMethodDefinition method) { WriteSymbol("~"); WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name); WriteSymbol("("); WriteSymbol(")", false); WriteEmptyBody(); } private void WriteTypeName(ITypeReference type, ITypeReference containingType, bool isDynamic = false) { var useKeywords = containingType.GetTypeName() != type.GetTypeName(); WriteTypeName(type, isDynamic: isDynamic, useTypeKeywords: useKeywords); } private void WriteMethodDefinitionSignature(IMethodDefinition method, string name) { bool isOperator = method.IsConversionOperator(); if (!isOperator && !method.IsConstructor) { WriteAttributes(method.ReturnValueAttributes, true); if (method.ReturnValueIsByRef) WriteKeyword("ref"); // We are ignoring custom modifiers right now, we might need to add them later. WriteTypeName(method.Type, method.ContainingType, isDynamic: IsDynamic(method.ReturnValueAttributes)); } WriteIdentifier(name); if (isOperator) { WriteSpace(); WriteTypeName(method.Type, method.ContainingType); } Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances"); if (method.IsGeneric) WriteGenericParameters(method.GenericParameters); WriteParameters(method.Parameters, method.ContainingType, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments); if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod()) WriteGenericContraints(method.GenericParameters); } private void WriteParameters(IEnumerable<IParameterDefinition> parameters, ITypeReference containingType, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false) { string start = property ? "[" : "("; string end = property ? "]" : ")"; WriteSymbol(start); _writer.WriteList(parameters, p => { WriteParameter(p, containingType, extensionMethod); extensionMethod = false; }); if (acceptsExtraArguments) { if (parameters.Any()) _writer.WriteSymbol(","); _writer.WriteSpace(); _writer.Write("__arglist"); } WriteSymbol(end); } private void WriteParameter(IParameterDefinition parameter, ITypeReference containingType, bool extensionMethod) { WriteAttributes(parameter.Attributes, true); if (extensionMethod) WriteKeyword("this"); if (parameter.IsParameterArray) WriteKeyword("params"); if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference) { WriteKeyword("out"); } else { // For In/Out we should not emit them until we find a scenario that is needs thems. //if (parameter.IsIn) // WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true); //if (parameter.IsOut) // WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true); if (parameter.IsByReference) WriteKeyword("ref"); } WriteTypeName(parameter.Type, containingType, isDynamic: IsDynamic(parameter.Attributes)); WriteIdentifier(parameter.Name); if (parameter.IsOptional && parameter.HasDefaultValue) { WriteSymbol("="); WriteMetadataConstant(parameter.DefaultValue, parameter.Type); } } private void WriteInterfaceMethodModifiers(IMethodDefinition method) { if (method.GetHiddenBaseMethod(_filter) != Dummy.Method) WriteKeyword("new"); } private void WriteMethodModifiers(IMethodDefinition method) { if (method.IsMethodUnsafe()) WriteKeyword("unsafe"); if (method.IsStatic) WriteKeyword("static"); if (method.IsPlatformInvoke) WriteKeyword("extern"); if (method.IsVirtual) { if (method.IsNewSlot) { if (method.IsAbstract) WriteKeyword("abstract"); else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots WriteKeyword("virtual"); } else { if (method.IsAbstract) WriteKeyword("abstract"); else if (method.IsSealed) WriteKeyword("sealed"); WriteKeyword("override"); } } } private void WriteMethodBody(IMethodDefinition method) { if (method.IsAbstract || !_forCompilation || method.IsPlatformInvoke) { WriteSymbol(";"); return; } if (method.IsConstructor) WriteBaseConstructorCall(method.ContainingTypeDefinition); // Write Dummy Body WriteSpace(); WriteSymbol("{", true); WriteOutParameterInitializations(method); if (_forCompilationThrowPlatformNotSupported) { Write("throw new "); if (_forCompilationIncludeGlobalprefix) Write("global::"); Write("System.PlatformNotSupportedException(); "); } else if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor) { // Structs cannot have empty constructors so we need to output this dummy body Write("throw null;"); } else if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid)) { WriteKeyword("throw null;"); } WriteSymbol("}"); } private void WritePrivateConstructor(ITypeDefinition type) { if (!_forCompilation || type.IsInterface || type.IsEnum || type.IsDelegate || type.IsValueType || type.IsStatic) return; WriteVisibility(TypeMemberVisibility.Assembly); WriteIdentifier(((INamedEntity)type).Name); WriteSymbol("("); WriteSymbol(")"); WriteBaseConstructorCall(type); WriteEmptyBody(); } private void WriteOutParameterInitializations(IMethodDefinition method) { if (!_forCompilation) return; var outParams = method.Parameters.Where(p => p.IsOut); foreach (var param in outParams) { WriteIdentifier(param.Name); WriteSpace(); WriteSymbol("=", true); WriteDefaultOf(param.Type); WriteSymbol(";", true); } } private void WriteBaseConstructorCall(ITypeDefinition type) { if (!_forCompilation) return; ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull(); if (baseType == null) return; var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m) && !m.Attributes.Any(a => a.IsObsoleteWithUsageTreatedAsCompilationError())); var defaultCtor = ctors.Where(c => c.ParameterCount == 0); // Don't need a base call if we have a default constructor if (defaultCtor.Any()) return; var ctor = ctors.FirstOrDefault(); if (ctor == null) return; WriteSpace(); WriteSymbol(":", true); WriteKeyword("base"); WriteSymbol("("); _writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type)); WriteSymbol(")"); } private void WriteEmptyBody() { if (!_forCompilation) { WriteSymbol(";"); } else { WriteSpace(); WriteSymbol("{", true); WriteSymbol("}"); } } private void WriteDefaultOf(ITypeReference type) { WriteKeyword("default", true); WriteSymbol("("); WriteTypeName(type, true); WriteSymbol(")"); } public static IDefinition GetDummyConstructor(ITypeDefinition type) { return new DummyInternalConstructor() { ContainingType = type }; } private class DummyInternalConstructor : IDefinition { public ITypeDefinition ContainingType { get; set; } public IEnumerable<ICustomAttribute> Attributes { get { throw new System.NotImplementedException(); } } public void Dispatch(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } public IEnumerable<ILocation> Locations { get { throw new System.NotImplementedException(); } } public void DispatchAsReference(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; namespace System.Net { // CookieCollection // // A list of cookies maintained in Sorted order. Only one cookie with matching Name/Domain/Path [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CookieCollection : ICollection { internal enum Stamp { Check = 0, Set = 1, SetToUnused = 2, SetToMaxUsed = 3, } private readonly ArrayList m_list = new ArrayList(); private int m_version; // Do not rename (binary serialization). This field only exists for netfx serialization compatibility. private DateTime m_TimeStamp = DateTime.MinValue; // Do not rename (binary serialization) private bool m_has_other_versions; // Do not rename (binary serialization) public CookieCollection() { } public Cookie this[int index] { get { if (index < 0 || index >= m_list.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } return m_list[index] as Cookie; } } public Cookie this[string name] { get { foreach (Cookie c in m_list) { if (string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase)) { return c; } } return null; } } [OnSerializing] private void OnSerializing(StreamingContext context) { m_version = m_list.Count; } public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } int idx = IndexOf(cookie); if (idx == -1) { m_list.Add(cookie); } else { m_list[idx] = cookie; } } public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } foreach (Cookie cookie in cookies.m_list) { Add(cookie); } } public bool IsReadOnly { get { return false; } } public int Count { get { return m_list.Count; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } public void CopyTo(Array array, int index) { ((ICollection)m_list).CopyTo(array, index); } public void CopyTo(Cookie[] array, int index) { m_list.CopyTo(array, index); } internal DateTime TimeStamp(Stamp how) { switch (how) { case Stamp.Set: m_TimeStamp = DateTime.Now; break; case Stamp.SetToMaxUsed: m_TimeStamp = DateTime.MaxValue; break; case Stamp.SetToUnused: m_TimeStamp = DateTime.MinValue; break; case Stamp.Check: default: break; } return m_TimeStamp; } // This is for internal cookie container usage. // For others not that _hasOtherVersions gets changed ONLY in InternalAdd internal bool IsOtherVersionSeen { get { return m_has_other_versions; } } // If isStrict == false, assumes that incoming cookie is unique. // If isStrict == true, replace the cookie if found same with newest Variant. // Returns 1 if added, 0 if replaced or rejected. /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif int InternalAdd(Cookie cookie, bool isStrict) { int ret = 1; if (isStrict) { int idx = 0; foreach (Cookie c in m_list) { if (CookieComparer.Compare(cookie, c) == 0) { ret = 0; // Will replace or reject // Cookie2 spec requires that new Variant cookie overwrite the old one. if (c.Variant <= cookie.Variant) { m_list[idx] = cookie; } break; } ++idx; } if (idx == m_list.Count) { m_list.Add(cookie); } } else { m_list.Add(cookie); } if (cookie.Version != Cookie.MaxSupportedVersion) { m_has_other_versions = true; } return ret; } internal int IndexOf(Cookie cookie) { int idx = 0; foreach (Cookie c in m_list) { if (CookieComparer.Compare(cookie, c) == 0) { return idx; } ++idx; } return -1; } internal void RemoveAt(int idx) { m_list.RemoveAt(idx); } public IEnumerator GetEnumerator() { return m_list.GetEnumerator(); } #if DEBUG internal void Dump() { if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); foreach (Cookie cookie in this) { cookie.Dump(); } } } #endif } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Windows.Forms; using XenAPI; using XenAdmin.Actions; using XenAdmin.Network; using XenAdmin.Core; namespace XenAdmin.Dialogs { public partial class RoleElevationDialog : XenDialogBase { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public Session elevatedSession; public string elevatedPassword; public string elevatedUsername; private List<Role> authorizedRoles; /// <summary> /// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs /// out the elevated session. If successful exposes the elevated session, password and username as fields. /// </summary> /// <param name="connection">The current server connection with the role information</param> /// <param name="session">The session on which we have been denied access</param> /// <param name="authorizedRoles">A list of roles that are able to complete the task</param> /// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param> public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle) :base(connection) { InitializeComponent(); UserDetails ud = session.CurrentUserDetails; labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER; labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles); authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1)); labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles); labelServerValue.Text = Helpers.GetName(connection); labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON; if (string.IsNullOrEmpty(actionTitle)) { labelCurrentAction.Visible = false; labelCurrentActionValue.Visible = false; } else { labelCurrentActionValue.Text = actionTitle; } this.authorizedRoles = authorizedRoles; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); Text = BrandManager.BrandConsole; } private void buttonAuthorize_Click(object sender, EventArgs e) { try { Exception delegateException = null; log.Debug("Testing logging in with the new credentials"); DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection, Messages.AUTHORIZING_USER, Messages.CREDENTIALS_CHECKING, Messages.CREDENTIALS_CHECK_COMPLETE, delegate { try { elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text); } catch (Exception ex) { delegateException = ex; } }); using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee) {ShowTryAgainMessage = false}) dlg.ShowDialog(this); // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog if (loginAction.Exception != null) return; if(HandledAnyDelegateException(delegateException)) return; if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession)) { elevatedUsername = TextBoxUsername.Text.Trim(); elevatedPassword = TextBoxPassword.Text; DialogResult = DialogResult.OK; Close(); return; } ShowNotAuthorisedDialog(); } catch (Exception ex) { log.DebugFormat("Exception when attempting to sudo action: {0} ", ex); using (var dlg = new ErrorDialog(string.Format(Messages.USER_AUTHORIZATION_FAILED, BrandManager.BrandConsole, TextBoxUsername.Text))) dlg.ShowDialog(Parent); TextBoxPassword.Focus(); TextBoxPassword.SelectAll(); } finally { // Check whether we have a successful elevated session and whether we have been asked to log it out // If non successful (most likely the new subject is not authorized) then log it out anyway. if (elevatedSession != null && DialogResult != DialogResult.OK) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } } private bool HandledAnyDelegateException(Exception delegateException) { if (delegateException != null) { Failure f = delegateException as Failure; if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { ShowNotAuthorisedDialog(); return true; } throw delegateException; } return false; } private void ShowNotAuthorisedDialog() { using (var dlg = new ErrorDialog(Messages.USER_NOT_AUTHORIZED) {WindowTitle = Messages.PERMISSION_DENIED}) { dlg.ShowDialog(this); } TextBoxPassword.Focus(); TextBoxPassword.SelectAll(); } private bool SessionAuthorized(Session s) { UserDetails ud = s.CurrentUserDetails; foreach (Role r in s.Roles) { if (authorizedRoles.Contains(r)) { log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return true; } } log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return false; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void UpdateButtons() { buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != ""; } private void TextBoxUsername_TextChanged(object sender, EventArgs e) { UpdateButtons(); } private void TextBoxPassword_TextChanged(object sender, EventArgs e) { UpdateButtons(); } } }
// --------------------------------------------------------------------------- // <copyright file="TemporaryDatabase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using System; using System.Globalization; using Microsoft.Isam.Esent.Interop; using Microsoft.Isam.Esent.Interop.Server2003; using Microsoft.Isam.Esent.Interop.Vista; using Microsoft.Isam.Esent.Interop.Windows7; /// <summary> /// A Database is a file used by the ISAM to store data. It is organized /// into tables which are in turn comprised of columns and indices and /// contain data in the form of records. The database's schema can be /// enumerated and manipulated by this object. Also, the database's /// tables can be opened for access by this object. /// <para> /// A <see cref="TemporaryDatabase"/> is used to access the temporary database. There /// is one temporary database per instance and its location is configured /// by Instance.IsamSystemParameters.TempPath. The temporary database is used /// to store temporary tables. /// </para> /// </summary> public class TemporaryDatabase : DatabaseCommon, IDisposable { /// <summary> /// The table collection /// </summary> private TableCollection tableCollection = null; /// <summary> /// The temporary table handle collection /// </summary> private TempTableHandleCollection tempTableHandleCollection = null; /// <summary> /// The cleanup /// </summary> private bool cleanup = false; /// <summary> /// The disposed /// </summary> private bool disposed = false; /// <summary> /// Initializes a new instance of the <see cref="TemporaryDatabase"/> class. /// </summary> /// <param name="isamSession">The session.</param> internal TemporaryDatabase(IsamSession isamSession) : base(isamSession) { lock (isamSession) { this.cleanup = true; this.tableCollection = new TableCollection(); this.tempTableHandleCollection = new TempTableHandleCollection(false); } } /// <summary> /// Finalizes an instance of the TemporaryDatabase class /// </summary> ~TemporaryDatabase() { this.Dispose(false); } /// <summary> /// Gets a collection of tables in the database. /// </summary> /// <returns>a collection of tables in the database</returns> public override TableCollection Tables { get { this.CheckDisposed(); return this.tableCollection; } } /// <summary> /// Gets or sets a value indicating whether [disposed]. /// </summary> /// <value> /// <c>true</c> if [disposed]; otherwise, <c>false</c>. /// </value> internal override bool Disposed { get { return this.disposed || this.IsamSession.Disposed; } set { this.disposed = value; } } /// <summary> /// Gets the temporary table handles. /// </summary> /// <value> /// The temporary table handles. /// </value> private TempTableHandleCollection TempTableHandles { get { this.CheckDisposed(); return this.tempTableHandleCollection; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public new void Dispose() { lock (this) { this.Dispose(true); } GC.SuppressFinalize(this); } /// <summary> /// Creates a single table with the specified definition in the database /// </summary> /// <param name="tableDefinition">The table definition.</param> /// <exception cref="EsentTableDuplicateException"> /// Thrown when the table definition overlaps with an already existing table. /// </exception> /// <exception cref="System.ArgumentException">A MaxKeyLength &gt; 255 is not supported for indices over a temporary table on this version of the database engine.;tableDefinition</exception> public override void CreateTable(TableDefinition tableDefinition) { lock (this.IsamSession) { this.CheckDisposed(); // validate the table definition for creating a TT this.ValidateTableDefinition(tableDefinition); // convert the given table definition into an JET_OPENTEMPORARYTABLE // struct that we will use to create the TT JET_OPENTEMPORARYTABLE openTemporaryTable = this.MakeOpenTemporaryTable(tableDefinition); // check if the TT already exists if (this.Exists(tableDefinition.Name)) { throw new EsentTableDuplicateException(); } // do not allow the TT to be created if the session is in a // transaction. we disallow this to sidestep the problem where // JET will automatically close (and destroy) the TT if the // current level of the transaction is aborted if (this.IsamSession.TransactionLevel > 0) { // NOTE: i'm thinking that this requirement is pretty lame, // especially since it only hits us on an abort. I am going // to allow this for now and see what happens // throw new ArgumentException( "We do not currently allow you to create temp tables while inside of a transaction." ); } // create the TT JET_TABLEID tableid = new JET_TABLEID(); if (DatabaseCommon.CheckEngineVersion( this.IsamSession, DatabaseCommon.ESENTVersion(6, 0, 6000, 0), DatabaseCommon.ESEVersion(8, 0, 685, 0))) { VistaApi.JetOpenTemporaryTable(this.IsamSession.Sesid, openTemporaryTable); tableid = openTemporaryTable.tableid; } else { if (openTemporaryTable.cbKeyMost > 255) { throw new ArgumentException("A MaxKeyLength > 255 is not supported for indices over a temporary table on this version of the database engine.", "tableDefinition"); } Api.JetOpenTempTable2( this.IsamSession.Sesid, openTemporaryTable.prgcolumndef, openTemporaryTable.prgcolumndef.Length, openTemporaryTable.pidxunicode.lcid, openTemporaryTable.grbit, out tableid, openTemporaryTable.prgcolumnid); } // re-create the TT's schema to reflect the created TT TableDefinition tableDefinitionToCache = MakeTableDefinitionToCache(tableDefinition, openTemporaryTable); // cache the TT and its handle TempTableHandle tempTableHandle = new TempTableHandle( tableDefinitionToCache.Name, this.IsamSession.Sesid, tableid, tableDefinitionToCache.Type == TableType.Sort || tableDefinitionToCache.Type == TableType.PreSortTemporary); this.Tables.Add(tableDefinitionToCache); this.TempTableHandles.Add(tempTableHandle); this.IsamSession.IsamInstance.TempTableHandles.Add(tempTableHandle); } } /// <summary> /// Deletes a single table in the database /// </summary> /// <param name="tableName">Name of the table.</param> /// <exception cref="EsentObjectNotFoundException"> /// Thrown when the specified table can't be found. /// </exception> /// <exception cref="EsentTableInUseException"> /// Thrown when the specified table still has cursors open. /// </exception> /// <remarks> /// It is currently not possible to delete a table that is being used /// by a Cursor. All such Cursors must be disposed before the /// table can be successfully deleted. /// </remarks> public override void DropTable(string tableName) { lock (this.IsamSession) { this.CheckDisposed(); if (!this.Exists(tableName)) { throw new EsentObjectNotFoundException(); } TempTableHandle tempTableHandle = this.TempTableHandles[tableName]; if (tempTableHandle.CursorCount > 0) { throw new EsentTableInUseException(); } this.Tables.Remove(tableName); Api.JetCloseTable(this.IsamSession.Sesid, tempTableHandle.Handle); this.TempTableHandles.Remove(tempTableHandle.Name); this.IsamSession.IsamInstance.TempTableHandles.Remove(tempTableHandle.Guid.ToString()); } } /// <summary> /// Determines if a given table exists in the database /// </summary> /// <param name="tableName">Name of the table.</param> /// <returns> /// true if the table was found, false otherwise /// </returns> public override bool Exists(string tableName) { this.CheckDisposed(); return this.Tables.Contains(tableName); } /// <summary> /// Opens a cursor over the specified table. /// </summary> /// <param name="tableName">the name of the table to be opened</param> /// <returns>a cursor over the specified table in this database</returns> public override Cursor OpenCursor(string tableName) { lock (this.IsamSession) { this.CheckDisposed(); if (!this.Exists(tableName)) { throw new EsentObjectNotFoundException(); } TableDefinition tableDefinition = this.Tables[tableName]; TempTableHandle tempTableHandle = this.TempTableHandles[tableName]; JET_TABLEID tableid; try { // if this is a Sort then we must always fail to dup the // cursor // // NOTE: this is a hack to work around problems in ESE/ESENT // that we cannot fix because we must work downlevel if (tableDefinition.Type == TableType.Sort) { throw new EsentIllegalOperationException(); } Api.JetDupCursor(this.IsamSession.Sesid, tempTableHandle.Handle, out tableid, DupCursorGrbit.None); tempTableHandle.InInsertMode = false; } catch (EsentIllegalOperationException) { if (tempTableHandle.CursorCount > 0) { throw new InvalidOperationException("It is not possible to have multiple open cursors on a temporary table that is currently in insert mode."); } else { tableid = tempTableHandle.Handle; } } Cursor newCursor = new Cursor(this.IsamSession, this, tableName, tableid, tempTableHandle.InInsertMode); tempTableHandle.CursorCount++; return newCursor; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { this.Dispose(); } /// <summary> /// Releases the temporary table. /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="inInsertMode">if set to <c>true</c> [in insert mode].</param> internal void ReleaseTempTable(string tableName, bool inInsertMode) { lock (this.IsamSession) { TempTableHandle tempTableHandle = this.TempTableHandles[tableName]; tempTableHandle.InInsertMode = inInsertMode; tempTableHandle.CursorCount--; } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { lock (this.IsamSession) { if (!this.Disposed) { if (this.cleanup) { foreach (TempTableHandle tempTableHandle in this.TempTableHandles) { Api.JetCloseTable(this.IsamSession.Sesid, tempTableHandle.Handle); this.IsamSession.IsamInstance.TempTableHandles.Remove(tempTableHandle.Guid.ToString()); } base.Dispose(disposing); this.cleanup = false; } this.Disposed = true; } } } /// <summary> /// Creates a <see cref="TableDefinition"/> object from a <see cref="JET_OPENTEMPORARYTABLE"/> /// object, suitable for caching. /// </summary> /// <param name="tableDefinition">The table definition.</param> /// <param name="openTemporaryTable">The open temporary table.</param> /// <returns>A <see cref="TableDefinition"/> object suitable for caching.</returns> private static TableDefinition MakeTableDefinitionToCache( TableDefinition tableDefinition, JET_OPENTEMPORARYTABLE openTemporaryTable) { // set the new table properties TableDefinition tableDefinitionToCache = new TableDefinition(tableDefinition.Name, tableDefinition.Type); // add the columns complete with the columnids generated when the // TT was created // // NOTE: this processing loop has to mirror the loop used to generate // the columndefs in MakeOpenTemporaryTable int currentColumndef = 0; foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { ColumnDefinition columnDefinition = tableDefinition.Columns[keyColumn.Name]; Columnid columnid = new Columnid( columnDefinition.Name, openTemporaryTable.prgcolumnid[currentColumndef], DatabaseCommon.ColtypFromColumnDefinition(columnDefinition), columnDefinition.IsAscii); ColumnDefinition columnDefinitionToCache = new ColumnDefinition(columnid); columnDefinitionToCache.Flags = columnDefinition.Flags; columnDefinitionToCache.MaxLength = columnDefinition.MaxLength; columnDefinitionToCache.ReadOnly = true; tableDefinitionToCache.Columns.Add(columnDefinitionToCache); currentColumndef++; } } // next collect the rest of the columns and put them after the key // columns, skipping over the columns we already added foreach (ColumnDefinition columnDefinition in tableDefinition.Columns) { bool alreadyAdded = false; foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { if (keyColumn.Name.ToLower(CultureInfo.InvariantCulture) == columnDefinition.Name.ToLower(CultureInfo.InvariantCulture)) { alreadyAdded = true; } } } if (!alreadyAdded) { Columnid columnid = new Columnid( columnDefinition.Name, openTemporaryTable.prgcolumnid[currentColumndef], DatabaseCommon.ColtypFromColumnDefinition(columnDefinition), columnDefinition.IsAscii); ColumnDefinition columnDefinitionToCache = new ColumnDefinition(columnid); columnDefinitionToCache.Flags = columnDefinition.Flags; columnDefinitionToCache.MaxLength = columnDefinition.MaxLength; columnDefinitionToCache.ReadOnly = true; tableDefinitionToCache.Columns.Add(columnDefinitionToCache); currentColumndef++; } } tableDefinitionToCache.Columns.ReadOnly = true; // add the indices foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { IndexDefinition indexDefinitionToCache = new IndexDefinition(indexDefinition.Name); indexDefinitionToCache.Flags = indexDefinition.Flags; indexDefinitionToCache.Density = 100; indexDefinitionToCache.CultureInfo = indexDefinition.CultureInfo; indexDefinitionToCache.CompareOptions = indexDefinition.CompareOptions; indexDefinitionToCache.MaxKeyLength = indexDefinition.MaxKeyLength; foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { Columnid columnid = tableDefinitionToCache.Columns[keyColumn.Name].Columnid; KeyColumn keyColumnToCache = new KeyColumn(columnid, keyColumn.IsAscending); indexDefinitionToCache.KeyColumns.Add(keyColumnToCache); } indexDefinitionToCache.KeyColumns.ReadOnly = true; indexDefinitionToCache.ReadOnly = true; tableDefinitionToCache.Indices.Add(indexDefinitionToCache); } tableDefinitionToCache.Indices.ReadOnly = true; // return the table definition return tableDefinitionToCache; } /// <summary> /// Makes the <see cref="JET_OPENTEMPORARYTABLE"/> object to later open it. /// </summary> /// <param name="tableDefinition">The table definition.</param> /// <returns>The newly created <see cref="JET_OPENTEMPORARYTABLE"/> object.</returns> private JET_OPENTEMPORARYTABLE MakeOpenTemporaryTable(TableDefinition tableDefinition) { JET_OPENTEMPORARYTABLE openTemporaryTable = new JET_OPENTEMPORARYTABLE(); // allocate room for our columns int currentColumndef = 0; openTemporaryTable.ccolumn = tableDefinition.Columns.Count; openTemporaryTable.prgcolumndef = new JET_COLUMNDEF[openTemporaryTable.ccolumn]; openTemporaryTable.prgcolumnid = new JET_COLUMNID[openTemporaryTable.ccolumn]; for (int coldef = 0; coldef < openTemporaryTable.ccolumn; ++coldef) { openTemporaryTable.prgcolumndef[coldef] = new JET_COLUMNDEF(); } // first, collect all the key columns in order and put them as the // first columndefs. we have to do this to guarantee that the TT // is sorted properly foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { ColumnDefinition columnDefinition = tableDefinition.Columns[keyColumn.Name]; openTemporaryTable.prgcolumndef[currentColumndef].coltyp = DatabaseCommon.ColtypFromColumnDefinition(columnDefinition); openTemporaryTable.prgcolumndef[currentColumndef].cp = JET_CP.Unicode; openTemporaryTable.prgcolumndef[currentColumndef].cbMax = columnDefinition.MaxLength; openTemporaryTable.prgcolumndef[currentColumndef].grbit = (ColumndefGrbit)columnDefinition.Flags | ColumndefGrbit.TTKey | (keyColumn.IsAscending ? ColumndefGrbit.None : ColumndefGrbit.TTDescending); currentColumndef++; } } // next collect the rest of the columns and put them after the key // columns, skipping over the columns we already added foreach (ColumnDefinition columnDefinition in tableDefinition.Columns) { bool alreadyAdded = false; foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { if (keyColumn.Name.ToLower(CultureInfo.InvariantCulture) == columnDefinition.Name.ToLower(CultureInfo.InvariantCulture)) { alreadyAdded = true; } } } if (!alreadyAdded) { openTemporaryTable.prgcolumndef[currentColumndef].coltyp = DatabaseCommon.ColtypFromColumnDefinition(columnDefinition); openTemporaryTable.prgcolumndef[currentColumndef].cp = JET_CP.Unicode; openTemporaryTable.prgcolumndef[currentColumndef].cbMax = columnDefinition.MaxLength; openTemporaryTable.prgcolumndef[currentColumndef].grbit = Converter.ColumndefGrbitFromColumnFlags(columnDefinition.Flags); currentColumndef++; } } // set the index flags foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { openTemporaryTable.pidxunicode = new JET_UNICODEINDEX(); openTemporaryTable.pidxunicode.lcid = indexDefinition.CultureInfo.LCID; UnicodeIndexFlags unicodeIndexFlags = Converter.UnicodeFlagsFromCompareOptions(indexDefinition.CompareOptions); openTemporaryTable.pidxunicode.dwMapFlags = Converter.MapFlagsFromUnicodeIndexFlags(unicodeIndexFlags); } // infer the TT mode of operation and set its grbits accordingly bool haveColumnWithLongValue = false; foreach (ColumnDefinition columnDefinition in tableDefinition.Columns) { JET_coltyp coltyp = DatabaseCommon.ColtypFromColumnDefinition(columnDefinition); if (coltyp == JET_coltyp.LongText || coltyp == JET_coltyp.LongBinary) { haveColumnWithLongValue = true; } } bool haveIndexWithSortNullsHigh = false; foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { if ((indexDefinition.Flags & IndexFlags.SortNullsHigh) != 0) { haveIndexWithSortNullsHigh = true; } } if (tableDefinition.Type == TableType.Sort) { foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { if ((indexDefinition.Flags & (IndexFlags.Unique | IndexFlags.Primary)) == 0) { // External Sort without duplicate removal openTemporaryTable.grbit = Server2003Grbits.ForwardOnly | (haveColumnWithLongValue ? Windows7Grbits.IntrinsicLVsOnly : TempTableGrbit.None) | (haveIndexWithSortNullsHigh ? TempTableGrbit.SortNullsHigh : TempTableGrbit.None); } else { // External Sort TT with deferred duplicate removal openTemporaryTable.grbit = TempTableGrbit.Unique | (haveColumnWithLongValue ? Windows7Grbits.IntrinsicLVsOnly : TempTableGrbit.None) | (haveIndexWithSortNullsHigh ? TempTableGrbit.SortNullsHigh : TempTableGrbit.None); } } } else if (tableDefinition.Type == TableType.PreSortTemporary) { // Pre-sorted B+ Tree TT with deferred duplicate removal openTemporaryTable.grbit = TempTableGrbit.Indexed | TempTableGrbit.Unique | TempTableGrbit.Updatable | TempTableGrbit.Scrollable | (haveColumnWithLongValue ? Windows7Grbits.IntrinsicLVsOnly : TempTableGrbit.None) | (haveIndexWithSortNullsHigh ? TempTableGrbit.SortNullsHigh : TempTableGrbit.None); } else if (tableDefinition.Type == TableType.Temporary) { if (tableDefinition.Indices.Count != 0) { // B+ Tree TT with immediate duplicate removal openTemporaryTable.grbit = TempTableGrbit.Indexed | TempTableGrbit.Unique | TempTableGrbit.Updatable | TempTableGrbit.Scrollable | TempTableGrbit.ForceMaterialization | (haveIndexWithSortNullsHigh ? TempTableGrbit.SortNullsHigh : TempTableGrbit.None); } else { // B+ Tree TT with a sequential index openTemporaryTable.grbit = TempTableGrbit.Updatable | TempTableGrbit.Scrollable; } } // set the key construction parameters for the TT foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { openTemporaryTable.cbKeyMost = indexDefinition.MaxKeyLength; openTemporaryTable.cbVarSegMac = 0; } // return the constructed JET_OPENTEMPORARYTABLE (whew!) return openTemporaryTable; } /// <summary> /// Checks whether this object is disposed. /// </summary> /// <exception cref="System.ObjectDisposedException">If the object has already been disposed.</exception> private void CheckDisposed() { lock (this.IsamSession) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } } } /// <summary> /// Validates the table definition. /// </summary> /// <param name="tableDefinition">The table definition.</param> /// <exception cref="System.ArgumentException"> /// Illegal name for a temporary table.;tableDefinition /// or /// Illegal TableType for a temporary table.;tableDefinition /// or /// Temporary tables must have at least one column.;tableDefinition /// or /// Illegal name for a column in a temporary table.;tableDefinition /// or /// Illegal ColumnFlags for a column in a temporary table.;tableDefinition /// or /// Default values are not supported for temporary table columns.;tableDefinition /// or /// Temporary tables of type TableType.Sort and TableType.PreSortTemporary must have an index defined.;tableDefinition /// or /// Temporary tables may only have a single index defined.;tableDefinition /// or /// Illegal name for an index in a temporary table.;tableDefinition /// or /// Illegal IndexFlags for an index in a temporary table.;tableDefinition /// or /// Illegal or unsupported MaxKeyLength for an index in a temporary table.;tableDefinition /// or /// No KeyColumns for an index in a temporary table.;tableDefinition /// or /// Too many KeyColumns for an index in a temporary table.;tableDefinition /// or /// A KeyColumn for an index in the temporary table refers to a column that doesn't exist.;tableDefinition /// or /// Conditional columns are not supported for temporary table indices.;tableDefinition /// or /// Temporary tables of type TableType.PreSortTemporary and TableType.Temporary must have a primary index defined.;tableDefinition /// </exception> private void ValidateTableDefinition(TableDefinition tableDefinition) { // validate the table's properties DatabaseCommon.CheckName( tableDefinition.Name, new ArgumentException("Illegal name for a temporary table.", "tableDefinition")); if (tableDefinition.Name == null) { throw new ArgumentException("Illegal name for a temporary table.", "tableDefinition"); } if ( !(tableDefinition.Type == TableType.Sort || tableDefinition.Type == TableType.PreSortTemporary || tableDefinition.Type == TableType.Temporary)) { throw new ArgumentException("Illegal TableType for a temporary table.", "tableDefinition"); } // validate all columns if (tableDefinition.Columns.Count == 0) { throw new ArgumentException("Temporary tables must have at least one column.", "tableDefinition"); } foreach (ColumnDefinition columnDefinition in tableDefinition.Columns) { DatabaseCommon.CheckName( columnDefinition.Name, new ArgumentException("Illegal name for a column in a temporary table.", "tableDefinition")); if (columnDefinition.Name == null) { throw new ArgumentException("Illegal name for a column in a temporary table.", "tableDefinition"); } if (tableDefinition.Type == TableType.Sort || tableDefinition.Type == TableType.PreSortTemporary) { JET_coltyp coltyp = DatabaseCommon.ColtypFromColumnDefinition(columnDefinition); if (coltyp == JET_coltyp.LongText || coltyp == JET_coltyp.LongBinary) { // timestamp when ESE/ESENT supports JET_bitTTIntrinsicLVsOnly DatabaseCommon.CheckEngineVersion( this.IsamSession, DatabaseCommon.ESENTVersion(6, 1, 6492, 0), DatabaseCommon.ESEVersion(14, 0, 46, 0), new ArgumentException( "LongText and LongBinary columns are not supported for columns in a temporary table of type TableType.Sort or TableType.PreSortTemporary on this version of the database engine.", "tableDefinition")); } } if (0 != (columnDefinition.Flags & ~(ColumnFlags.Fixed | ColumnFlags.Variable | ColumnFlags.Sparse | ColumnFlags.NonNull | ColumnFlags.MultiValued))) { throw new ArgumentException("Illegal ColumnFlags for a column in a temporary table.", "tableDefinition"); } if (columnDefinition.DefaultValue != null) { throw new ArgumentException("Default values are not supported for temporary table columns.", "tableDefinition"); } } // validate all indices if (tableDefinition.Indices.Count == 0 && (tableDefinition.Type == TableType.Sort || tableDefinition.Type == TableType.PreSortTemporary)) { throw new ArgumentException("Temporary tables of type TableType.Sort and TableType.PreSortTemporary must have an index defined.", "tableDefinition"); } if (tableDefinition.Indices.Count > 1) { throw new ArgumentException("Temporary tables may only have a single index defined.", "tableDefinition"); } foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { DatabaseCommon.CheckName( indexDefinition.Name, new ArgumentException("Illegal name for an index in a temporary table.", "tableDefinition")); if (indexDefinition.Name == null) { throw new ArgumentException("Illegal name for an index in a temporary table.", "tableDefinition"); } if (0 != (indexDefinition.Flags & ~(IndexFlags.Unique | IndexFlags.Primary | IndexFlags.AllowNull | IndexFlags.SortNullsLow | IndexFlags.SortNullsHigh | IndexFlags.AllowTruncation))) { throw new ArgumentException("Illegal IndexFlags for an index in a temporary table.", "tableDefinition"); } // Require AllowTruncation. if (0 == (indexDefinition.Flags & IndexFlags.AllowTruncation)) { throw new ArgumentException("Illegal IndexFlags for an index in a temporary table.", "tableDefinition"); } // 255 in XP. long keyMost = this.IsamSession.IsamInstance.IsamSystemParameters.KeyMost; if (indexDefinition.MaxKeyLength < 255 || indexDefinition.MaxKeyLength > keyMost) { throw new ArgumentException("Illegal or unsupported MaxKeyLength for an index in a temporary table.", "tableDefinition"); } // 12 in XP. 16 in Vista. int keyColumnMost = 16; if (indexDefinition.KeyColumns.Count == 0) { throw new ArgumentException("No KeyColumns for an index in a temporary table.", "tableDefinition"); } if (indexDefinition.KeyColumns.Count > keyColumnMost) { throw new ArgumentException("Too many KeyColumns for an index in a temporary table.", "tableDefinition"); } foreach (KeyColumn keyColumn in indexDefinition.KeyColumns) { if (!tableDefinition.Columns.Contains(keyColumn.Name)) { throw new ArgumentException("A KeyColumn for an index in the temporary table refers to a column that doesn't exist.", "tableDefinition"); } } if (indexDefinition.ConditionalColumns.Count != 0) { throw new ArgumentException("Conditional columns are not supported for temporary table indices.", "tableDefinition"); } if ((indexDefinition.Flags & IndexFlags.Primary) == 0 && (tableDefinition.Type == TableType.PreSortTemporary || tableDefinition.Type == TableType.Temporary)) { throw new ArgumentException("Temporary tables of type TableType.PreSortTemporary and TableType.Temporary must have a primary index defined.", "tableDefinition"); } } } } }
/******************************************************** * ADO.NET 2.0 Data Provider for SQLite Version 3.X * Written by Robert Simpson (robert@blackcastlesoft.com) * * Released to the public domain, use at your own risk! ********************************************************/ namespace System.Data.SQLite { using System; using System.Data.Common; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Metadata.Edm; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Data.Entity.Core.Common; public class SQLiteProviderServices : DbProviderServices { internal static readonly SQLiteProviderServices Instance = new SQLiteProviderServices(); protected override DbCommandDefinition CreateDbCommandDefinition(DbProviderManifest manifest, DbCommandTree commandTree) { DbCommand prototype = CreateCommand(manifest, commandTree); DbCommandDefinition result = this.CreateCommandDefinition(prototype); return result; } protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { var sql = DdlBuilder.CreateObjectsScript(storeItemCollection); connection.Open(); using (var cmd = connection.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { return DdlBuilder.CreateObjectsScript(storeItemCollection); } //protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) //{ // throw new NotImplementedException(); //} protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection.Database == ":memory:") { return false; } return false; } protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { base.DbDeleteDatabase(connection, commandTimeout, storeItemCollection); } private DbCommand CreateCommand(DbProviderManifest manifest, DbCommandTree commandTree) { if (manifest == null) throw new ArgumentNullException("manifest"); if (commandTree == null) throw new ArgumentNullException("commandTree"); SQLiteCommand command = new SQLiteCommand(); try { List<DbParameter> parameters; CommandType commandType; command.CommandText = SqlGenerator.GenerateSql((SQLiteProviderManifest)manifest, commandTree, out parameters, out commandType); command.CommandType = commandType; // Get the function (if any) implemented by the command tree since this influences our interpretation of parameters EdmFunction function = null; if (commandTree is DbFunctionCommandTree) { function = ((DbFunctionCommandTree)commandTree).EdmFunction; } // Now make sure we populate the command's parameters from the CQT's parameters: foreach (KeyValuePair<string, TypeUsage> queryParameter in commandTree.Parameters) { SQLiteParameter parameter; // Use the corresponding function parameter TypeUsage where available (currently, the SSDL facets and // type trump user-defined facets and type in the EntityCommand). FunctionParameter functionParameter; if (null != function && function.Parameters.TryGetValue(queryParameter.Key, false, out functionParameter)) { parameter = CreateSqlParameter(functionParameter.Name, functionParameter.TypeUsage, functionParameter.Mode, DBNull.Value); } else { parameter = CreateSqlParameter(queryParameter.Key, queryParameter.Value, ParameterMode.In, DBNull.Value); } command.Parameters.Add(parameter); } // Now add parameters added as part of SQL gen (note: this feature is only safe for DML SQL gen which // does not support user parameters, where there is no risk of name collision) if (null != parameters && 0 < parameters.Count) { if (!(commandTree is DbInsertCommandTree) && !(commandTree is DbUpdateCommandTree) && !(commandTree is DbDeleteCommandTree)) { throw new InvalidOperationException("SqlGenParametersNotPermitted"); } foreach (DbParameter parameter in parameters) { command.Parameters.Add(parameter); } } return command; } catch { command.Dispose(); throw; } } protected override string GetDbProviderManifestToken(DbConnection connection) { if (String.IsNullOrEmpty(connection.ConnectionString)) throw new ArgumentNullException("ConnectionString"); SortedList<string, string> opts = SQLiteConnection.ParseConnectionString(connection.ConnectionString); return SQLiteConnection.FindKey(opts, "DateTimeFormat", "ISO8601"); } protected override DbProviderManifest GetDbProviderManifest(string versionHint) { return new SQLiteProviderManifest(versionHint); } /// <summary> /// Creates a SQLiteParameter given a name, type, and direction /// </summary> internal static SQLiteParameter CreateSqlParameter(string name, TypeUsage type, ParameterMode mode, object value) { int? size; SQLiteParameter result = new SQLiteParameter(name, value); // .Direction ParameterDirection direction = MetadataHelpers.ParameterModeToParameterDirection(mode); if (result.Direction != direction) { result.Direction = direction; } // .Size and .DbType // output parameters are handled differently (we need to ensure there is space for return // values where the user has not given a specific Size/MaxLength) bool isOutParam = mode != ParameterMode.In; DbType sqlDbType = GetSqlDbType(type, isOutParam, out size); if (result.DbType != sqlDbType) { result.DbType = sqlDbType; } // Note that we overwrite 'facet' parameters where either the value is different or // there is an output parameter. if (size.HasValue && (isOutParam || result.Size != size.Value)) { result.Size = size.Value; } // .IsNullable bool isNullable = MetadataHelpers.IsNullable(type); if (isOutParam || isNullable != result.IsNullable) { result.IsNullable = isNullable; } return result; } /// <summary> /// Determines DbType for the given primitive type. Extracts facet /// information as well. /// </summary> private static DbType GetSqlDbType(TypeUsage type, bool isOutParam, out int? size) { // only supported for primitive type PrimitiveTypeKind primitiveTypeKind = MetadataHelpers.GetPrimitiveTypeKind(type); size = default(int?); switch (primitiveTypeKind) { case PrimitiveTypeKind.Binary: // for output parameters, ensure there is space... size = GetParameterSize(type, isOutParam); return GetBinaryDbType(type); case PrimitiveTypeKind.Boolean: return DbType.Boolean; case PrimitiveTypeKind.Byte: return DbType.Byte; case PrimitiveTypeKind.Time: return DbType.Time; case PrimitiveTypeKind.DateTimeOffset: return DbType.DateTimeOffset; case PrimitiveTypeKind.DateTime: return DbType.DateTime; case PrimitiveTypeKind.Decimal: return DbType.Decimal; case PrimitiveTypeKind.Double: return DbType.Double; case PrimitiveTypeKind.Guid: return DbType.Guid; case PrimitiveTypeKind.Int16: return DbType.Int16; case PrimitiveTypeKind.Int32: return DbType.Int32; case PrimitiveTypeKind.Int64: return DbType.Int64; case PrimitiveTypeKind.SByte: return DbType.SByte; case PrimitiveTypeKind.Single: return DbType.Single; case PrimitiveTypeKind.String: size = GetParameterSize(type, isOutParam); return GetStringDbType(type); default: Debug.Fail("unknown PrimitiveTypeKind " + primitiveTypeKind); return DbType.Object; } } /// <summary> /// Determines preferred value for SqlParameter.Size. Returns null /// where there is no preference. /// </summary> private static int? GetParameterSize(TypeUsage type, bool isOutParam) { int maxLength; if (MetadataHelpers.TryGetMaxLength(type, out maxLength)) { // if the MaxLength facet has a specific value use it return maxLength; } else if (isOutParam) { // if the parameter is a return/out/inout parameter, ensure there // is space for any value return int.MaxValue; } else { // no value return default(int?); } } /// <summary> /// Chooses the appropriate DbType for the given string type. /// </summary> private static DbType GetStringDbType(TypeUsage type) { Debug.Assert(type.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType && PrimitiveTypeKind.String == ((PrimitiveType)type.EdmType).PrimitiveTypeKind, "only valid for string type"); DbType dbType; // Specific type depends on whether the string is a unicode string and whether it is a fixed length string. // By default, assume widest type (unicode) and most common type (variable length) bool unicode; bool fixedLength; if (!MetadataHelpers.TryGetIsFixedLength(type, out fixedLength)) { fixedLength = false; } if (!MetadataHelpers.TryGetIsUnicode(type, out unicode)) { unicode = true; } if (fixedLength) { dbType = (unicode ? DbType.StringFixedLength : DbType.AnsiStringFixedLength); } else { dbType = (unicode ? DbType.String : DbType.AnsiString); } return dbType; } /// <summary> /// Chooses the appropriate DbType for the given binary type. /// </summary> private static DbType GetBinaryDbType(TypeUsage type) { Debug.Assert(type.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType && PrimitiveTypeKind.Binary == ((PrimitiveType)type.EdmType).PrimitiveTypeKind, "only valid for binary type"); // Specific type depends on whether the binary value is fixed length. By default, assume variable length. bool fixedLength; if (!MetadataHelpers.TryGetIsFixedLength(type, out fixedLength)) { fixedLength = false; } return DbType.Binary; // return fixedLength ? DbType.Binary : DbType.VarBinary; } #region ISQLiteSchemaExtensions Members /// <summary> /// Creates temporary tables on the connection so schema information can be queried /// </summary> /// <remarks> /// There's a lot of work involved in getting schema information out of SQLite, but LINQ expects to /// be able to query on schema tables. Therefore we need to "fake" it by generating temporary tables /// filled with the schema of the current connection. We get away with making this information static /// because schema information seems to always be queried on a new connection object, so the schema is /// always fresh. /// </remarks> /// <param name="cnn">The connection upon which to build the schema tables</param> void BuildTempSchema(SQLiteConnection cnn) { string[] arr = new string[] { "TABLES", "COLUMNS", "VIEWS", "VIEWCOLUMNS", "INDEXES", "INDEXCOLUMNS", "FOREIGNKEYS", "CATALOGS" }; using (DataTable table = cnn.GetSchema("Tables", new string[] { "temp", null, String.Format("SCHEMA{0}", arr[0]) })) { if (table.Rows.Count > 0) return; } for (int n = 0; n < arr.Length; n++) { using (DataTable table = cnn.GetSchema(arr[n])) { DataTableToTable(cnn, table, String.Format("SCHEMA{0}", arr[n])); } } using (var cmd = cnn.CreateCommand()) { cmd.CommandText = Properties.Resources.SQL_CONSTRAINTS; cmd.ExecuteNonQuery(); cmd.CommandText = Properties.Resources.SQL_CONSTRAINTCOLUMNS; cmd.ExecuteNonQuery(); } } /// <summary> /// Turn a datatable into a table in the temporary database for the connection /// </summary> /// <param name="cnn">The connection to make the temporary table in</param> /// <param name="table">The table to write out</param> /// <param name="dest">The temporary table name to write to</param> private void DataTableToTable(SQLiteConnection cnn, DataTable table, string dest) { StringBuilder sql = new StringBuilder(); SQLiteCommandBuilder builder = new SQLiteCommandBuilder(); using (var cmd = cnn.CreateCommand()) using (DataTable source = new DataTable()) { sql.AppendFormat(CultureInfo.InvariantCulture, "CREATE TEMP TABLE {0} (", builder.QuoteIdentifier(dest)); string separator = String.Empty; foreach (DataColumn dc in table.Columns) { DbType dbtypeName = SQLiteConvert.TypeToDbType(dc.DataType); string typeName = SQLiteConvert.DbTypeToTypeName(dbtypeName); sql.AppendFormat(CultureInfo.InvariantCulture, "{2}{0} {1} COLLATE NOCASE", builder.QuoteIdentifier(dc.ColumnName), typeName, separator); separator = ", "; } sql.Append(")"); cmd.CommandText = sql.ToString(); cmd.ExecuteNonQuery(); cmd.CommandText = String.Format("SELECT * FROM TEMP.{0} WHERE 1=2", builder.QuoteIdentifier(dest)); using (SQLiteDataAdapter adp = new SQLiteDataAdapter(cmd)) { builder.DataAdapter = adp; adp.Fill(source); foreach (DataRow row in table.Rows) { object[] arr = row.ItemArray; source.Rows.Add(arr); } adp.Update(source); } } } #endregion } }
using OmniBeanEB.Library.Internal; using System; using System.Collections.Generic; using System.IO; namespace OmniBeanEB.Library { [SmallBasicType] public class File { public static EBPrimitive LastError { get; set; } public static EBPrimitive ReadContents(EBPrimitive filePath) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); try { if (!System.IO.File.Exists(path)) { EBPrimitive result = ""; return result; } using (StreamReader streamReader = new StreamReader(path)) { string value = streamReader.ReadToEnd(); EBPrimitive result = value; return result; } } catch (Exception ex) { File.LastError = ex.Message; } return ""; } public static EBPrimitive WriteContents(EBPrimitive filePath, EBPrimitive contents) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); try { using (StreamWriter streamWriter = new StreamWriter(path)) { streamWriter.Write((string)contents); return "SUCCESS"; } } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive ReadLine(EBPrimitive filePath, EBPrimitive lineNumber) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); if (lineNumber < 0) { return ""; } try { if (!System.IO.File.Exists(path)) { EBPrimitive result = ""; return result; } using (StreamReader streamReader = new StreamReader(path)) { EBPrimitive result; for (int i = 0; i < lineNumber - 1; i++) { if (streamReader.ReadLine() == null) { result = ""; return result; } } result = streamReader.ReadLine(); return result; } } catch (Exception ex) { File.LastError = ex.Message; } return ""; } public static EBPrimitive WriteLine(EBPrimitive filePath, EBPrimitive lineNumber, EBPrimitive contents) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); string tempFileName = Path.GetTempFileName(); try { EBPrimitive result; if (!System.IO.File.Exists(path)) { using (StreamWriter streamWriter = new StreamWriter(path)) { streamWriter.WriteLine((string)contents); } result = "SUCCESS"; return result; } using (StreamWriter streamWriter2 = new StreamWriter(tempFileName)) { using (StreamReader streamReader = new StreamReader(path)) { int num = 1; while (true) { string text = streamReader.ReadLine(); if (text == null) { break; } if (num == lineNumber) { streamWriter2.WriteLine((string)contents); } else { streamWriter2.WriteLine(text); } num++; } if (num <= lineNumber) { streamWriter2.WriteLine((string)contents); } } } System.IO.File.Copy(tempFileName, filePath, true); System.IO.File.Delete(tempFileName); result = "SUCCESS"; return result; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive InsertLine(EBPrimitive filePath, EBPrimitive lineNumber, EBPrimitive contents) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); string tempFileName = Path.GetTempFileName(); try { EBPrimitive result; if (!System.IO.File.Exists(path)) { using (StreamWriter streamWriter = new StreamWriter(path)) { streamWriter.WriteLine((string)contents); } result = "SUCCESS"; return result; } using (StreamWriter streamWriter2 = new StreamWriter(tempFileName)) { using (StreamReader streamReader = new StreamReader(path)) { int num = 1; while (true) { string text = streamReader.ReadLine(); if (text == null) { break; } if (num == lineNumber) { streamWriter2.WriteLine((string)contents); } streamWriter2.WriteLine(text); num++; } if (num <= lineNumber) { streamWriter2.WriteLine((string)contents); } } } System.IO.File.Copy(tempFileName, filePath, true); System.IO.File.Delete(tempFileName); result = "SUCCESS"; return result; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive AppendContents(EBPrimitive filePath, EBPrimitive contents) { File.LastError = ""; Environment.ExpandEnvironmentVariables(filePath); try { using (StreamWriter streamWriter = new StreamWriter(filePath, true)) { streamWriter.WriteLine((string)contents); } return "SUCCESS"; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive CopyFile(EBPrimitive sourceFilePath, EBPrimitive destinationFilePath) { File.LastError = ""; string text = Environment.ExpandEnvironmentVariables(sourceFilePath); string text2 = Environment.ExpandEnvironmentVariables(destinationFilePath); if (!System.IO.File.Exists(text)) { File.LastError = "Source file doesn't exist."; return "FAILED"; } if (Directory.Exists(text2) || text2[text2.Length - 1] == '\\') { text2 = Path.Combine(text2, Path.GetFileName(text)); } try { string directoryName = Path.GetDirectoryName(text2); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } System.IO.File.Copy(text, text2, true); return "SUCCESS"; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive DeleteFile(EBPrimitive filePath) { File.LastError = ""; string path = Environment.ExpandEnvironmentVariables(filePath); try { System.IO.File.Delete(path); return "SUCCESS"; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive CreateDirectory(EBPrimitive directoryPath) { File.LastError = ""; Environment.ExpandEnvironmentVariables(directoryPath); try { Directory.CreateDirectory(directoryPath); return "SUCCESS"; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive DeleteDirectory(EBPrimitive directoryPath) { File.LastError = ""; Environment.ExpandEnvironmentVariables(directoryPath); try { Directory.Delete(directoryPath, true); return "SUCCESS"; } catch (Exception ex) { File.LastError = ex.Message; } return "FAILED"; } public static EBPrimitive GetFiles(EBPrimitive directoryPath) { File.LastError = ""; Environment.ExpandEnvironmentVariables(directoryPath); EBPrimitive result; try { if (Directory.Exists(directoryPath)) { Dictionary<EBPrimitive, EBPrimitive> dictionary = new Dictionary<EBPrimitive, EBPrimitive>(); int num = 1; string[] files = Directory.GetFiles(directoryPath); for (int i = 0; i < files.Length; i++) { string value = files[i]; dictionary[num] = value; num++; } result = EBPrimitive.ConvertFromMap(dictionary); } else { File.LastError = "Directory Path does not exist."; result = "FAILED"; } } catch (Exception ex) { File.LastError = ex.Message; result = "FAILED"; } return result; } public static EBPrimitive GetDirectories(EBPrimitive directoryPath) { File.LastError = ""; Environment.ExpandEnvironmentVariables(directoryPath); EBPrimitive result; try { if (Directory.Exists(directoryPath)) { Dictionary<EBPrimitive, EBPrimitive> dictionary = new Dictionary<EBPrimitive, EBPrimitive>(); int num = 1; string[] directories = Directory.GetDirectories(directoryPath); for (int i = 0; i < directories.Length; i++) { string value = directories[i]; dictionary[num] = value; num++; } result = EBPrimitive.ConvertFromMap(dictionary); } else { File.LastError = "Directory Path does not exist."; result = "FAILED"; } } catch (Exception ex) { File.LastError = ex.Message; result = "FAILED"; } return result; } public static EBPrimitive GetTemporaryFilePath() { return Path.GetTempFileName(); } public static EBPrimitive GetSettingsFilePath() { string entryAssemblyPath = SmallBasicApplication.GetEntryAssemblyPath(); return Path.ChangeExtension(entryAssemblyPath, ".settings"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class FindTests { private const string LeftToRightMark = "\u200E"; private static void RunTest(Action<X509Certificate2Collection> test) { RunTest((msCer, pfxCer, col1) => test(col1)); } private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer }); test(msCer, pfxCer, col1); } } private static void RunExceptionTest<TException>(X509FindType findType, object findValue) where TException : Exception { RunTest( (msCer, pfxCer, col1) => { Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false)); }); } private static void RunZeroMatchTest(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(msCer, col1, findType, findValue); }); } private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(pfxCer, col1, findType, findValue); }); } private static void EvaluateSingleMatch( X509Certificate2 expected, X509Certificate2Collection col1, X509FindType findType, object findValue) { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); byte[] serialNumber; using (X509Certificate2 match = col2[0]) { Assert.Equal(expected, match); Assert.NotSame(expected, match); // FriendlyName is Windows-only. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Verify that the find result and original are linked, not just equal. match.FriendlyName = "HAHA"; Assert.Equal("HAHA", expected.FriendlyName); } serialNumber = match.GetSerialNumber(); } // Check that disposing match didn't dispose expected Assert.Equal(serialNumber, expected.GetSerialNumber()); } } [Theory] [MemberData(nameof(GenerateInvalidInputs))] public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType) { object badValue; if (badValueType == typeof(object)) { badValue = new object(); } else if (badValueType == typeof(DateTime)) { badValue = DateTime.Now; } else if (badValueType == typeof(byte[])) { badValue = Array.Empty<byte>(); } else if (badValueType == typeof(string)) { badValue = "Hello, world"; } else { throw new InvalidOperationException("No creator exists for type " + badValueType); } RunExceptionTest<CryptographicException>(findType, badValue); } [Theory] [MemberData(nameof(GenerateInvalidOidInputs))] public static void FindWithBadOids(X509FindType findType, string badOid) { RunExceptionTest<ArgumentException>(findType, badOid); } [Fact] public static void FindByNullName() { RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null); } [Fact] public static void FindByInvalidThumbprint() { RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing"); } [Fact] public static void FindByInvalidThumbprint_RightLength() { RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff"); } [Fact] public static void FindByValidThumbprint() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, pfxCer.Thumbprint); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "31463 is not fixed in NetFX")] public static void FindByThumbprint_WithLrm() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, LeftToRightMark + pfxCer.Thumbprint); }); } [Theory] [InlineData(false)] [InlineData(true)] public static void FindByValidThumbprint_ValidOnly(bool validOnly) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { var col1 = new X509Certificate2Collection(msCer); X509Certificate2Collection col2 = col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly); using (new ImportedCollection(col2)) { // The certificate is expired. Unless we invent time travel // (or roll the computer clock back significantly), the validOnly // criteria should filter it out. // // This test runs both ways to make sure that the precondition of // "would match otherwise" is met (in the validOnly=false case it is // effectively the same as FindByValidThumbprint, but does less inspection) int expectedMatchCount = validOnly ? 0 : 1; Assert.Equal(expectedMatchCount, col2.Count); if (!validOnly) { // Double check that turning on validOnly doesn't prevent the cloning // behavior of Find. using (X509Certificate2 match = col2[0]) { Assert.Equal(msCer, match); Assert.NotSame(msCer, match); } } } } } [Fact] public static void FindByValidThumbprint_RootCert() { using (X509Store machineRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { machineRoot.Open(OpenFlags.ReadOnly); using (var watchedStoreCerts = new ImportedCollection(machineRoot.Certificates)) { X509Certificate2Collection storeCerts = watchedStoreCerts.Collection; X509Certificate2 rootCert = null; TimeSpan tolerance = TimeSpan.FromHours(12); // These APIs use local time, so use DateTime.Now, not DateTime.UtcNow. DateTime notBefore = DateTime.Now; DateTime notAfter = DateTime.Now.Subtract(tolerance); foreach (X509Certificate2 cert in storeCerts) { if (cert.NotBefore >= notBefore || cert.NotAfter <= notAfter) { // Not (safely) valid, skip. continue; } X509KeyUsageExtension keyUsageExtension = null; foreach (X509Extension extension in cert.Extensions) { keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { break; } } // Some tool is putting the com.apple.systemdefault utility cert in the // LM\Root store on OSX machines; but it gets rejected by OpenSSL as an // invalid root for not having the Certificate Signing key usage value. // // While the real problem seems to be with whatever tool is putting it // in the bundle; we can work around it here. const X509KeyUsageFlags RequiredFlags = X509KeyUsageFlags.KeyCertSign; // No key usage extension means "good for all usages" if (keyUsageExtension != null && (keyUsageExtension.KeyUsages & RequiredFlags) != RequiredFlags) { // Not a valid KeyUsage, skip. continue; } using (ChainHolder chainHolder = new ChainHolder()) { chainHolder.Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; if (!chainHolder.Chain.Build(cert)) { // Despite being not expired and having a valid KeyUsage, it's // not considered a valid root/chain. continue; } } rootCert = cert; break; } // Just in case someone has a system with no valid trusted root certs whatsoever. if (rootCert != null) { X509Certificate2Collection matches = storeCerts.Find(X509FindType.FindByThumbprint, rootCert.Thumbprint, true); using (new ImportedCollection(matches)) { // Improve the debuggability, since the root cert found on each // machine might be different if (matches.Count == 0) { Assert.True( false, $"Root certificate '{rootCert.Subject}' ({rootCert.NotBefore} - {rootCert.NotAfter}) is findable with thumbprint '{rootCert.Thumbprint}' and validOnly=true"); } Assert.NotSame(rootCert, matches[0]); Assert.Equal(rootCert, matches[0]); } } } } } [Theory] [InlineData("Nothing")] [InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] public static void TestSubjectName_NoMatch(string subjectQualifier) { RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("Microsoft Corporation")] [InlineData("MOPR")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] [InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")] public static void TestSubjectName_Match(string subjectQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("ou=mopr, o=microsoft corporation")] [InlineData("CN=Microsoft Corporation")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName) { RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Theory] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Fact] public static void TestIssuerName_NoMatch() { RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing"); } [Theory] [InlineData("Microsoft Code Signing PCA")] [InlineData("Microsoft Corporation")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")] [InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")] public static void TestIssuerName_Match(string issuerQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("CN=Microsoft Code Signing PCA")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName) { RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Theory] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Fact] public static void TestByTimeValid_Before() { RunTest( (msCer, pfxCer, col1) => { DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, earliest - TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_After() { RunTest( (msCer, pfxCer, col1) => { DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, latest + TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Between() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Match() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( msCer, col1, X509FindType.FindByTimeValid, msCer.NotBefore + TimeSpan.FromSeconds(1)); }); } [Fact] public static void TestFindByTimeNotYetValid_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the latest NotBefore, so one is valid, the other is not yet valid. DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeNotYetValid_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the latest NotBefore, both certificates are time-valid DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the earliest NotAfter, so one is valid, the other is no longer valid. DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the earliest NotAfter, so both certificates are valid DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestBySerialNumber_Decimal() { // Decimal string is an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "284069184166497622998429950103047369500"); } [Fact] public static void TestBySerialNumber_DecimalLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "000" + "284069184166497622998429950103047369500"); } [Theory] [InlineData("1137338006039264696476027508428304567989436592")] // Leading zeroes are fine/ignored [InlineData("0001137338006039264696476027508428304567989436592")] // Compat: Minus signs are ignored [InlineData("-1137338006039264696476027508428304567989436592")] public static void TestBySerialNumber_Decimal_CertB(string serialNumber) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber); } [Fact] public static void TestBySerialNumber_Hex() { // Hex string is also an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_HexIgnoreCase() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5b5bc1c458a558845bff51cb4dff31c"); } [Fact] public static void TestBySerialNumber_HexLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "0000" + "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_WithSpaces() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5 b5 bc 1c 45 8a 55 88 45 bf f5 1c b4 df f3 1c"); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "31463 is not fixed in NetFX")] public static void TestBySerialNumber_WithLRM() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, LeftToRightMark + "d5 b5 bc 1c 45 8a 55 88 45 bf f5 1c b4 df f3 1c"); } [Fact] public static void TestBySerialNumber_NoMatch() { RunZeroMatchTest( X509FindType.FindBySerialNumber, "23000000B011AF0A8BD03B9FDD0001000000B0"); } [Theory] [MemberData(nameof(GenerateWorkingFauxSerialNumbers))] public static void TestBySerialNumber_Match_NonDecimalInput(string input) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input); } [Fact] public static void TestByExtension_FriendlyName() { // Cannot just say "Enhanced Key Usage" here because the extension name is localized. // Instead, look it up via the OID. RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName); } [Fact] public static void TestByExtension_OidValue() { RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37"); } [Fact] // Compat: Non-ASCII digits don't throw, but don't match. public static void TestByExtension_OidValue_ArabicNumericChar() { // This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead // of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw // as an illegal OID value. RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37"); } [Fact] public static void TestByExtension_UnknownFriendlyName() { RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS"); } [Fact] public static void TestByExtension_NoMatch() { RunZeroMatchTest(X509FindType.FindByExtension, "2.9"); } [Fact] public static void TestBySubjectKeyIdentifier_UsingFallback() { RunSingleMatchTest_PfxCer( X509FindType.FindBySubjectKeyIdentifier, "B4D738B2D4978AFF290A0B02987BABD114FEE9C7"); } [Theory] [InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")] // Whitespace is allowed [InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Lots of kinds of whitespace (does not include \u000b or \u000c, because those // produce a build warning (which becomes an error): // EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character. [InlineData( "59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" + "80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" + "4\u20091\u200aF\u20282\u2029\u202f")] // Non-byte-aligned whitespace is allowed [InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")] // Non-symmetric whitespace is allowed [InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")] public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } // Should ignore Left-to-right mark \u200E [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "31463 is not fixed in NetFX")] [InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Compat: Lone trailing nybbles are ignored [InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] public static void TestBySubjectKeyIdentifier_ExtensionPresentWithLTM(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Theory] // Compat: Lone trailing nybbles are ignored [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] // Compat: A non-hex character as the high nybble makes that nybble be F [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")] // Compat: A non-hex character as the low nybble makes the whole byte FF. [InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")] public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch() { RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, ""); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch_RightLength() { RunZeroMatchTest( X509FindType.FindBySubjectKeyIdentifier, "5971A65A334DDA980780FF841EBE87F9723241F0"); } [Fact] public static void TestByApplicationPolicy_MatchAll() { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false); using (new ImportedCollection(results)) { Assert.Equal(2, results.Count); Assert.True(results.Contains(msCer)); Assert.True(results.Contains(pfxCer)); } }); } [Fact] public static void TestByApplicationPolicy_NoPolicyAlwaysMatches() { // PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.) RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2"); } [Fact] public static void TestByApplicationPolicy_NoMatch() { RunTest( (msCer, pfxCer, col1) => { // Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it. col1.Remove(pfxCer); X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } }); } [Fact] public static void TestByCertificatePolicies_MatchA() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.18.19"); } } [Fact] public static void TestByCertificatePolicies_MatchB() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.32.33"); } } [Fact] public static void TestByCertificatePolicies_NoMatch() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Fact] public static void TestByTemplate_MatchA() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "Hello"); } } [Fact] public static void TestByTemplate_MatchB() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "2.7.8.9"); } } [Fact] public static void TestByTemplate_NoMatch() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Theory] [InlineData((int)0x80)] [InlineData((uint)0x80)] [InlineData(X509KeyUsageFlags.DigitalSignature)] [InlineData("DigitalSignature")] [InlineData("digitalSignature")] public static void TestFindByKeyUsage_Match(object matchCriteria) { TestFindByKeyUsage(true, matchCriteria); } [Theory] [InlineData((int)0x20)] [InlineData((uint)0x20)] [InlineData(X509KeyUsageFlags.KeyEncipherment)] [InlineData("KeyEncipherment")] [InlineData("KEYEncipherment")] public static void TestFindByKeyUsage_NoMatch(object matchCriteria) { TestFindByKeyUsage(false, matchCriteria); } private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria) { using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate)) using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer"))) { var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, }; X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false); using (new ImportedCollection(results)) { // The two certificates with no KeyUsages extension will always match, // the real question is about the third. int matchCount = shouldMatch ? 3 : 2; Assert.Equal(matchCount, results.Count); if (shouldMatch) { bool found = false; foreach (X509Certificate2 cert in results) { if (keyUsages.Equals(cert)) { Assert.NotSame(cert, keyUsages); found = true; break; } } Assert.True(found, "Certificate with key usages was found in the collection"); } else { Assert.False( results.Contains(keyUsages), "KeyUsages certificate is not present in the collection"); } } } } public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers { get { const string seedDec = "1137338006039264696476027508428304567989436592"; string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" }; string gluedTogether = string.Join("", nonHexWords); string withSpaces = string.Join(" ", nonHexWords); yield return new object[] { gluedTogether + seedDec }; yield return new object[] { seedDec + gluedTogether }; yield return new object[] { withSpaces + seedDec }; yield return new object[] { seedDec + withSpaces }; StringBuilder builderDec = new StringBuilder(512); int offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; } builderDec.Append(nonHexWords[i]); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; builderDec.Length = 0; offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; builderDec.Append(' '); } builderDec.Append(nonHexWords[i]); builderDec.Append(' '); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; } } public static IEnumerable<object[]> GenerateInvalidOidInputs { get { X509FindType[] oidTypes = { X509FindType.FindByApplicationPolicy, }; string[] invalidOids = { "", "This Is Not An Oid", "1", "95.22", ".1", "1..1", "1.", "1.2.", }; List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length); for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++) { for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++) { combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] }); } } return combinations; } } public static IEnumerable<object[]> GenerateInvalidInputs { get { Type[] allTypes = { typeof(object), typeof(DateTime), typeof(byte[]), typeof(string), }; Tuple<X509FindType, Type>[] legalInputs = { Tuple.Create(X509FindType.FindByThumbprint, typeof(string)), Tuple.Create(X509FindType.FindBySubjectName, typeof(string)), Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)), Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)), Tuple.Create(X509FindType.FindByTemplateName, typeof(string)), Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)), Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)), Tuple.Create(X509FindType.FindByExtension, typeof(string)), // KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes. Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)), Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)), }; List<object[]> invalidCombinations = new List<object[]>(); for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++) { Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex]; for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) { Type t = allTypes[typeIndex]; if (t != tuple.Item2) { invalidCombinations.Add(new object[] { tuple.Item1, t }); } } } return invalidCombinations; } } } }
namespace Lex { /* * Class: Gen */ using System; using System.Text; using System.IO; using System.Collections; using BitSet; public class Gen { /* * Member Variables */ private StreamReader instream; /* Lex specification file. */ private StreamWriter outstream; /* Lexical analyzer source file. */ private Input ibuf; /* Input buffer class. */ private Hashtable tokens; /* Hashtable that maps characters to their corresponding lexical code for the internal lexical analyzer. */ private Spec spec; /* Spec class holds information about the generated lexer. */ private bool init_flag; /* Flag set to true only upon successful initialization. */ private MakeNfa makeNfa; /* NFA machine generator module. */ private Nfa2Dfa nfa2dfa; /* NFA to DFA machine (transition table) conversion module. */ private Minimize minimize; /* Transition table compressor. */ //private SimplifyNfa simplifyNfa; /* NFA simplifier using char classes */ private Emit emit; /* Output module that emits source code into the generated lexer file. */ private String usercode; /* temporary to hold the user supplied code */ /* * Constants */ private const bool ERROR = false; private const bool NOT_ERROR = true; private const int BUFFER_SIZE = 1024; /* * Constants: Token Types */ public const int EOS = 1; public const int ANY = 2; public const int AT_BOL = 3; public const int AT_EOL = 4; public const int CCL_END = 5; public const int CCL_START = 6; public const int CLOSE_CURLY = 7; public const int CLOSE_PAREN = 8; public const int CLOSURE = 9; public const int DASH = 10; public const int END_OF_INPUT = 11; public const int L = 12; public const int OPEN_CURLY = 13; public const int OPEN_PAREN = 14; public const int OPTIONAL = 15; public const int OR = 16; public const int PLUS_CLOSE = 17; /* * Function: LexGen */ public Gen(String filename) { /* Successful initialization flag. */ init_flag = false; /* Open input stream. */ instream = new StreamReader( new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, Lex.MAXBUF) ); if (instream == null) { Console.WriteLine("Error: Unable to open input file " + filename + "."); return; } int j = filename.LastIndexOf('\\'); if (j < 0) j = 0; else j++; String outfile = filename.Substring(j,filename.Length-j).Replace('.','_') + ".cs"; Console.WriteLine("Creating output file ["+outfile+"]"); /* Open output stream. */ outstream = new StreamWriter( new FileStream(outfile, FileMode.Create, FileAccess.Write, FileShare.Write, 8192) ); if (outstream == null) { Console.WriteLine("Error: Unable to open output file " + filename + ".java."); return; } /* Create input buffer class. */ ibuf = new Input(instream); /* Initialize character hash table. */ tokens = new Hashtable(); tokens['$'] = AT_EOL; tokens['('] = OPEN_PAREN; tokens[')'] = CLOSE_PAREN; tokens['*'] = CLOSURE; tokens['+'] = PLUS_CLOSE; tokens['-'] = DASH; tokens['.'] = ANY; tokens['?'] = OPTIONAL; tokens['['] = CCL_START; tokens[']'] = CCL_END; tokens['^'] = AT_BOL; tokens['{'] = OPEN_CURLY; tokens['|'] = OR; tokens['}'] = CLOSE_CURLY; /* Initialize spec structure. */ // spec = new Spec(this); spec = new Spec(); /* Nfa to dfa converter. */ nfa2dfa = new Nfa2Dfa(); minimize = new Minimize(); makeNfa = new MakeNfa(); // simplifyNfa = new SimplifyNfa(); emit = new Emit(); /* Successful initialization flag. */ init_flag = true; } /* * Function: generate * Description: */ public void generate() { if (!init_flag) { Error.parse_error(Error.E_INIT,0); } #if DEBUG Utility.assert(this != null); Utility.assert(outstream != null); Utility.assert(ibuf != null); Utility.assert(tokens != null); Utility.assert(spec != null); Utility.assert(init_flag); #endif if (spec.verbose) { Console.WriteLine("Processing first section -- user code."); } userCode(); if (ibuf.eof_reached) { Error.parse_error(Error.E_EOF,ibuf.line_number); } if (spec.verbose) { Console.WriteLine("Processing second section -- Lex declarations."); } userDeclare(); if (ibuf.eof_reached) { Error.parse_error(Error.E_EOF,ibuf.line_number); } if (spec.verbose) { Console.WriteLine("Processing third section -- lexical rules."); } userRules(); #if DO_DEBUG Console.WriteLine("Printing DO_DEBUG header"); print_header(); #endif if (spec.verbose) { Console.WriteLine("Outputting lexical analyzer code."); } outstream.Write("namespace "+spec.namespace_name+"\n{\n"); outstream.Write(usercode); outstream.Write("/* test */\n"); emit.Write(spec,outstream); outstream.Write("\n}\n"); #if OLD_DUMP_DEBUG details(); #endif outstream.Close(); } /* * Function: userCode * Description: Process first section of specification, * echoing it into output file. */ private void userCode() { StringBuilder sb = new StringBuilder(); if (!init_flag) { Error.parse_error(Error.E_INIT,0); } #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif if (ibuf.eof_reached) { Error.parse_error(Error.E_EOF,0); } while (true) { if (ibuf.GetLine()) { /* Eof reached. */ Error.parse_error(Error.E_EOF,0); } if (ibuf.line_read >= 2 && ibuf.line[0] == '%' && ibuf.line[1] == '%') { usercode = sb.ToString(); /* Discard remainder of line. */ ibuf.line_index = ibuf.line_read; return; } sb.Append(new String(ibuf.line,0,ibuf.line_read)); } } /* * Function: getName */ private String getName() { /* Skip white space. */ while (ibuf.line_index < ibuf.line_read && Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; } /* No name? */ if (ibuf.line_index >= ibuf.line_read) { Error.parse_error(Error.E_DIRECT,0); } /* Determine length. */ int elem = ibuf.line_index; while (elem < ibuf.line_read && !Utility.IsNewline(ibuf.line[elem])) elem++; /* Allocate non-terminated buffer of exact length. */ StringBuilder sb = new StringBuilder(elem - ibuf.line_index); /* Copy. */ elem = 0; while (ibuf.line_index < ibuf.line_read && !Utility.IsNewline(ibuf.line[ibuf.line_index])) { sb.Append(ibuf.line[ibuf.line_index]); ibuf.line_index++; } return sb.ToString(); } private const int CLASS_CODE = 0; private const int INIT_CODE = 1; private const int EOF_CODE = 2; private const int EOF_VALUE_CODE = 3; /* * Function: packCode * Description: */ //private String packCode(String start_dir, String end_dir, // String prev_code, int prev_read, int specified) private String packCode(String st_dir, String end_dir, String prev, int code) { #if DEBUG Utility.assert(INIT_CODE == code || CLASS_CODE == code || EOF_CODE == code || EOF_VALUE_CODE == code ); #endif if (Utility.Compare(ibuf.line, st_dir) != 0) Error.parse_error(Error.E_INTERNAL,0); /* * build up the text to be stored in sb */ StringBuilder sb; if (prev != null) sb = new StringBuilder(prev, prev.Length*2); // use any previous text else sb = new StringBuilder(Lex.MAXSTR); ibuf.line_index = st_dir.Length; while (true) { while (ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) Error.parse_error(Error.E_EOF,ibuf.line_number); if (Utility.Compare(ibuf.line, end_dir) == 0) { ibuf.line_index = end_dir.Length - 1; return sb.ToString(); } } while (ibuf.line_index < ibuf.line_read) { sb.Append(ibuf.line[ibuf.line_index]); ibuf.line_index++; } } } /* * Member Variables: Lex directives. */ private String state_dir = "%state"; private String char_dir = "%char"; private String line_dir = "%line"; private String class_dir = "%class"; private String implements_dir = "%implements"; private String function_dir = "%function"; private String type_dir = "%type"; private String integer_dir = "%integer"; private String intwrap_dir = "%intwrap"; private String full_dir = "%full"; private String unicode_dir = "%unicode"; private String ignorecase_dir = "%ignorecase"; private String init_code_dir = "%init{"; private String init_code_end_dir = "%init}"; private String eof_code_dir = "%eof{"; private String eof_code_end_dir = "%eof}"; private String eof_value_code_dir = "%eofval{"; private String eof_value_code_end_dir = "%eofval}"; private String class_code_dir = "%{"; private String class_code_end_dir = "%}"; private String yyeof_dir = "%yyeof"; private String public_dir = "%public"; private String namespace_dir = "%namespace"; /* * Function: userDeclare * Description: */ private void userDeclare() { #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif if (ibuf.eof_reached) { /* End-of-file. */ Error.parse_error(Error.E_EOF,ibuf.line_number); } while (!ibuf.GetLine()) { /* Look for double percent. */ if (ibuf.line_read >= 2 && '%' == ibuf.line[0] && '%' == ibuf.line[1]) { /* Mess around with line. */ for (int elem = 0; elem < ibuf.line.Length - 2; ++elem) ibuf.line[elem] = ibuf.line[elem + 2]; ibuf.line_read = ibuf.line_read - 2; ibuf.pushback_line = true; /* Check for and discard empty line. */ if (ibuf.line_read == 0 || '\r' == ibuf.line[0] || '\n' == ibuf.line[0]) { ibuf.pushback_line = false; } return; } if (ibuf.line_read == 0) continue; if (ibuf.line[0] == '%') { /* Special lex declarations. */ if (1 >= ibuf.line_read) { Error.parse_error(Error.E_DIRECT, ibuf.line_number); continue; } switch (ibuf.line[1]) { case '{': if (Utility.Compare(ibuf.line, class_code_dir) == 0) { spec.class_code = packCode(class_code_dir, class_code_end_dir, spec.class_code, CLASS_CODE); break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'c': if (Utility.Compare(ibuf.line, char_dir) == 0) { /* Set line counting to ON. */ ibuf.line_index = char_dir.Length; spec.count_chars = true; break; } if (Utility.Compare(ibuf.line, class_dir) == 0) { ibuf.line_index = class_dir.Length; spec.class_name = getName(); break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'e': if (Utility.Compare(ibuf.line, eof_code_dir) == 0) { spec.eof_code = packCode(eof_code_dir, eof_code_end_dir, spec.eof_code, EOF_CODE); break; } if (Utility.Compare(ibuf.line, eof_value_code_dir) == 0) { spec.eof_value_code = packCode(eof_value_code_dir, eof_value_code_end_dir, spec.eof_value_code, EOF_VALUE_CODE); break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'f': if (Utility.Compare(ibuf.line, function_dir) == 0) { /* Set line counting to ON. */ ibuf.line_index = function_dir.Length; spec.function_name = getName(); break; } if (Utility.Compare(ibuf.line, full_dir) == 0) { ibuf.line_index = full_dir.Length; spec.dtrans_ncols = Utility.MAX_EIGHT_BIT + 1; break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'i': if (Utility.Compare(ibuf.line, integer_dir) == 0) { /* Set line counting to ON. */ ibuf.line_index = integer_dir.Length; spec.integer_type = true; break; } if (Utility.Compare(ibuf.line, intwrap_dir) == 0) { /* Set line counting to ON. */ ibuf.line_index = integer_dir.Length; spec.intwrap_type = true; break; } if (Utility.Compare(ibuf.line, init_code_dir) == 0) { spec.init_code = packCode(init_code_dir, init_code_end_dir, spec.init_code, INIT_CODE); break; } if (Utility.Compare(ibuf.line, implements_dir) == 0) { ibuf.line_index = implements_dir.Length; spec.implements_name = getName(); break; } if (Utility.Compare(ibuf.line, ignorecase_dir) == 0) { /* Set ignorecase to ON. */ ibuf.line_index = ignorecase_dir.Length; spec.ignorecase = true; break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'l': if (Utility.Compare(ibuf.line, line_dir) == 0) { /* Set line counting to ON. */ ibuf.line_index = line_dir.Length; spec.count_lines = true; break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'p': if (Utility.Compare(ibuf.line, public_dir) == 0) { /* Set public flag. */ ibuf.line_index = public_dir.Length; spec.lex_public = true; break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 's': if (Utility.Compare(ibuf.line, state_dir) == 0) { /* Recognize state list. */ ibuf.line_index = state_dir.Length; saveStates(); break; } /* Undefined directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 't': if (Utility.Compare(ibuf.line, type_dir) == 0) { ibuf.line_index = type_dir.Length; spec.type_name = getName(); break; } /* Undefined directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'u': if (Utility.Compare(ibuf.line, unicode_dir) == 0) { ibuf.line_index = unicode_dir.Length; /* UNDONE: What to do here? */ break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'y': if (Utility.Compare(ibuf.line, yyeof_dir) == 0) { ibuf.line_index = yyeof_dir.Length; spec.yyeof = true; break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; case 'n': if (Utility.Compare(ibuf.line, namespace_dir) == 0) { ibuf.line_index = namespace_dir.Length; spec.namespace_name = getName(); break; } /* Bad directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; default: /* Undefined directive. */ Error.parse_error(Error.E_DIRECT, ibuf.line_number); break; } } else { /* Regular expression macro. */ ibuf.line_index = 0; saveMacro(); } #if OLD_DEBUG Console.WriteLine("Line number " + ibuf.line_number + ":"); Console.Write(new String(ibuf.line, 0,ibuf.line_read)); #endif } } /* * Function: userRules * Description: Processes third section of Lex * specification and creates minimized transition table. */ private void userRules() { if (false == init_flag) { Error.parse_error(Error.E_INIT,0); } #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif /* UNDONE: Need to handle states preceding rules. */ if (spec.verbose) { Console.WriteLine("Creating NFA machine representation."); } MakeNfa.Allocate_BOL_EOF(spec); MakeNfa.CreateMachine(this, spec, ibuf); SimplifyNfa.simplify(spec); #if DUMMY print_nfa(); #endif #if DEBUG Utility.assert(END_OF_INPUT == spec.current_token); #endif if (spec.verbose) { Console.WriteLine("Creating DFA transition table."); } Nfa2Dfa.MakeDFA(spec); #if FOODEBUG Console.WriteLine("Printing FOODEBUG header"); print_header(); #endif if (spec.verbose) { Console.WriteLine("Minimizing DFA transition table."); } minimize.min_dfa(spec); } /* * Function: printccl * Description: Debuggng routine that outputs readable form * of character class. */ private void printccl(CharSet cset) { int i; Console.Write(" ["); for (i = 0; i < spec.dtrans_ncols; ++i) { if (cset.contains(i)) { Console.Write(interp_int(i)); } } Console.Write(']'); } /* * Function: plab * Description: */ private String plab(Nfa state) { if (null == state) { return "--"; } int index = spec.nfa_states.IndexOf(state, 0, spec.nfa_states.Count); return index.ToString(); } /* * Function: interp_int * Description: */ private String interp_int(int i) { switch (i) { case (int) '\b': return "\\b"; case (int) '\t': return "\\t"; case (int) '\n': return "\\n"; case (int) '\f': return "\\f"; case (int) '\r': return "\\r"; case (int) ' ': return "\\ "; default: { return Char.ToString((char) i); } } } /* * Function: print_nfa * Description: */ public void print_nfa() { int elem; Nfa nfa; int j; int vsize; Console.WriteLine("--------------------- NFA -----------------------"); for (elem = 0; elem < spec.nfa_states.Count; elem++) { nfa = (Nfa) spec.nfa_states[elem]; Console.Write("Nfa state " + plab(nfa) + ": "); if (null == nfa.GetNext()) { Console.Write("(TERMINAL)"); } else { Console.Write("--> " + plab(nfa.GetNext())); Console.Write("--> " + plab(nfa.GetSib())); switch (nfa.GetEdge()) { case Nfa.CCL: printccl(nfa.GetCharSet()); break; case Nfa.EPSILON: Console.Write(" EPSILON "); break; default: Console.Write(" " + interp_int(nfa.GetEdge())); break; } } if (0 == elem) { Console.Write(" (START STATE)"); } if (null != nfa.GetAccept()) { Console.Write(" accepting " + ((0 != (nfa.GetAnchor() & Spec.START)) ? "^" : "") + "<" + nfa.GetAccept().action + ">" + ((0 != (nfa.GetAnchor() & Spec.END)) ? "$" : "")); } Console.WriteLine(""); } foreach (string state in spec.states.Keys) { int index = (int) spec.states[state]; #if DEBUG Utility.assert(null != state); #endif Console.WriteLine("State \"" + state + "\" has identifying index " + index + "."); Console.Write("\tStart states of matching rules: "); vsize = spec.state_rules[index].Count; for (j = 0; j < vsize; ++j) { ArrayList a = spec.state_rules[index]; #if DEBUG Utility.assert(null != a); #endif object o = a[j]; #if DEBUG Utility.assert(null != o); #endif nfa = (Nfa) o; Console.Write(spec.nfa_states.IndexOf(nfa) + " "); } Console.WriteLine(""); } Console.WriteLine("-------------------- NFA ----------------------"); } /* * Function: getStates * Description: Parses the state area of a rule, * from the beginning of a line. * < state1, state2 ... > regular_expression { action } * Returns null on only EOF. Returns all_states, * initialied properly to correspond to all states, * if no states are found. * Special Notes: This function treats commas as optional * and permits states to be spread over multiple lines. */ private BitSet all_states = null; public BitSet GetStates() { int start_state; int count_state; BitSet states; String name; int index; #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif states = null; /* Skip white space. */ while (Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; while (ibuf.line_index >= ibuf.line_read) { /* Must just be an empty line. */ if (ibuf.GetLine()) { /* EOF found. */ return null; } } } /* Look for states. */ if ('<' == ibuf.line[ibuf.line_index]) { ibuf.line_index++; states = new BitSet(); // create new BitSet /* Parse states. */ while (true) { /* We may have reached the end of the line. */ while (ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) { /* EOF found. */ Error.parse_error(Error.E_EOF,ibuf.line_number); return states; } } while (true) { /* Skip white space. */ while (Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; while (ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) { /* EOF found. */ Error.parse_error(Error.E_EOF,ibuf.line_number); return states; } } } if (',' != ibuf.line[ibuf.line_index]) { break; } ibuf.line_index++; } if ('>' == ibuf.line[ibuf.line_index]) { ibuf.line_index++; if (ibuf.line_index < ibuf.line_read) { advance_stop = true; } return states; } /* Read in state name. */ start_state = ibuf.line_index; while (false == Utility.IsSpace(ibuf.line[ibuf.line_index]) && ',' != ibuf.line[ibuf.line_index] && '>' != ibuf.line[ibuf.line_index]) { ibuf.line_index++; if (ibuf.line_index >= ibuf.line_read) { /* End of line means end of state name. */ break; } } count_state = ibuf.line_index - start_state; /* Save name after checking definition. */ name = new String(ibuf.line, start_state, count_state); Object o = spec.states[name]; if (o == null) { /* Uninitialized state. */ Console.WriteLine("Uninitialized State Name: [" + name +"]"); Error.parse_error(Error.E_STATE,ibuf.line_number); } index = (int) o; states.Set(index, true); } } if (null == all_states) { all_states = new BitSet(states.Count, true); } if (ibuf.line_index < ibuf.line_read) { advance_stop = true; } return all_states; } /* * Function: expandMacro * Description: Returns false on error, true otherwise. */ private bool expandMacro() { int elem; int start_macro; int end_macro; int start_name; int count_name; String def; int def_elem; String name; char[] replace; int rep_elem; #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif /* Check for macro. */ if ('{' != ibuf.line[ibuf.line_index]) { Error.parse_error(Error.E_INTERNAL,ibuf.line_number); return ERROR; } start_macro = ibuf.line_index; elem = ibuf.line_index + 1; if (elem >= ibuf.line_read) { Error.impos("Unfinished macro name"); return ERROR; } /* Get macro name. */ start_name = elem; while ('}' != ibuf.line[elem]) { ++elem; if (elem >= ibuf.line_read) { Error.impos("Unfinished macro name at line " + ibuf.line_number); return ERROR; } } count_name = elem - start_name; end_macro = elem; /* Check macro name. */ if (0 == count_name) { Error.impos("Nonexistent macro name"); return ERROR; } /* Debug checks. */ #if DEBUG Utility.assert(0 < count_name); #endif /* Retrieve macro definition. */ name = new String(ibuf.line,start_name,count_name); def = (String) spec.macros[name]; if (null == def) { /*Error.impos("Undefined macro \"" + name + "\".");*/ Console.WriteLine("Error: Undefined macro \"" + name + "\"."); Error.parse_error(Error.E_NOMAC, ibuf.line_number); return ERROR; } #if OLD_DUMP_DEBUG Console.WriteLine("expanded escape: \"" + def + "\""); #endif /* Replace macro in new buffer, beginning by copying first part of line buffer. */ replace = new char[ibuf.line.Length]; for (rep_elem = 0; rep_elem < start_macro; ++rep_elem) { replace[rep_elem] = ibuf.line[rep_elem]; #if DEBUG Utility.assert(rep_elem < replace.Length); #endif } /* Copy macro definition. */ if (rep_elem >= replace.Length) { replace = Utility.doubleSize(replace); } for (def_elem = 0; def_elem < def.Length; ++def_elem) { replace[rep_elem] = def[def_elem]; ++rep_elem; if (rep_elem >= replace.Length) { replace = Utility.doubleSize(replace); } } /* Copy last part of line. */ if (rep_elem >= replace.Length) { replace = Utility.doubleSize(replace); } for (elem = end_macro + 1; elem < ibuf.line_read; ++elem) { replace[rep_elem] = ibuf.line[elem]; ++rep_elem; if (rep_elem >= replace.Length) { replace = Utility.doubleSize(replace); } } /* Replace buffer. */ ibuf.line = replace; ibuf.line_read = rep_elem; #if OLD_DEBUG Console.WriteLine(new String(ibuf.line,0,ibuf.line_read)); #endif return NOT_ERROR; } /* * Function: saveMacro * Description: Saves macro definition of form: * macro_name = macro_definition */ private void saveMacro() { int elem; int start_name; int count_name; int start_def; int count_def; bool saw_escape; bool in_quote; bool in_ccl; #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif /* Macro declarations are of the following form: macro_name macro_definition */ elem = 0; /* Skip white space preceding macro name. */ while (Utility.IsSpace(ibuf.line[elem])) { ++elem; if (elem >= ibuf.line_read) { /* End of line has been reached, and line was found to be empty. */ return; } } /* Read macro name. */ start_name = elem; while (false == Utility.IsSpace(ibuf.line[elem]) && '=' != ibuf.line[elem]) { ++elem; if (elem >= ibuf.line_read) { /* Macro name but no associated definition. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } } count_name = elem - start_name; /* Check macro name. */ if (0 == count_name) { /* Nonexistent macro name. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } /* Skip white space between name and definition. */ while (Utility.IsSpace(ibuf.line[elem])) { ++elem; if (elem >= ibuf.line_read) { /* Macro name but no associated definition. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } } if ('=' == ibuf.line[elem]) { ++elem; if (elem >= ibuf.line_read) { /* Macro name but no associated definition. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } } /* Skip white space between name and definition. */ while (Utility.IsSpace(ibuf.line[elem])) { ++elem; if (elem >= ibuf.line_read) { /* Macro name but no associated definition. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } } /* Read macro definition. */ start_def = elem; in_quote = false; in_ccl = false; saw_escape = false; while (false == Utility.IsSpace(ibuf.line[elem]) || true == in_quote || true == in_ccl || true == saw_escape) { if ('\"' == ibuf.line[elem] && false == saw_escape) { in_quote = !in_quote; } if ('\\' == ibuf.line[elem] && false == saw_escape) { saw_escape = true; } else { saw_escape = false; } if (false == saw_escape && false == in_quote) { if ('[' == ibuf.line[elem] && false == in_ccl) in_ccl = true; if (']' == ibuf.line[elem] && true == in_ccl) in_ccl = false; } ++elem; if (elem >= ibuf.line_read) { /* End of line. */ break; } } count_def = elem - start_def; /* Check macro definition. */ if (count_def == 0) { /* Nonexistent macro name. */ Error.parse_error(Error.E_MACDEF,ibuf.line_number); } /* Debug checks. */ #if DEBUG Utility.assert(0 < count_def); Utility.assert(0 < count_name); Utility.assert(null != spec.macros); #endif String macro_name = new String(ibuf.line,start_name,count_name); String macro_def = new String(ibuf.line,start_def,count_def); #if OLD_DEBUG Console.WriteLine("macro name \"" + macro_name + "\"."); Console.WriteLine("macro definition \"" + macro_def + "\"."); #endif /* Add macro name and definition to table. */ spec.macros.Add(macro_name, macro_def); } /* * Function: saveStates * Description: Takes state declaration and makes entries * for them in state hashtable in CSpec structure. * State declaration should be of the form: * %state name0[, name1, name2 ...] * (But commas are actually optional as long as there is * white space in between them.) */ private void saveStates() { int start_state; int count_state; #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif /* EOF found? */ if (ibuf.eof_reached) return; /* Debug checks. */ #if DEBUG Utility.assert('%' == ibuf.line[0]); Utility.assert('s' == ibuf.line[1]); Utility.assert(ibuf.line_index <= ibuf.line_read); Utility.assert(0 <= ibuf.line_index); Utility.assert(0 <= ibuf.line_read); #endif /* Blank line? No states? */ if (ibuf.line_index >= ibuf.line_read) return; while (ibuf.line_index < ibuf.line_read) { #if OLD_DEBUG Console.WriteLine("line read " + ibuf.line_read + "\tline index = " + ibuf.line_index); #endif /* Skip white space. */ while (Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; if (ibuf.line_index >= ibuf.line_read) { /* No more states to be found. */ return; } } /* Look for state name. */ start_state = ibuf.line_index; while (!Utility.IsSpace(ibuf.line[ibuf.line_index]) && ibuf.line[ibuf.line_index] != ',') { ibuf.line_index++; if (ibuf.line_index >= ibuf.line_read) { /* End of line and end of state name. */ break; } } count_state = ibuf.line_index - start_state; #if OLD_DEBUG Console.WriteLine("State name \"" + new String(ibuf.line,start_state,count_state) + "\"."); Console.WriteLine("Integer index \"" + spec.states.Count + "\"."); #endif /* Enter new state name, along with unique index. */ spec.states[new String(ibuf.line,start_state,count_state)] = spec.states.Count; /* Skip comma. */ if (',' == ibuf.line[ibuf.line_index]) { ibuf.line_index++; if (ibuf.line_index >= ibuf.line_read) { /* End of line. */ return; } } } } /* * Function: expandEscape * Description: Takes escape sequence and returns * corresponding character code. */ private char expandEscape() { char r; /* Debug checks. */ #if DEBUG Utility.assert(ibuf.line_index < ibuf.line_read); Utility.assert(0 < ibuf.line_read); Utility.assert(0 <= ibuf.line_index); #endif if (ibuf.line[ibuf.line_index] != '\\') { ibuf.line_index++; return ibuf.line[ibuf.line_index - 1]; } else { ibuf.line_index++; switch (Utility.toupper(ibuf.line[ibuf.line_index])) { case 'B': ibuf.line_index++; return '\b'; case 'T': ibuf.line_index++; return '\t'; case 'N': ibuf.line_index++; return '\n'; case 'F': ibuf.line_index++; return '\f'; case 'R': ibuf.line_index++; return '\r'; case '^': ibuf.line_index++; r = (char) (Utility.toupper(ibuf.line[ibuf.line_index]) - '@'); ibuf.line_index++; return r; case 'X': ibuf.line_index++; r = (char) 0; if (Utility.ishexdigit(ibuf.line[ibuf.line_index])) { r = Utility.hex2bin(ibuf.line[ibuf.line_index]); ibuf.line_index++; } if (Utility.ishexdigit(ibuf.line[ibuf.line_index])) { r = (char) (r << 4); r = (char) (r | Utility.hex2bin(ibuf.line[ibuf.line_index])); ibuf.line_index++; } if (Utility.ishexdigit(ibuf.line[ibuf.line_index])) { r = (char) (r << 4); r = (char) (r | Utility.hex2bin(ibuf.line[ibuf.line_index])); ibuf.line_index++; } return r; default: if (!Utility.isoctdigit(ibuf.line[ibuf.line_index])) { r = ibuf.line[ibuf.line_index]; ibuf.line_index++; } else { r = Utility.oct2bin(ibuf.line[ibuf.line_index]); ibuf.line_index++; if (Utility.isoctdigit(ibuf.line[ibuf.line_index])) { r = (char) (r << 3); r = (char) (r | Utility.oct2bin(ibuf.line[ibuf.line_index])); ibuf.line_index++; } if (Utility.isoctdigit(ibuf.line[ibuf.line_index])) { r = (char) (r << 3); r = (char) (r | Utility.oct2bin(ibuf.line[ibuf.line_index])); ibuf.line_index++; } } return r; } } } /* * Function: packAccept * Description: Packages and returns CAccept * for action next in input stream. */ public Accept packAccept() { Accept accept; int brackets; bool inquotes; bool instarcomment; bool inslashcomment; bool escaped; bool slashed; StringBuilder action = new StringBuilder(BUFFER_SIZE); #if DEBUG Utility.assert(null != this); Utility.assert(null != outstream); Utility.assert(null != ibuf); Utility.assert(null != tokens); Utility.assert(null != spec); #endif /* Get a new line, if needed. */ while (ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) { Error.parse_error(Error.E_EOF,ibuf.line_number); return null; } } /* Look for beginning of action */ while (Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; /* Get a new line, if needed. */ while (ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) { Error.parse_error(Error.E_EOF,ibuf.line_number); return null; } } } /* Look for brackets. */ if ('{' != ibuf.line[ibuf.line_index]) { Error.parse_error(Error.E_BRACE,ibuf.line_number); } /* Copy new line into action buffer. */ brackets = 0; inquotes = inslashcomment = instarcomment = false; escaped = slashed = false; while (true) { action.Append(ibuf.line[ibuf.line_index]); /* Look for quotes. */ if (inquotes && escaped) escaped=false; // only protects one char, but this is enough. else if (inquotes && '\\' == ibuf.line[ibuf.line_index]) escaped=true; else if ('\"' == ibuf.line[ibuf.line_index]) inquotes=!inquotes; // unescaped quote. /* Look for comments. */ if (instarcomment) { // inside "/*" comment; look for "*/" if (slashed && '/' == ibuf.line[ibuf.line_index]) instarcomment = slashed = false; else // note that inside a star comment, // slashed means starred slashed = ('*' == ibuf.line[ibuf.line_index]); } else if (!inslashcomment) { // not in comment, look for /* or // inslashcomment = (slashed && '/' == ibuf.line[ibuf.line_index]); instarcomment = (slashed && '*' == ibuf.line[ibuf.line_index]); slashed = ('/' == ibuf.line[ibuf.line_index]); } /* Look for brackets. */ if (!inquotes && !instarcomment && !inslashcomment) { if ('{' == ibuf.line[ibuf.line_index]) { ++brackets; } else if ('}' == ibuf.line[ibuf.line_index]) { --brackets; if (0 == brackets) { ibuf.line_index++; break; } } } ibuf.line_index++; /* Get a new line, if needed. */ while (ibuf.line_index >= ibuf.line_read) { inslashcomment = slashed = false; if (inquotes) { // non-fatal Error.parse_error(Error.E_NEWLINE,ibuf.line_number); inquotes=false; } if (ibuf.GetLine()) { Error.parse_error(Error.E_SYNTAX,ibuf.line_number); return null; } } } accept = new Accept(action.ToString(), ibuf.line_number); #if DEBUG Utility.assert(null != accept); #endif #if DESCENT_DEBUG Console.Write("\nAccepting action:"); Console.WriteLine(accept.action); #endif return accept; } /* * Function: advance * Description: Returns code for next token. */ private bool advance_stop = false; public int Advance() { bool saw_escape = false; if (ibuf.eof_reached) { /* EOF has already been reached, so return appropriate code. */ spec.current_token = END_OF_INPUT; spec.lexeme = '\0'; return spec.current_token; } /* End of previous regular expression? Refill line buffer? */ if (EOS == spec.current_token || ibuf.line_index >= ibuf.line_read) { if (spec.in_quote) { Error.parse_error(Error.E_SYNTAX,ibuf.line_number); } while (true) { if (!advance_stop || ibuf.line_index >= ibuf.line_read) { if (ibuf.GetLine()) { /* EOF has already been reached, so return appropriate code. */ spec.current_token = END_OF_INPUT; spec.lexeme = '\0'; return spec.current_token; } ibuf.line_index = 0; } else { advance_stop = false; } while (ibuf.line_index < ibuf.line_read && true == Utility.IsSpace(ibuf.line[ibuf.line_index])) { ibuf.line_index++; } if (ibuf.line_index < ibuf.line_read) { break; } } } #if DEBUG Utility.assert(ibuf.line_index <= ibuf.line_read); #endif while (true) { if (!spec.in_quote && '{' == ibuf.line[ibuf.line_index]) { if (!expandMacro()) { break; } if (ibuf.line_index >= ibuf.line_read) { spec.current_token = EOS; spec.lexeme = '\0'; return spec.current_token; } } else if ('\"' == ibuf.line[ibuf.line_index]) { spec.in_quote = !spec.in_quote; ibuf.line_index++; if (ibuf.line_index >= ibuf.line_read) { spec.current_token = EOS; spec.lexeme = '\0'; return spec.current_token; } } else { break; } } if (ibuf.line_index > ibuf.line_read) { Console.WriteLine("ibuf.line_index = " + ibuf.line_index); Console.WriteLine("ibuf.line_read = " + ibuf.line_read); Utility.assert(ibuf.line_index <= ibuf.line_read); } /* Look for backslash, and corresponding escape sequence. */ if ('\\' == ibuf.line[ibuf.line_index]) { saw_escape = true; } else { saw_escape = false; } if (!spec.in_quote) { if (!spec.in_ccl && Utility.IsSpace(ibuf.line[ibuf.line_index])) { /* White space means the end of the current regular expression. */ spec.current_token = EOS; spec.lexeme = '\0'; return spec.current_token; } /* Process escape sequence, if needed. */ if (saw_escape) { spec.lexeme = expandEscape(); } else { spec.lexeme = ibuf.line[ibuf.line_index]; ibuf.line_index++; } } else { if (saw_escape && (ibuf.line_index + 1) < ibuf.line_read && '\"' == ibuf.line[ibuf.line_index + 1]) { spec.lexeme = '\"'; ibuf.line_index = ibuf.line_index + 2; } else { spec.lexeme = ibuf.line[ibuf.line_index]; ibuf.line_index++; } } if (spec.in_quote || saw_escape) { spec.current_token = L; } else { Object code = tokens[spec.lexeme]; if (code == null) { spec.current_token = L; } else { spec.current_token = (int) code; } } if (CCL_START == spec.current_token) spec.in_ccl = true; if (CCL_END == spec.current_token) spec.in_ccl = false; #if FOODEBUG DumpLexeme(spec.lexeme, spec.current_token, ibuf.line_index); #endif return spec.current_token; } #if FOODEBUG void DumpLexeme(char lexeme, int token, int index) { StringBuilder sb = new StringBuilder(); sb.Append("Lexeme: '"); if (lexeme < ' ') { lexeme += (char) 64; sb.Append("^"); } sb.Append(lexeme); sb.Append("'\tToken: "); sb.Append(token); sb.Append("\tIndex: "); sb.Append(index); Console.WriteLine(sb.ToString()); } #endif /* * Function: details * Description: High level debugging routine. */ private void details() { Console.WriteLine("\n\t** Macros **"); foreach (string name in spec.macros.Keys) { #if DEBUG Utility.assert(null != name); #endif string def = (String) spec.macros[name]; #if DEBUG Utility.assert(null != def); #endif Console.WriteLine("Macro name \"" + name + "\" has definition \"" + def + "\"."); } Console.WriteLine("\n\t** States **"); foreach (string state in spec.states.Keys) { int index = (int) spec.states[state]; #if DEBUG Utility.assert(null != state); #endif Console.WriteLine("State \"" + state + "\" has identifying index " + index + "."); } Console.WriteLine("\n\t** Character Counting **"); if (!spec.count_chars) Console.WriteLine("Character counting is off."); else { #if DEBUG Utility.assert(spec.count_lines); #endif Console.WriteLine("Character counting is on."); } Console.WriteLine("\n\t** Line Counting **"); if (!spec.count_lines) Console.WriteLine("Line counting is off."); else { #if DEBUG Utility.assert(spec.count_lines); #endif Console.WriteLine("Line counting is on."); } Console.WriteLine("\n\t** Operating System Specificity **"); #if FOODEBUG if (spec.nfa_states != null && spec.nfa_start != null) { Console.WriteLine("\n\t** NFA machine **"); print_nfa(); } #endif if (spec.dtrans_list != null) { Console.WriteLine("\n\t** DFA transition table **"); } } /* * Function: print_header */ private void print_header() { int j; int chars_printed=0; DTrans dtrans; int last_transition; String str; Accept accept; Console.WriteLine("/*---------------------- DFA -----------------------"); if (spec.states == null) throw new ApplicationException("States is null"); foreach (string state in spec.states.Keys) { int index = (int) spec.states[state]; #if DEBUG Utility.assert(null != state); #endif Console.WriteLine("State \"" + state + "\" has identifying index " + index + "."); if (DTrans.F != spec.state_dtrans[index]) { Console.WriteLine("\tStart index in transition table: " + spec.state_dtrans[index]); } else { Console.WriteLine("\tNo associated transition states."); } } for (int i = 0; i < spec.dtrans_list.Count; ++i) { dtrans = (DTrans) spec.dtrans_list[i]; if (null == spec.accept_list && null == spec.anchor_array) { if (null == dtrans.GetAccept()) { Console.Write(" * State " + i + " [nonaccepting]"); } else { Console.Write(" * State " + i + " [accepting, line " + dtrans.GetAccept().line_number + " <" + dtrans.GetAccept().action + ">]"); if (Spec.NONE != dtrans.GetAnchor()) { Console.Write(" Anchor: " + ((0 != (dtrans.GetAnchor() & Spec.START)) ? "start " : "") + ((0 != (dtrans.GetAnchor() & Spec.END)) ? "end " : "")); } } } else { accept = (Accept) spec.accept_list[i]; if (null == accept) { Console.Write(" * State " + i + " [nonaccepting]"); } else { Console.Write(" * State " + i + " [accepting, line " + accept.line_number + " <" + accept.action + ">]"); if (Spec.NONE != spec.anchor_array[i]) { Console.Write(" Anchor: " + ((0 != (spec.anchor_array[i] & Spec.START)) ? "start " : "") + ((0 != (spec.anchor_array[i] & Spec.END)) ? "end " : "")); } } } last_transition = -1; for (j = 0; j < spec.dtrans_ncols; ++j) { if (DTrans.F != dtrans.GetDTrans(j)) { if (last_transition != dtrans.GetDTrans(j)) { Console.Write("\n * goto " + dtrans.GetDTrans(j) + " on "); chars_printed = 0; } str = interp_int((int) j); Console.Write(str); chars_printed = chars_printed + str.Length; if (56 < chars_printed) { Console.Write("\n * "); chars_printed = 0; } last_transition = dtrans.GetDTrans(j); } } Console.WriteLine(""); } Console.WriteLine(" */\n"); } } }
#region Using Statements using System; using WaveEngine.Common; using WaveEngine.Common.Graphics; using WaveEngine.Common.Math; using WaveEngine.Components.Cameras; using WaveEngine.Components.Graphics2D; using WaveEngine.Components.Graphics3D; using WaveEngine.Components.UI; using WaveEngine.Framework; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Resources; using WaveEngine.Framework.Services; using WaveEngine.Framework.UI; using WaveEngine.Materials; #endregion namespace AMoreComplexUIProject { public class MyScene : Scene { private Color backgroundColor = new Color(163 / 255f, 178 / 255f, 97 / 255f); private Color darkColor = new Color(120 / 255f, 39 / 255f, 72 / 255f); private Color lightColor = new Color(157 / 255f, 73 / 255f, 133 / 255f); private Transform3D cubeTransform; private BasicMaterial cubeMaterial; private Slider sliderRotX; private Slider sliderRotY; protected override void CreateScene() { //Create a 3D camera var camera3D = new FixedCamera("Camera3D", new Vector3(2f, 0f, 2.8f), new Vector3(.5f, 0, 0)) { BackgroundColor = backgroundColor }; EntityManager.Add(camera3D); this.CreateCube3D(); // Create a 2D camera var camera2D = new FixedCamera2D("Camera2D") { ClearFlags = ClearFlags.DepthAndStencil }; // Transparent background need this clearFlags. EntityManager.Add(camera2D); this.CreateSliders(); this.CreateGrid(); this.CreateDebugMode(); } private void CreateDebugMode() { ToggleSwitch debugMode = new ToggleSwitch() { OnText = "Debug On", OffText = "Debug Off", Margin = new Thickness(5), Width = 200, Foreground = darkColor, Background = lightColor, }; debugMode.Toggled += (s, o) => { RenderManager.DebugLines = debugMode.IsOn; }; EntityManager.Add(debugMode.Entity); } private void CreateGrid() { Grid grid = new Grid() { HorizontalAlignment = HorizontalAlignment.Right, Height = WaveServices.Platform.ScreenHeight, }; grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(4, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(3, GridUnitType.Proportional) }); grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(200, GridUnitType.Pixel) }); EntityManager.Add(grid); #region Color UI TextBlock t_colors = new TextBlock() { Text = "Colors", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(10), }; t_colors.SetValue(GridControl.RowProperty, 0); t_colors.SetValue(GridControl.ColumnProperty, 0); grid.Add(t_colors); StackPanel stackPanel = new StackPanel() { Margin = new Thickness(30, 0, 0, 0), }; stackPanel.SetValue(GridControl.RowProperty, 1); stackPanel.SetValue(GridControl.ColumnProperty, 0); grid.Add(stackPanel); RadioButton radio1 = new RadioButton() { Text = "Red", GroupName = "colors", Foreground = Color.Red, }; radio1.Checked += (s, o) => { this.cubeMaterial.DiffuseColor = Color.Red; }; stackPanel.Add(radio1); RadioButton radio2 = new RadioButton() { Text = "Green", GroupName = "colors", Foreground = Color.Green, }; radio2.Checked += (s, o) => { this.cubeMaterial.DiffuseColor = Color.Green; }; stackPanel.Add(radio2); RadioButton radio3 = new RadioButton() { Text = "Blue", GroupName = "colors", Foreground = Color.Blue, }; radio3.Checked += (s, o) => { this.cubeMaterial.DiffuseColor = Color.Blue; }; stackPanel.Add(radio3); RadioButton radio4 = new RadioButton() { Text = "White", GroupName = "colors", Foreground = Color.White, IsChecked = true, }; radio4.Checked += (s, o) => { this.cubeMaterial.DiffuseColor = Color.White; }; stackPanel.Add(radio4); #endregion #region Texture UI TextBlock t_texture = new TextBlock() { Text = "Textures", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(10), }; t_texture.SetValue(GridControl.RowProperty, 2); t_texture.SetValue(GridControl.ColumnProperty, 0); grid.Add(t_texture); ToggleSwitch toggleTexture = new ToggleSwitch() { Margin = new Thickness(30, 0, 0, 0), Foreground = darkColor, Background = lightColor, IsOn = true, }; toggleTexture.Toggled += (s, o) => { this.cubeMaterial.TextureEnabled = toggleTexture.IsOn; }; toggleTexture.SetValue(GridControl.RowProperty, 3); toggleTexture.SetValue(GridControl.ColumnProperty, 0); grid.Add(toggleTexture); #endregion #region Scale UI TextBlock t_scale = new TextBlock() { Text = "Scale", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(10), }; t_scale.SetValue(GridControl.RowProperty, 4); t_scale.SetValue(GridControl.ColumnProperty, 0); grid.Add(t_scale); Slider sliderScale = new Slider() { Width = 150, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(30, 0, 0, 0), Foreground = darkColor, Background = lightColor, Value = 50, }; sliderScale.RealTimeValueChanged += (s, o) => { this.cubeTransform.Scale = Vector3.One / 2 + (Vector3.One * (o.NewValue / 100f)); }; sliderScale.SetValue(GridControl.RowProperty, 5); sliderScale.SetValue(GridControl.ColumnProperty, 0); grid.Add(sliderScale); #endregion #region Reset UI Button b_reset = new Button() { Text = "Reset", Margin = new Thickness(10, 0, 0, 20), VerticalAlignment = VerticalAlignment.Bottom, Foreground = Color.White, BackgroundColor = lightColor, }; b_reset.Click += (s, o) => { radio4.IsChecked = true; toggleTexture.IsOn = true; sliderScale.Value = 50; this.sliderRotX.Value = 0; this.sliderRotY.Value = 0; }; b_reset.SetValue(GridControl.RowProperty, 6); b_reset.SetValue(GridControl.ColumnProperty, 0); grid.Add(b_reset); #endregion } private void CreateSliders() { TextBlock t_rotX = new TextBlock() { Text = "Rot X", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(15, 0, 0, 60), }; EntityManager.Add(t_rotX); this.sliderRotX = new Slider() { Margin = new Thickness(50, 0, 0, 0), Orientation = Orientation.Vertical, VerticalAlignment = VerticalAlignment.Center, Height = 360, Width = 40, Minimum = 0, Maximum = 360, Foreground = darkColor, Background = lightColor, }; this.sliderRotX.RealTimeValueChanged += this.sliderRot_RealTimeValueChanged; EntityManager.Add(this.sliderRotX); TextBlock t_rotY = new TextBlock() { Text = "Rot Y", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(40, 0, 0, 40), }; EntityManager.Add(t_rotY); this.sliderRotY = new Slider() { Margin = new Thickness(100, 20, 0, 32), VerticalAlignment = VerticalAlignment.Bottom, Width = 360, Height = 40, Minimum = 0, Maximum = 360, Foreground = darkColor, Background = lightColor, }; this.sliderRotY.RealTimeValueChanged += this.sliderRot_RealTimeValueChanged; EntityManager.Add(this.sliderRotY); } private void sliderRot_RealTimeValueChanged(object sender, ChangedEventArgs e) { this.cubeTransform.LocalRotation = new Vector3(MathHelper.ToRadians(this.sliderRotX.Value), MathHelper.ToRadians(this.sliderRotY.Value), 0); } private void CreateCube3D() { Entity cube = new Entity("Cube") .AddComponent(new Transform3D()) .AddComponent(Model.CreateCube()) .AddComponent(new MaterialsMap(new BasicMaterial("Content/crate.jpg"))) .AddComponent(new ModelRenderer()); this.cubeTransform = cube.FindComponent<Transform3D>(); this.cubeMaterial = (BasicMaterial)cube.FindComponent<MaterialsMap>().DefaultMaterial; EntityManager.Add(cube); } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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.Collections.Generic; using NUnit.Framework.Internal; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Attributes { public class TestMethodBuilderTests { #region TestAttribute [Test] public void TestAttribute_NoArgs_Runnable() { var method = GetMethod("MethodWithoutArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestAttribute_WithArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseAttribute [Test] public void TestCaseAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42, 99).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseSourceAttribute [Test] public void TestCaseSourceAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_NoArgs_NoData_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("ZeroData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseSourceAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("BadData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TheoryAttribute [Test] public void TheoryAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void TheoryAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(9)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void CombinatorialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void PairwiseAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region SequentialAttribute [Test] public void SequentialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void SequentialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region Helper Methods and Data private IMethodInfo GetMethod(string methodName) { return new MethodWrapper(GetType(), methodName); } public static void MethodWithoutArgs() { } public static void MethodWithIntArgs(int x, int y) { } public static void MethodWithIntValues( [Values(1, 2, 3)]int x, [Values(10, 20)]int y) { } static object[] ZeroData = new object[0]; static object[] GoodData = new object[] { new object[] { 12, 3 }, new object[] { 12, 4 }, new object[] { 12, 6 } }; static object[] BadData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; [DatapointSource] int[] ints = new int[] { 1, 2, 3 }; #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.Styles { // // ********************************************************************** /// <summary> /// Defines a style used for rendering labels /// </summary> // ********************************************************************** // public class LabelStyle : AbstractStyle { #region Private Member Variables // // ********************************************************************** /// <summary> /// Font /// </summary> // ********************************************************************** // private System.Drawing.Font m_Font; // // ********************************************************************** /// <summary> /// Foreground Colour /// </summary> // ********************************************************************** // private System.Drawing.Color m_ForeColor; // // ********************************************************************** /// <summary> /// Background Colour /// </summary> // ********************************************************************** // private System.Drawing.Brush m_BackColor; // // ********************************************************************** /// <summary> /// Pen Halo /// </summary> // ********************************************************************** // private System.Drawing.Pen m_Halo; // // ********************************************************************** /// <summary> /// Point Offset /// </summary> // ********************************************************************** // private System.Drawing.PointF m_Offset; // // ********************************************************************** /// <summary> /// Collision Detection /// </summary> // ********************************************************************** // private bool m_CollisionDetection; // // ********************************************************************** /// <summary> /// Collision Buffer /// </summary> // ********************************************************************** // private System.Drawing.SizeF m_CollisionBuffer; // // ********************************************************************** /// <summary> /// Horizontal Alignment /// </summary> // ********************************************************************** // private HorizontalAlignmentEnum m_HorisontalAlignment; // // ********************************************************************** /// <summary> /// Vertical Alignment /// </summary> // ********************************************************************** // private VerticalAlignmentEnum m_VerticalAlignment; #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new LabelStyle /// </summary> // ********************************************************************** // public LabelStyle() { m_Font = new System.Drawing.Font("Times New Roman", 12f); m_Offset = new System.Drawing.PointF(0, 0); m_CollisionDetection = false; m_CollisionBuffer = new System.Drawing.Size(0, 0); m_ForeColor = System.Drawing.Color.Black; m_HorisontalAlignment = HorizontalAlignmentEnum.Center; m_VerticalAlignment = VerticalAlignmentEnum.Middle; } #endregion #region Properties // // ********************************************************************** /// <summary> /// Label Font /// </summary> /// <value>The font.</value> // ********************************************************************** // public System.Drawing.Font Font { get { return m_Font; } set { m_Font = value; } } // // ********************************************************************** /// <summary> /// Font color /// </summary> /// <value>The color of the fore.</value> // ********************************************************************** // public System.Drawing.Color ForeColor { get { return m_ForeColor; } set { m_ForeColor = value; } } // // ********************************************************************** /// <summary> /// The background color of the label. Set to transparent brush or null if background isn't needed /// </summary> /// <value>The color of the back.</value> // ********************************************************************** // public System.Drawing.Brush BackColor { get { return m_BackColor; } set { m_BackColor = value; } } // // ********************************************************************** /// <summary> /// Creates a halo around the text /// </summary> /// <value>The halo.</value> // ********************************************************************** // public System.Drawing.Pen Halo { get { return m_Halo; } set { m_Halo = value; } } // // ********************************************************************** /// <summary> /// Specifies relative position of labels with respect to objects label point /// </summary> /// <value>The offset.</value> // ********************************************************************** // public System.Drawing.PointF Offset { get { return m_Offset; } set { m_Offset = value; } } // // ********************************************************************** /// <summary> /// Gets or sets whether Collision Detection is enabled for the labels. /// If set to true, label collision will be tested. /// </summary> /// <value><c>true</c> if [collision detection]; otherwise, <c>false</c>.</value> // ********************************************************************** // public bool CollisionDetection { get { return m_CollisionDetection; } set { m_CollisionDetection = value; } } // // ********************************************************************** /// <summary> /// Distance around label where collision buffer is active /// </summary> /// <value>The collision buffer.</value> // ********************************************************************** // public System.Drawing.SizeF CollisionBuffer { get { return m_CollisionBuffer; } set { m_CollisionBuffer = value; } } // // ********************************************************************** /// <summary> /// The horisontal alignment of the text in relation to the labelpoint /// </summary> /// <value>The horizontal alignment.</value> // ********************************************************************** // public HorizontalAlignmentEnum HorizontalAlignment { get { return m_HorisontalAlignment; } set { m_HorisontalAlignment = value; } } // // ********************************************************************** /// <summary> /// The horisontal alignment of the text in relation to the labelpoint /// </summary> /// <value>The vertical alignment.</value> // ********************************************************************** // public VerticalAlignmentEnum VerticalAlignment { get { return m_VerticalAlignment; } set { m_VerticalAlignment = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System; using System.Collections; using System.Data; using System.IO; using System.Threading.Tasks; using System.Threading; namespace System.Data.Common { public abstract class DbDataReader : IDisposable, IEnumerable { protected DbDataReader() : base() { } abstract public int Depth { get; } abstract public int FieldCount { get; } abstract public bool HasRows { get; } abstract public bool IsClosed { get; } abstract public int RecordsAffected { get; } virtual public int VisibleFieldCount { get { return FieldCount; } } abstract public object this[int ordinal] { get; } abstract public object this[string name] { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { } } abstract public string GetDataTypeName(int ordinal); abstract public IEnumerator GetEnumerator(); abstract public Type GetFieldType(int ordinal); abstract public string GetName(int ordinal); abstract public int GetOrdinal(string name); abstract public bool GetBoolean(int ordinal); abstract public byte GetByte(int ordinal); abstract public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length); abstract public char GetChar(int ordinal); abstract public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length); public DbDataReader GetData(int ordinal) { return GetDbDataReader(ordinal); } virtual protected DbDataReader GetDbDataReader(int ordinal) { throw ADP.NotSupported(); } abstract public DateTime GetDateTime(int ordinal); abstract public Decimal GetDecimal(int ordinal); abstract public double GetDouble(int ordinal); abstract public float GetFloat(int ordinal); abstract public Guid GetGuid(int ordinal); abstract public Int16 GetInt16(int ordinal); abstract public Int32 GetInt32(int ordinal); abstract public Int64 GetInt64(int ordinal); virtual public Type GetProviderSpecificFieldType(int ordinal) { return GetFieldType(ordinal); } virtual public Object GetProviderSpecificValue(int ordinal) { return GetValue(ordinal); } virtual public int GetProviderSpecificValues(object[] values) { return GetValues(values); } abstract public String GetString(int ordinal); virtual public Stream GetStream(int ordinal) { using (MemoryStream bufferStream = new MemoryStream()) { long bytesRead = 0; long bytesReadTotal = 0; byte[] buffer = new byte[4096]; do { bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length); bufferStream.Write(buffer, 0, (int)bytesRead); bytesReadTotal += bytesRead; } while (bytesRead > 0); return new MemoryStream(bufferStream.ToArray(), false); } } virtual public TextReader GetTextReader(int ordinal) { if (IsDBNull(ordinal)) { return new StringReader(String.Empty); } else { return new StringReader(GetString(ordinal)); } } abstract public Object GetValue(int ordinal); virtual public T GetFieldValue<T>(int ordinal) { return (T)GetValue(ordinal); } public Task<T> GetFieldValueAsync<T>(int ordinal) { return GetFieldValueAsync<T>(ordinal, CancellationToken.None); } virtual public Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<T>(cancellationToken); } else { try { return Task.FromResult<T>(GetFieldValue<T>(ordinal)); } catch (Exception e) { return TaskHelpers.FromException<T>(e); } } } abstract public int GetValues(object[] values); abstract public bool IsDBNull(int ordinal); public Task<bool> IsDBNullAsync(int ordinal) { return IsDBNullAsync(ordinal, CancellationToken.None); } virtual public Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } abstract public bool NextResult(); abstract public bool Read(); public Task<bool> ReadAsync() { return ReadAsync(CancellationToken.None); } virtual public Task<bool> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return Read() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } public Task<bool> NextResultAsync() { return NextResultAsync(CancellationToken.None); } virtual public Task<bool> NextResultAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return NextResult() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } } }
// <copyright file="SparseVectorTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; using MathNet.Numerics.LinearAlgebra.Storage; using NUnit.Framework; using System; using System.Collections.Generic; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double { /// <summary> /// Sparse vector tests. /// </summary> public class SparseVectorTest : VectorTests { /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="size">The size of the <strong>Vector</strong> to construct.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<double> CreateVector(int size) { return Vector<double>.Build.Sparse(size); } /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="data">The array to create this vector from.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<double> CreateVector(IList<double> data) { var vector = Vector<double>.Build.Sparse(data.Count); for (var index = 0; index < data.Count; index++) { vector[index] = data[index]; } return vector; } /// <summary> /// Can create a sparse vector form array. /// </summary> [Test] public void CanCreateSparseVectorFromArray() { var data = new double[Data.Length]; Array.Copy(Data, data, Data.Length); var vector = Vector<double>.Build.SparseOfEnumerable(data); for (var i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], vector[i]); } } /// <summary> /// Can create a sparse vector from another sparse vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherSparseVector() { var vector = Vector<double>.Build.SparseOfEnumerable(Data); var other = Vector<double>.Build.SparseOfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from another vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherVector() { var vector = Vector<double>.Build.SparseOfEnumerable(Data); var other = Vector<double>.Build.SparseOfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from user defined vector. /// </summary> [Test] public void CanCreateSparseVectorFromUserDefinedVector() { var vector = new UserDefinedVector(Data); var other = Vector<double>.Build.SparseOfVector(vector); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse matrix. /// </summary> [Test] public void CanCreateSparseMatrix() { var vector = Vector<double>.Build.Sparse(3); var matrix = Matrix<double>.Build.SameAs(vector, 2, 3); Assert.IsInstanceOf<SparseMatrix>(matrix); Assert.AreEqual(2, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); } /// <summary> /// Can convert a sparse vector to an array. /// </summary> [Test] public void CanConvertSparseVectorToArray() { var vector = Vector<double>.Build.SparseOfEnumerable(Data); var array = vector.ToArray(); Assert.IsInstanceOf(typeof (double[]), array); CollectionAssert.AreEqual(vector, array); } /// <summary> /// Can convert an array to a sparse vector. /// </summary> [Test] public void CanConvertArrayToSparseVector() { var array = new[] {0.0, 1.0, 2.0, 3.0, 4.0}; var vector = Vector<double>.Build.SparseOfEnumerable(array); Assert.IsInstanceOf(typeof (SparseVector), vector); CollectionAssert.AreEqual(array, array); } /// <summary> /// Can multiply a sparse vector by a scalar using "*" operator. /// </summary> [Test] public void CanMultiplySparseVectorByScalarUsingOperators() { var vector = Vector<double>.Build.SparseOfEnumerable(Data); vector = vector*2.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, vector[i]); } vector = vector*1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, vector[i]); } vector = Vector<double>.Build.SparseOfEnumerable(Data); vector = 2.0*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, vector[i]); } vector = 1.0*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, vector[i]); } } /// <summary> /// Can divide a sparse vector by a scalar using "/" operator. /// </summary> [Test] public void CanDivideSparseVectorByScalarUsingOperators() { var vector = Vector<double>.Build.SparseOfEnumerable(Data); vector = vector/2.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]/2.0, vector[i]); } vector = vector/1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]/2.0, vector[i]); } } /// <summary> /// Can calculate an outer product for a sparse vector. /// </summary> [Test] public void CanCalculateOuterProductForSparseVector() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<double>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i]*vector2[j]); } } } /// <summary> /// Check sparse mechanism by setting values. /// </summary> [Test] public void CheckSparseMechanismBySettingValues() { var vector = Vector<double>.Build.Sparse(10000); var storage = (SparseVectorStorage<double>) vector.Storage; // Add non-zero elements vector[200] = 1.5; Assert.AreEqual(1.5, vector[200]); Assert.AreEqual(1, storage.ValueCount); vector[500] = 3.5; Assert.AreEqual(3.5, vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = 5.5; Assert.AreEqual(5.5, vector[800]); Assert.AreEqual(3, storage.ValueCount); vector[0] = 7.5; Assert.AreEqual(7.5, vector[0]); Assert.AreEqual(4, storage.ValueCount); // Remove non-zero elements vector[200] = 0; Assert.AreEqual(0, vector[200]); Assert.AreEqual(3, storage.ValueCount); vector[500] = 0; Assert.AreEqual(0, vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = 0; Assert.AreEqual(0, vector[800]); Assert.AreEqual(1, storage.ValueCount); vector[0] = 0; Assert.AreEqual(0, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Check sparse mechanism by zero multiply. /// </summary> [Test] public void CheckSparseMechanismByZeroMultiply() { var vector = Vector<double>.Build.Sparse(10000); // Add non-zero elements vector[200] = 1.5; vector[500] = 3.5; vector[800] = 5.5; vector[0] = 7.5; // Multiply by 0 vector *= 0; var storage = (SparseVectorStorage<double>) vector.Storage; Assert.AreEqual(0, vector[200]); Assert.AreEqual(0, vector[500]); Assert.AreEqual(0, vector[800]); Assert.AreEqual(0, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Can calculate a dot product of two sparse vectors. /// </summary> [Test] public void CanDotProductOfTwoSparseVectors() { var vectorA = Vector<double>.Build.Sparse(10000); vectorA[200] = 1; vectorA[500] = 3; vectorA[800] = 5; vectorA[100] = 7; vectorA[900] = 9; var vectorB = Vector<double>.Build.Sparse(10000); vectorB[300] = 3; vectorB[500] = 5; vectorB[800] = 7; Assert.AreEqual(50.0, vectorA.DotProduct(vectorB)); } /// <summary> /// Can pointwise multiple a sparse vector. /// </summary> [Test] public void CanPointwiseMultiplySparseVector() { var zeroArray = new[] {0.0, 1.0, 0.0, 1.0, 0.0}; var vector1 = Vector<double>.Build.SparseOfEnumerable(Data); var vector2 = Vector<double>.Build.SparseOfEnumerable(zeroArray); var result = Vector<double>.Build.Sparse(vector1.Count); vector1.PointwiseMultiply(vector2, result); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i]*zeroArray[i], result[i]); } var resultStorage = (SparseVectorStorage<double>) result.Storage; Assert.AreEqual(2, resultStorage.ValueCount); } /// <summary> /// Can outer multiple two sparse vectors. Checking fix for workitem 5696. /// </summary> [Test] public void CanOuterMultiplySparseVectors() { var vector1 = Vector<double>.Build.SparseOfEnumerable(new[] { 2.0, 2.0, 0.0, 0.0 }); var vector2 = Vector<double>.Build.SparseOfEnumerable(new[] { 2.0, 2.0, 0.0, 0.0 }); var result = vector1.OuterProduct(vector2); Assert.AreEqual(4.0, result[0, 0]); Assert.AreEqual(4.0, result[0, 1]); Assert.AreEqual(4.0, result[1, 0]); Assert.AreEqual(4.0, result[1, 1]); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { if (i > 1 || j > 1) { Assert.AreEqual(0.0, result[i, j]); } } } } /// <summary> /// Test for issues #52. When setting previous non-zero values to zero, /// DoMultiply would copy non-zero values to the result, but use the /// length of nonzerovalues instead of NonZerosCount. /// </summary> [Test] public void CanScaleAVectorWhenSettingPreviousNonzeroElementsToZero() { var vector = Vector<double>.Build.Sparse(20); vector[10] = 1.0; vector[11] = 2.0; vector[11] = 0.0; var scaled = Vector<double>.Build.Sparse(20); vector.Multiply(3.0, scaled); Assert.AreEqual(3.0, scaled[10]); Assert.AreEqual(0.0, scaled[11]); } } }
/* * 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.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientRegionInterestRegexInterest2Tests : ThinClientRegionSteps { #region Private members and methods private UnitProcess m_client1, m_client2, m_client3, m_feeder; private static string[] m_regexes = { "Key-*1", "Key-*2", "Key-*3", "Key-*4" }; private const string m_regex23 = "Key-[23]"; private const string m_regexWildcard = "Key-.*"; private const int m_numUnicodeStrings = 5; private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" }; private static string[] m_keysForRegex = {"key-regex-1", "key-regex-2", "key-regex-3" }; private static string[] RegionNamesForInterestNotify = { "RegionTrue", "RegionFalse", "RegionOther" }; string GetUnicodeString(int index) { return new string('\x0905', 40) + index.ToString("D10"); } #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); m_client3 = new UnitProcess(); m_feeder = new UnitProcess(); return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder }; } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { m_client1.Call(DestroyRegions); m_client2.Call(DestroyRegions); CacheHelper.ClearEndpoints(); } finally { CacheHelper.StopJavaServers(); } base.EndTest(); } #region Steps for Thin Client IRegion<object, object> with Interest public void StepFourIL() { VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); } public void StepFourRegex3() { IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); try { Util.Log("Registering empty regular expression."); region0.GetSubscriptionService().RegisterRegex(string.Empty); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } try { Util.Log("Registering null regular expression."); region1.GetSubscriptionService().RegisterRegex(null); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } try { Util.Log("Registering non-existent regular expression."); region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*"); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } } public void StepFourFailoverRegex() { VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true); UnregisterRegexes(null, m_regexes[2]); } public void StepFiveIL() { VerifyCreated(m_regionNames[0], m_keys[1]); VerifyCreated(m_regionNames[1], m_keys[3]); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false); } public void StepFiveRegex() { CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]); CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]); } public void CreateAllEntries(string regionName) { CreateEntry(regionName, m_keys[0], m_vals[0]); CreateEntry(regionName, m_keys[1], m_vals[1]); CreateEntry(regionName, m_keys[2], m_vals[2]); CreateEntry(regionName, m_keys[3], m_vals[3]); } public void VerifyAllEntries(string regionName, bool newVal, bool checkVal) { string[] vals = newVal ? m_nvals : m_vals; VerifyEntry(regionName, m_keys[0], vals[0], checkVal); VerifyEntry(regionName, m_keys[1], vals[1], checkVal); VerifyEntry(regionName, m_keys[2], vals[2], checkVal); VerifyEntry(regionName, m_keys[3], vals[3], checkVal); } public void VerifyInvalidAll(string regionName, params string[] keys) { if (keys != null) { foreach (string key in keys) { VerifyInvalid(regionName, key); } } } public void UpdateAllEntries(string regionName, bool checkVal) { UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal); UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal); UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal); UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal); } public void DoNetsearchAllEntries(string regionName, bool newVal, bool checkNoKey) { string[] vals; if (newVal) { vals = m_nvals; } else { vals = m_vals; } DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey); DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey); DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey); DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey); } public void StepFiveFailoverRegex() { UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false); } public void StepSixIL() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]); region0.Remove(m_keys[1]); region1.Remove(m_keys[3]); } public void StepSixRegex() { CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]); CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UnregisterRegexes(null, m_regexes[3]); } public void StepSixFailoverRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false); UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false); } public void StepSevenIL() { VerifyDestroyed(m_regionNames[0], m_keys[1]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); } public void StepSevenRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]); UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true); UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true); UnregisterRegexes(null, m_regexes[1]); } public void StepSevenRegex2() { VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]); DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true); DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true); UpdateAllEntries(m_regionNames[1], true); } public void StepSevenInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region.GetSubscriptionService().RegisterRegex(m_regex23); VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true); VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true); } public void StepSevenFailoverRegex() { UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true); UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true); VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]); } public void StepEightIL() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]); } public void StepEightRegex() { VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true); UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true); } public void StepEightInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); region.GetSubscriptionService().RegisterAllKeys(); VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1], m_keys[2], m_keys[3]); UpdateAllEntries(m_regionNames[0], true); } public void StepEightFailoverRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); } public void StepNineRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]); } public void StepNineRegex2() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]); } public void StepNineInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region.GetSubscriptionService().UnregisterRegex(m_regex23); List<Object> keys = new List<Object>(); keys.Add(m_keys[0]); keys.Add(m_keys[1]); keys.Add(m_keys[2]); region.GetSubscriptionService().RegisterKeys(keys); VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]); } public void PutUnicodeKeys(string regionName, bool updates) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string key; object val; for (int index = 0; index < m_numUnicodeStrings; ++index) { key = GetUnicodeString(index); if (updates) { val = index + 100; } else { val = (float)index + 20.0F; } region[key] = val; } } public void RegisterUnicodeKeys(string regionName) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string[] keys = new string[m_numUnicodeStrings]; for (int index = 0; index < m_numUnicodeStrings; ++index) { keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index); } region.GetSubscriptionService().RegisterKeys(keys); } public void VerifyUnicodeKeys(string regionName, bool updates) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string key; object expectedVal; for (int index = 0; index < m_numUnicodeStrings; ++index) { key = GetUnicodeString(index); if (updates) { expectedVal = index + 100; Assert.AreEqual(expectedVal, region.GetEntry(key).Value, "Got unexpected value"); } else { expectedVal = (float)index + 20.0F; Assert.AreEqual(expectedVal, region[key], "Got unexpected value"); } } } public void CreateRegionsInterestNotify_Pool(string[] regionNames, string locators, string poolName, bool notify, string nbs) { Properties<string, string> props = Properties<string, string>.Create<string, string>(); //props.Insert("notify-by-subscription-override", nbs); CacheHelper.InitConfig(props); CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true, new TallyListener<object, object>(), locators, poolName, notify); CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true, new TallyListener<object, object>(), locators, poolName, notify); CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true, new TallyListener<object, object>(), locators, poolName, notify); } /* public void CreateRegionsInterestNotify(string[] regionNames, string endpoints, bool notify, string nbs) { Properties props = Properties.Create(); //props.Insert("notify-by-subscription-override", nbs); CacheHelper.InitConfig(props); CacheHelper.CreateTCRegion(regionNames[0], true, false, new TallyListener(), endpoints, notify); CacheHelper.CreateTCRegion(regionNames[1], true, false, new TallyListener(), endpoints, notify); CacheHelper.CreateTCRegion(regionNames[2], true, false, new TallyListener(), endpoints, notify); } * */ public void DoFeed() { foreach (string regionName in RegionNamesForInterestNotify) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); foreach (string key in m_keysNonRegex) { region[key] = "00"; } foreach (string key in m_keysForRegex) { region[key] = "00"; } } } public void DoFeederOps() { foreach (string regionName in RegionNamesForInterestNotify) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); foreach (string key in m_keysNonRegex) { region[key] = "11"; region[key] = "22"; region[key] = "33"; region.GetLocalView().Invalidate(key); region.Remove(key); } foreach (string key in m_keysForRegex) { region[key] = "11"; region[key] = "22"; region[key] = "33"; region.GetLocalView().Invalidate(key); region.Remove(key); } } } public void DoRegister() { DoRegisterInterests(RegionNamesForInterestNotify[0], true); DoRegisterInterests(RegionNamesForInterestNotify[1], false); // We intentionally do not register interest in Region3 //DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]); } public void DoRegisterInterests(string regionName, bool receiveValues) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); List<string> keys = new List<string>(); foreach (string key in m_keysNonRegex) { keys.Add(key); } region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues); region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues); } public void DoUnregister() { DoUnregisterInterests(RegionNamesForInterestNotify[0]); DoUnregisterInterests(RegionNamesForInterestNotify[1]); } public void DoUnregisterInterests(string regionName) { List<string> keys = new List<string>(); foreach (string key in m_keysNonRegex) { keys.Add(key); } IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); region.GetSubscriptionService().UnregisterKeys(keys.ToArray()); region.GetSubscriptionService().UnregisterRegex("key-regex.*"); } public void DoValidation(string clientName, string regionName, int creates, int updates, int invalidates, int destroys) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>; Util.Log(clientName + ": " + regionName + ": creates expected=" + creates + ", actual=" + listener.Creates); Util.Log(clientName + ": " + regionName + ": updates expected=" + updates + ", actual=" + listener.Updates); Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates + ", actual=" + listener.Invalidates); Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys + ", actual=" + listener.Destroys); Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName); Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName); Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName); Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName); } #endregion [Test] public void RegexInterest2() { CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true); Util.Log("StepOne complete."); m_client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true); Util.Log("StepTwo complete."); m_client1.Call(RegisterRegexes, m_regex23, (string)null); Util.Log("StepThree complete."); m_client2.Call(RegisterRegexes, (string)null, m_regexWildcard); Util.Log("StepFour complete."); m_client1.Call(CreateAllEntries, RegionNames[1]); Util.Log("StepFive complete."); m_client2.Call(CreateAllEntries, RegionNames[0]); m_client2.Call(VerifyAllEntries, RegionNames[1], false, false); Util.Log("StepSix complete."); m_client1.Call(StepSevenRegex2); m_client1.Call(UpdateAllEntries, RegionNames[1], true); Util.Log("StepSeven complete."); m_client2.Call(VerifyAllEntries, RegionNames[1], true, true); m_client2.Call(UpdateAllEntries, RegionNames[0], true); Util.Log("StepEight complete."); m_client1.Call(StepNineRegex2); Util.Log("StepNine complete."); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } } }
/* * Copyright 2017 ZXing.Net authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Runtime.InteropServices; using ZXing.Common; using ZXing.OneD; namespace ZXing.ZKWeb.Rendering { /// <summary> /// Renders a <see cref="BitMatrix" /> to a <see cref="System.DrawingCore.Bitmap" /> image /// </summary> public class BitmapRenderer : ZXing.Rendering.IBarcodeRenderer<System.DrawingCore.Bitmap> { /// <summary> /// Gets or sets the foreground color. /// </summary> /// <value>The foreground color.</value> public System.DrawingCore.Color Foreground { get; set; } /// <summary> /// Gets or sets the background color. /// </summary> /// <value>The background color.</value> public System.DrawingCore.Color Background { get; set; } /// <summary> /// Gets or sets the resolution which should be used to create the bitmap /// If nothing is set the current system settings are used /// </summary> public float? DpiX { get; set; } /// <summary> /// Gets or sets the resolution which should be used to create the bitmap /// If nothing is set the current system settings are used /// </summary> public float? DpiY { get; set; } /// <summary> /// Gets or sets the text font. /// </summary> /// <value> /// The text font. /// </value> public System.DrawingCore.Font TextFont { get; set; } private static readonly System.DrawingCore.Font DefaultTextFont; static BitmapRenderer() { try { DefaultTextFont = new System.DrawingCore.Font("Arial", 10, System.DrawingCore.FontStyle.Regular); } catch (Exception) { // have to ignore, no better idea } } /// <summary> /// Initializes a new instance of the <see cref="BitmapRenderer"/> class. /// </summary> public BitmapRenderer() { Foreground = System.DrawingCore.Color.Black; Background = System.DrawingCore.Color.White; TextFont = DefaultTextFont; } /// <summary> /// Renders the specified matrix. /// </summary> /// <param name="matrix">The matrix.</param> /// <param name="format">The format.</param> /// <param name="content">The content.</param> /// <returns></returns> public System.DrawingCore.Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content) { return Render(matrix, format, content, new EncodingOptions()); } /// <summary> /// Renders the specified matrix. /// </summary> /// <param name="matrix">The matrix.</param> /// <param name="format">The format.</param> /// <param name="content">The content.</param> /// <param name="options">The options.</param> /// <returns></returns> public System.DrawingCore.Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options) { var width = matrix.Width; var height = matrix.Height; var font = TextFont ?? DefaultTextFont; var emptyArea = 0; var outputContent = font != null && (options == null || !options.PureBarcode) && !String.IsNullOrEmpty(content) && (format == BarcodeFormat.CODE_39 || format == BarcodeFormat.CODE_93 || format == BarcodeFormat.CODE_128 || format == BarcodeFormat.EAN_13 || format == BarcodeFormat.EAN_8 || format == BarcodeFormat.CODABAR || format == BarcodeFormat.ITF || format == BarcodeFormat.UPC_A || format == BarcodeFormat.UPC_E || format == BarcodeFormat.MSI || format == BarcodeFormat.PLESSEY); if (options != null) { if (options.Width > width) { width = options.Width; } if (options.Height > height) { height = options.Height; } } // calculating the scaling factor var pixelsizeWidth = width / matrix.Width; var pixelsizeHeight = height / matrix.Height; // create the bitmap and lock the bits because we need the stride // which is the width of the image and possible padding bytes var bmp = new System.DrawingCore.Bitmap(width, height, System.DrawingCore.Imaging.PixelFormat.Format24bppRgb); var dpiX = DpiX ?? DpiY; var dpiY = DpiY ?? DpiX; if (dpiX != null) bmp.SetResolution(dpiX.Value, dpiY.Value); using (var g = System.DrawingCore.Graphics.FromImage(bmp)) { var bmpData = bmp.LockBits(new System.DrawingCore.Rectangle(0, 0, bmp.Width, bmp.Height), System.DrawingCore.Imaging.ImageLockMode.WriteOnly, System.DrawingCore.Imaging.PixelFormat.Format24bppRgb); try { var pixels = new byte[bmpData.Stride * height]; var padding = bmpData.Stride - (3 * width); var index = 0; var color = Background; // going through the lines of the matrix for (int y = 0; y < matrix.Height; y++) { // stretching the line by the scaling factor for (var pixelsizeHeightProcessed = 0; pixelsizeHeightProcessed < pixelsizeHeight; pixelsizeHeightProcessed++) { // going through the columns of the current line for (var x = 0; x < matrix.Width; x++) { color = matrix[x, y] ? Foreground : Background; // stretching the columns by the scaling factor for (var pixelsizeWidthProcessed = 0; pixelsizeWidthProcessed < pixelsizeWidth; pixelsizeWidthProcessed++) { pixels[index++] = color.B; pixels[index++] = color.G; pixels[index++] = color.R; } } // fill up to the right if the barcode doesn't fully fit in for (var x = pixelsizeWidth * matrix.Width; x < width; x++) { pixels[index++] = Background.B; pixels[index++] = Background.G; pixels[index++] = Background.R; } index += padding; } } // fill up to the bottom if the barcode doesn't fully fit in for (var y = pixelsizeHeight * matrix.Height; y < height; y++) { for (var x = 0; x < width; x++) { pixels[index++] = Background.B; pixels[index++] = Background.G; pixels[index++] = Background.R; } index += padding; } // fill the bottom area with the background color if the content should be written below the barcode if (outputContent) { var textAreaHeight = font.Height; emptyArea = height > textAreaHeight ? textAreaHeight : 0; if (emptyArea > 0) { index = (width * 3 + padding) * (height - emptyArea); for (int y = height - emptyArea; y < height; y++) { for (var x = 0; x < width; x++) { pixels[index++] = Background.B; pixels[index++] = Background.G; pixels[index++] = Background.R; } index += padding; } } } //Copy the data from the byte array into BitmapData.Scan0 Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length); } finally { //Unlock the pixels bmp.UnlockBits(bmpData); } // output content text below the barcode if (emptyArea > 0) { switch (format) { case BarcodeFormat.UPC_E: case BarcodeFormat.EAN_8: if (content.Length < 8) content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content); if (content.Length > 4) content = content.Insert(4, " "); break; case BarcodeFormat.EAN_13: if (content.Length < 13) content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content); if (content.Length > 7) content = content.Insert(7, " "); if (content.Length > 1) content = content.Insert(1, " "); break; case BarcodeFormat.UPC_A: if (content.Length < 12) content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content); if (content.Length > 11) content = content.Insert(11, " "); if (content.Length > 6) content = content.Insert(6, " "); if (content.Length > 1) content = content.Insert(1, " "); break; } var brush = new System.DrawingCore.SolidBrush(Foreground); var drawFormat = new System.DrawingCore.StringFormat { Alignment = System.DrawingCore.StringAlignment.Center }; g.DrawString(content, font, brush, pixelsizeWidth * matrix.Width / 2, height - emptyArea, drawFormat); } } return bmp; } } }
using System; using System.Diagnostics; using System.Text; using HANDLE = System.IntPtr; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_CORE //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ private const int SQLITE_CORE = 1; #endif //#include "sqlite3ext.h" //#include "sqliteInt.h" //#include <string.h> #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #if !SQLITE_ENABLE_COLUMN_METADATA //# define sqlite3_column_database_name 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name 0 //# define sqlite3_column_origin_name16 0 //# define sqlite3_table_column_metadata 0 #endif #if SQLITE_OMIT_AUTHORIZATION //# define sqlite3_set_authorizer 0 #endif #if SQLITE_OMIT_UTF16 //# define sqlite3_bind_text16 0 //# define sqlite3_collation_needed16 0 //# define sqlite3_column_decltype16 0 //# define sqlite3_column_name16 0 //# define sqlite3_column_text16 0 //# define sqlite3_complete16 0 //# define sqlite3_create_collation16 0 //# define sqlite3_create_function16 0 //# define sqlite3_errmsg16 0 private static string sqlite3_errmsg16(sqlite3 db) { return ""; } //# define sqlite3_open16 0 //# define sqlite3_prepare16 0 //# define sqlite3_prepare16_v2 0 //# define sqlite3_result_error16 0 //# define sqlite3_result_text16 0 private static void sqlite3_result_text16(sqlite3_context pCtx, string z, int n, dxDel xDel) { } //# define sqlite3_result_text16be 0 //# define sqlite3_result_text16le 0 //# define sqlite3_value_text16 0 //# define sqlite3_value_text16be 0 //# define sqlite3_value_text16le 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name16 0 #endif #if SQLITE_OMIT_COMPLETE //# define sqlite3_complete 0 //# define sqlite3_complete16 0 #endif #if SQLITE_OMIT_DECLTYPE //# define sqlite3_column_decltype16 0 //# define sqlite3_column_decltype 0 #endif #if SQLITE_OMIT_PROGRESS_CALLBACK //# define sqlite3_progress_handler 0 static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if SQLITE_OMIT_VIRTUALTABLE //# define sqlite3_create_module 0 //# define sqlite3_create_module_v2 0 //# define sqlite3_declare_vtab 0 #endif #if SQLITE_OMIT_SHARED_CACHE //# define sqlite3_enable_shared_cache 0 #endif #if SQLITE_OMIT_TRACE //# define sqlite3_profile 0 //# define sqlite3_trace 0 #endif #if SQLITE_OMIT_GET_TABLE //# define //sqlite3_free_table 0 static public int sqlite3_free_table(ref string[] pazResult) { pazResult = null; return 0; } static public int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ object dummy, ref string pzErrmsg /* Error msg written here */ ) { int iDummy = 0; return sqlite3_get_table(db, zSql, ref pazResult, ref pnRow, ref iDummy, ref pzErrmsg); } //# define sqlite3_get_table 0 static public int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ ref int pnColumn, /* Number of result columns written here */ ref string pzErrmsg /* Error msg written here */ ) { return 0; } #endif #if SQLITE_OMIT_INCRBLOB //#define sqlite3_bind_zeroblob 0 //#define sqlite3_blob_bytes 0 //#define sqlite3_blob_close 0 //#define sqlite3_blob_open 0 //#define sqlite3_blob_read 0 //#define sqlite3_blob_write 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ public class sqlite3_api_routines { public sqlite3 context_db_handle; }; private static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); //{ // sqlite3_aggregate_context, #if !SQLITE_OMIT_DEPRECATED / sqlite3_aggregate_count, #else // 0, #endif // sqlite3_bind_blob, // sqlite3_bind_double, // sqlite3_bind_int, // sqlite3_bind_int64, // sqlite3_bind_null, // sqlite3_bind_parameter_count, // sqlite3_bind_parameter_index, // sqlite3_bind_parameter_name, // sqlite3_bind_text, // sqlite3_bind_text16, // sqlite3_bind_value, // sqlite3_busy_handler, // sqlite3_busy_timeout, // sqlite3_changes, // sqlite3_close, // sqlite3_collation_needed, // sqlite3_collation_needed16, // sqlite3_column_blob, // sqlite3_column_bytes, // sqlite3_column_bytes16, // sqlite3_column_count, // sqlite3_column_database_name, // sqlite3_column_database_name16, // sqlite3_column_decltype, // sqlite3_column_decltype16, // sqlite3_column_double, // sqlite3_column_int, // sqlite3_column_int64, // sqlite3_column_name, // sqlite3_column_name16, // sqlite3_column_origin_name, // sqlite3_column_origin_name16, // sqlite3_column_table_name, // sqlite3_column_table_name16, // sqlite3_column_text, // sqlite3_column_text16, // sqlite3_column_type, // sqlite3_column_value, // sqlite3_commit_hook, // sqlite3_complete, // sqlite3_complete16, // sqlite3_create_collation, // sqlite3_create_collation16, // sqlite3_create_function, // sqlite3_create_function16, // sqlite3_create_module, // sqlite3_data_count, // sqlite3_db_handle, // sqlite3_declare_vtab, // sqlite3_enable_shared_cache, // sqlite3_errcode, // sqlite3_errmsg, // sqlite3_errmsg16, // sqlite3_exec, #if !SQLITE_OMIT_DEPRECATED //sqlite3_expired, #else //0, #endif // sqlite3_finalize, // //sqlite3_free, // //sqlite3_free_table, // sqlite3_get_autocommit, // sqlite3_get_auxdata, // sqlite3_get_table, // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ // sqlite3_interrupt, // sqlite3_last_insert_rowid, // sqlite3_libversion, // sqlite3_libversion_number, // sqlite3_malloc, // sqlite3_mprintf, // sqlite3_open, // sqlite3_open16, // sqlite3_prepare, // sqlite3_prepare16, // sqlite3_profile, // sqlite3_progress_handler, // sqlite3_realloc, // sqlite3_reset, // sqlite3_result_blob, // sqlite3_result_double, // sqlite3_result_error, // sqlite3_result_error16, // sqlite3_result_int, // sqlite3_result_int64, // sqlite3_result_null, // sqlite3_result_text, // sqlite3_result_text16, // sqlite3_result_text16be, // sqlite3_result_text16le, // sqlite3_result_value, // sqlite3_rollback_hook, // sqlite3_set_authorizer, // sqlite3_set_auxdata, // sqlite3_snprintf, // sqlite3_step, // sqlite3_table_column_metadata, #if !SQLITE_OMIT_DEPRECATED //sqlite3_thread_cleanup, #else // 0, #endif // sqlite3_total_changes, // sqlite3_trace, #if !SQLITE_OMIT_DEPRECATED //sqlite3_transfer_bindings, #else // 0, #endif // sqlite3_update_hook, // sqlite3_user_data, // sqlite3_value_blob, // sqlite3_value_bytes, // sqlite3_value_bytes16, // sqlite3_value_double, // sqlite3_value_int, // sqlite3_value_int64, // sqlite3_value_numeric_type, // sqlite3_value_text, // sqlite3_value_text16, // sqlite3_value_text16be, // sqlite3_value_text16le, // sqlite3_value_type, // sqlite3_vmprintf, // /* // ** The original API set ends here. All extensions can call any // ** of the APIs above provided that the pointer is not NULL. But // ** before calling APIs that follow, extension should check the // ** sqlite3_libversion_number() to make sure they are dealing with // ** a library that is new enough to support that API. // ************************************************************************* // */ // sqlite3_overload_function, // /* // ** Added after 3.3.13 // */ // sqlite3_prepare_v2, // sqlite3_prepare16_v2, // sqlite3_clear_bindings, // /* // ** Added for 3.4.1 // */ // sqlite3_create_module_v2, // /* // ** Added for 3.5.0 // */ // sqlite3_bind_zeroblob, // sqlite3_blob_bytes, // sqlite3_blob_close, // sqlite3_blob_open, // sqlite3_blob_read, // sqlite3_blob_write, // sqlite3_create_collation_v2, // sqlite3_file_control, // sqlite3_memory_highwater, // sqlite3_memory_used, #if SQLITE_MUTEX_OMIT // 0, // 0, // 0, // 0, // 0, #else // sqlite3MutexAlloc, // sqlite3_mutex_enter, // sqlite3_mutex_free, // sqlite3_mutex_leave, // sqlite3_mutex_try, #endif // sqlite3_open_v2, // sqlite3_release_memory, // sqlite3_result_error_nomem, // sqlite3_result_error_toobig, // sqlite3_sleep, // sqlite3_soft_heap_limit, // sqlite3_vfs_find, // sqlite3_vfs_register, // sqlite3_vfs_unregister, // /* // ** Added for 3.5.8 // */ // sqlite3_threadsafe, // sqlite3_result_zeroblob, // sqlite3_result_error_code, // sqlite3_test_control, // sqlite3_randomness, // sqlite3_context_db_handle, // /* // ** Added for 3.6.0 // */ // sqlite3_extended_result_codes, // sqlite3_limit, // sqlite3_next_stmt, // sqlite3_sql, // sqlite3_status, // /* // ** Added for 3.7.4 // */ // sqlite3_backup_finish, // sqlite3_backup_init, // sqlite3_backup_pagecount, // sqlite3_backup_remaining, // sqlite3_backup_step, //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS // sqlite3_compileoption_get, // sqlite3_compileoption_used, //#else // 0, // 0, //#endif // sqlite3_create_function_v2, // sqlite3_db_config, // sqlite3_db_mutex, // sqlite3_db_status, // sqlite3_extended_errcode, // sqlite3_log, // sqlite3_soft_heap_limit64, // sqlite3_sourceid, // sqlite3_stmt_status, // sqlite3_strnicmp, //#if SQLITE_ENABLE_UNLOCK_NOTIFY // sqlite3_unlock_notify, //#else // 0, //#endif //#if !SQLITE_OMIT_WAL // sqlite3_wal_autocheckpoint, // sqlite3_wal_checkpoint, // sqlite3_wal_hook, //#else // 0, // 0, // 0, //#endif //}; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ private static int sqlite3LoadExtension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { sqlite3_vfs pVfs = db.pVfs; HANDLE handle; dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines); StringBuilder zErrmsg = new StringBuilder(100); //object aHandle; const int nMsg = 300; if (pzErrMsg != null) pzErrMsg = null; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call sqlite3_enable_load_extension() to turn on extension ** loading. Otherwise you get the following error. */ if ((db.flags & SQLITE_LoadExtension) == 0) { //if( pzErrMsg != null){ pzErrMsg = sqlite3_mprintf("not authorized"); //} return SQLITE_ERROR; } if (zProc == null || zProc == "") { zProc = "sqlite3_extension_init"; } handle = sqlite3OsDlOpen(pVfs, zFile); if (handle == IntPtr.Zero) { // if( pzErrMsg ){ pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); //if( zErrmsg !=null){ sqlite3_snprintf(nMsg, zErrmsg, "unable to open shared library [%s]", zFile); sqlite3OsDlError(pVfs, nMsg - 1, zErrmsg.ToString()); return SQLITE_ERROR; } //xInit = (int()(sqlite3*,char**,const sqlite3_api_routines)) // sqlite3OsDlSym(pVfs, handle, zProc); xInit = (dxInit)sqlite3OsDlSym(pVfs, handle, ref zProc); Debugger.Break(); // TODO -- //if( xInit==0 ){ // if( pzErrMsg ){ // *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); // if( zErrmsg ){ // sqlite3_snprintf(nMsg, zErrmsg, // "no entry point [%s] in shared library [%s]", zProc,zFile); // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); // } // sqlite3OsDlClose(pVfs, handle); // } // return SQLITE_ERROR; // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ //// if( pzErrMsg !=null){ // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); // //} // sqlite3DbFree(db,ref zErrmsg); // sqlite3OsDlClose(pVfs, ref handle); // return SQLITE_ERROR; // } // /* Append the new shared library handle to the db.aExtension array. */ // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); // if( aHandle==null ){ // return SQLITE_NOMEM; // } // if( db.nExtension>0 ){ // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); // } // sqlite3DbFree(db,ref db.aExtension); // db.aExtension = aHandle; // db.aExtension[db.nExtension++] = handle; return SQLITE_OK; } static public int sqlite3_load_extension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { int rc; sqlite3_mutex_enter(db.mutex); rc = sqlite3LoadExtension(db, zFile, zProc, ref pzErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ private static void sqlite3CloseExtensions(sqlite3 db) { int i; Debug.Assert(sqlite3_mutex_held(db.mutex)); for (i = 0; i < db.nExtension; i++) { sqlite3OsDlClose(db.pVfs, (HANDLE)db.aExtension[i]); } sqlite3DbFree(db, ref db.aExtension); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ static public int sqlite3_enable_load_extension(sqlite3 db, int onoff) { sqlite3_mutex_enter(db.mutex); if (onoff != 0) { db.flags |= SQLITE_LoadExtension; } else { db.flags &= ~SQLITE_LoadExtension; } sqlite3_mutex_leave(db.mutex); return SQLITE_OK; } #endif //* SQLITE_OMIT_LOAD_EXTENSION */ /* ** The auto-extension code added regardless of whether or not extension ** loading is supported. We need a dummy sqlite3Apis pointer for that ** code if regular extension loading is not available. This is that ** dummy pointer. */ #if SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines sqlite3Apis = null; #endif /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ //typedef struct sqlite3AutoExtList sqlite3AutoExtList; public class sqlite3AutoExtList { public int nExt = 0; /* Number of entries in aExt[] */ public dxInit[] aExt = null; /* Pointers to the extension init functions */ public sqlite3AutoExtList(int nExt, dxInit[] aExt) { this.nExt = nExt; this.aExt = aExt; } } private static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList(0, null); /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) //# define wsdAutoext x[0] #else //# define wsdAutoextInit private static void wsdAutoextInit() { } //# define wsdAutoext sqlite3Autoext private static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ private static int sqlite3_auto_extension(dxInit xInit) { int rc = SQLITE_OK; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if (rc != 0) { return rc; } else #endif { int i; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter(mutex); for (i = 0; i < wsdAutoext.nExt; i++) { if (wsdAutoext.aExt[i] == xInit) break; } //if( i==wsdAutoext.nExt ){ // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); // void **aNew; // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); // if( aNew==0 ){ // rc = SQLITE_NOMEM; // }else{ Array.Resize(ref wsdAutoext.aExt, wsdAutoext.nExt + 1);// wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; //} sqlite3_mutex_leave(mutex); Debug.Assert((rc & 0xff) == rc); return rc; } } /* ** Reset the automatic extension loading mechanism. */ private static void sqlite3_reset_auto_extension() { #if !SQLITE_OMIT_AUTOINIT if (sqlite3_initialize() == SQLITE_OK) #endif { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter(mutex); #if SQLITE_OMIT_WSD //sqlite3_free( ref wsdAutoext.aExt ); wsdAutoext.aExt = null; wsdAutoext.nExt = 0; #else //sqlite3_free( ref sqlite3Autoext.aExt ); sqlite3Autoext.aExt = null; sqlite3Autoext.nExt = 0; #endif sqlite3_mutex_leave(mutex); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ private static void sqlite3AutoLoadExtensions(sqlite3 db) { int i; bool go = true; dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines); wsdAutoextInit(); #if SQLITE_OMIT_WSD if ( wsdAutoext.nExt == 0 ) #else if (sqlite3Autoext.nExt == 0) #endif { /* Common case: early out without every having to acquire a mutex */ return; } for (i = 0; go; i++) { string zErrmsg = ""; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter(mutex); if (i >= wsdAutoext.nExt) { xInit = null; go = false; } else { xInit = (dxInit) wsdAutoext.aExt[i]; } sqlite3_mutex_leave(mutex); zErrmsg = ""; if (xInit != null && xInit(db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis) != 0) { sqlite3Error(db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg); go = false; } sqlite3DbFree(db, ref zErrmsg); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdv = Google.Cloud.Dialogflow.V2; using sys = System; namespace Google.Cloud.Dialogflow.V2 { /// <summary>Resource name for the <c>Participant</c> resource.</summary> public sealed partial class ParticipantName : gax::IResourceName, sys::IEquatable<ParticipantName> { /// <summary>The possible contents of <see cref="ParticipantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> ProjectConversationParticipant = 1, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> ProjectLocationConversationParticipant = 2, } private static gax::PathTemplate s_projectConversationParticipant = new gax::PathTemplate("projects/{project}/conversations/{conversation}/participants/{participant}"); private static gax::PathTemplate s_projectLocationConversationParticipant = new gax::PathTemplate("projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}"); /// <summary>Creates a <see cref="ParticipantName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ParticipantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ParticipantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ParticipantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ParticipantName"/> with the pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ParticipantName"/> constructed from the provided ids.</returns> public static ParticipantName FromProjectConversationParticipant(string projectId, string conversationId, string participantId) => new ParticipantName(ResourceNameType.ProjectConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Creates a <see cref="ParticipantName"/> with the pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ParticipantName"/> constructed from the provided ids.</returns> public static ParticipantName FromProjectLocationConversationParticipant(string projectId, string locationId, string conversationId, string participantId) => new ParticipantName(ResourceNameType.ProjectLocationConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string Format(string projectId, string conversationId, string participantId) => FormatProjectConversationParticipant(projectId, conversationId, participantId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string FormatProjectConversationParticipant(string projectId, string conversationId, string participantId) => s_projectConversationParticipant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string FormatProjectLocationConversationParticipant(string projectId, string locationId, string conversationId, string participantId) => s_projectLocationConversationParticipant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary>Parses the given resource name string into a new <see cref="ParticipantName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ParticipantName"/> if successful.</returns> public static ParticipantName Parse(string participantName) => Parse(participantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ParticipantName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ParticipantName"/> if successful.</returns> public static ParticipantName Parse(string participantName, bool allowUnparsed) => TryParse(participantName, allowUnparsed, out ParticipantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ParticipantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ParticipantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string participantName, out ParticipantName result) => TryParse(participantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ParticipantName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ParticipantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string participantName, bool allowUnparsed, out ParticipantName result) { gax::GaxPreconditions.CheckNotNull(participantName, nameof(participantName)); gax::TemplatedResourceName resourceName; if (s_projectConversationParticipant.TryParseName(participantName, out resourceName)) { result = FromProjectConversationParticipant(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectLocationConversationParticipant.TryParseName(participantName, out resourceName)) { result = FromProjectLocationConversationParticipant(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(participantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ParticipantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversationId = null, string locationId = null, string participantId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversationId = conversationId; LocationId = locationId; ParticipantId = participantId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ParticipantName"/> class from the component parts of pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> public ParticipantName(string projectId, string conversationId, string participantId) : this(ResourceNameType.ProjectConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Conversation</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConversationId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Participant</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ParticipantId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectConversationParticipant: return s_projectConversationParticipant.Expand(ProjectId, ConversationId, ParticipantId); case ResourceNameType.ProjectLocationConversationParticipant: return s_projectLocationConversationParticipant.Expand(ProjectId, LocationId, ConversationId, ParticipantId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ParticipantName); /// <inheritdoc/> public bool Equals(ParticipantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ParticipantName a, ParticipantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ParticipantName a, ParticipantName b) => !(a == b); } /// <summary>Resource name for the <c>Message</c> resource.</summary> public sealed partial class MessageName : gax::IResourceName, sys::IEquatable<MessageName> { /// <summary>The possible contents of <see cref="MessageName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> ProjectConversationMessage = 1, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> ProjectLocationConversationMessage = 2, } private static gax::PathTemplate s_projectConversationMessage = new gax::PathTemplate("projects/{project}/conversations/{conversation}/messages/{message}"); private static gax::PathTemplate s_projectLocationConversationMessage = new gax::PathTemplate("projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}"); /// <summary>Creates a <see cref="MessageName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="MessageName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static MessageName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MessageName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MessageName"/> with the pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MessageName"/> constructed from the provided ids.</returns> public static MessageName FromProjectConversationMessage(string projectId, string conversationId, string messageId) => new MessageName(ResourceNameType.ProjectConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Creates a <see cref="MessageName"/> with the pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MessageName"/> constructed from the provided ids.</returns> public static MessageName FromProjectLocationConversationMessage(string projectId, string locationId, string conversationId, string messageId) => new MessageName(ResourceNameType.ProjectLocationConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string Format(string projectId, string conversationId, string messageId) => FormatProjectConversationMessage(projectId, conversationId, messageId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string FormatProjectConversationMessage(string projectId, string conversationId, string messageId) => s_projectConversationMessage.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string FormatProjectLocationConversationMessage(string projectId, string locationId, string conversationId, string messageId) => s_projectLocationConversationMessage.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary>Parses the given resource name string into a new <see cref="MessageName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="MessageName"/> if successful.</returns> public static MessageName Parse(string messageName) => Parse(messageName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MessageName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="MessageName"/> if successful.</returns> public static MessageName Parse(string messageName, bool allowUnparsed) => TryParse(messageName, allowUnparsed, out MessageName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MessageName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="MessageName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string messageName, out MessageName result) => TryParse(messageName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MessageName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MessageName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string messageName, bool allowUnparsed, out MessageName result) { gax::GaxPreconditions.CheckNotNull(messageName, nameof(messageName)); gax::TemplatedResourceName resourceName; if (s_projectConversationMessage.TryParseName(messageName, out resourceName)) { result = FromProjectConversationMessage(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectLocationConversationMessage.TryParseName(messageName, out resourceName)) { result = FromProjectLocationConversationMessage(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(messageName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MessageName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversationId = null, string locationId = null, string messageId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversationId = conversationId; LocationId = locationId; MessageId = messageId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="MessageName"/> class from the component parts of pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> public MessageName(string projectId, string conversationId, string messageId) : this(ResourceNameType.ProjectConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Conversation</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConversationId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Message</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string MessageId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectConversationMessage: return s_projectConversationMessage.Expand(ProjectId, ConversationId, MessageId); case ResourceNameType.ProjectLocationConversationMessage: return s_projectLocationConversationMessage.Expand(ProjectId, LocationId, ConversationId, MessageId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as MessageName); /// <inheritdoc/> public bool Equals(MessageName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MessageName a, MessageName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MessageName a, MessageName b) => !(a == b); } public partial class Participant { /// <summary> /// <see cref="gcdv::ParticipantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ParticipantName ParticipantName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ParticipantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Message { /// <summary> /// <see cref="gcdv::MessageName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::MessageName MessageName { get => string.IsNullOrEmpty(Name) ? null : gcdv::MessageName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateParticipantRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetParticipantRequest { /// <summary> /// <see cref="gcdv::ParticipantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ParticipantName ParticipantName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ParticipantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListParticipantsRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class AnalyzeContentRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Participant"/> resource name property. /// </summary> public ParticipantName ParticipantAsParticipantName { get => string.IsNullOrEmpty(Participant) ? null : ParticipantName.Parse(Participant, allowUnparsed: true); set => Participant = value?.ToString() ?? ""; } } public partial class SuggestArticlesRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ParticipantName ParentAsParticipantName { get => string.IsNullOrEmpty(Parent) ? null : ParticipantName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } public partial class SuggestFaqAnswersRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ParticipantName ParentAsParticipantName { get => string.IsNullOrEmpty(Parent) ? null : ParticipantName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } public partial class SuggestSmartRepliesRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ParticipantName ParentAsParticipantName { get => string.IsNullOrEmpty(Parent) ? null : ParticipantName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } public partial class SuggestSmartRepliesResponse { /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } public partial class SmartReplyAnswer { /// <summary> /// <see cref="AnswerRecordName"/>-typed view over the <see cref="AnswerRecord"/> resource name property. /// </summary> public AnswerRecordName AnswerRecordAsAnswerRecordName { get => string.IsNullOrEmpty(AnswerRecord) ? null : AnswerRecordName.Parse(AnswerRecord, allowUnparsed: true); set => AnswerRecord = value?.ToString() ?? ""; } } }
#region Copyright & License // // Author: Ian Davis <ian.f.davis@gmail.com> // Copyright (c) 2007, Ian Davs // // Portions of this software were developed for NUnit. // See NOTICE.txt for more information. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ensurance.Tests { [TestClass] public class ConditionAssertTests : MessageChecker { [TestMethod] public void IsTrue() { Ensure.IsTrue( true ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsTrueFails() { expectedMessage = " Expected: True" + Environment.NewLine + " But was: False" + Environment.NewLine; Ensure.IsTrue( false ); } [TestMethod] public void IsFalse() { Ensure.IsFalse( false ); } [TestMethod] [ExpectedException( typeof (EnsuranceException) )] public void IsFalseFails() { expectedMessage = " Expected: False" + Environment.NewLine + " But was: True" + Environment.NewLine; Ensure.IsFalse( true ); } [TestMethod] public void IsNull() { Ensure.IsNull( null ); } [TestMethod] [ExpectedException( typeof (EnsuranceException) )] public void IsNullFails() { String s1 = "S1"; expectedMessage = " Expected: null" + Environment.NewLine + " But was: \"S1\"" + Environment.NewLine; Ensure.IsNull( s1 ); } [TestMethod] public void IsNotNull() { String s1 = "S1"; Ensure.IsNotNull( s1 ); } [TestMethod] [ExpectedException( typeof (EnsuranceException) )] public void IsNotNullFails() { expectedMessage = " Expected: not null" + Environment.NewLine + " But was: null" + Environment.NewLine; Ensure.IsNotNull( null ); } [TestMethod] public void IsNaN() { Ensure.IsNaN( double.NaN ); } [TestMethod] [ExpectedException( typeof (EnsuranceException) )] public void IsNaNFails() { expectedMessage = " Expected: NaN" + Environment.NewLine + " But was: 10.0d" + Environment.NewLine; Ensure.IsNaN( 10.0 ); } [TestMethod] public void IsEmpty() { Ensure.IsEmpty( "", "Failed on empty String" ); Ensure.IsEmpty( new int[0], "Failed on empty Array" ); Ensure.IsEmpty( new ArrayList(), "Failed on empty ArrayList" ); Ensure.IsEmpty( new Hashtable(), "Failed on empty Hashtable" ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsEmptyFailsOnString() { expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: \"Hi!\"" + Environment.NewLine; Ensure.IsEmpty( "Hi!" ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsEmptyFailsOnNullString() { expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: null" + Environment.NewLine; Ensure.IsEmpty( (string) null ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsEmptyFailsOnNonEmptyArray() { expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: < 1, 2, 3 >" + Environment.NewLine; Ensure.IsEmpty( new int[] {1, 2, 3} ); } [TestMethod] public void IsNotEmpty() { int[] array = new int[] {1, 2, 3}; ArrayList list = new ArrayList( array ); Hashtable hash = new Hashtable(); hash.Add( "array", array ); Ensure.IsNotEmpty( "Hi!", "Failed on String" ); Ensure.IsNotEmpty( array, "Failed on Array" ); Ensure.IsNotEmpty( list, "Failed on ArrayList" ); Ensure.IsNotEmpty( hash, "Failed on Hashtable" ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsNotEmptyFailsOnEmptyString() { expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <string.Empty>" + Environment.NewLine; Ensure.IsNotEmpty( "" ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsNotEmptyFailsOnEmptyArray() { expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; Ensure.IsNotEmpty( new int[0] ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsNotEmptyFailsOnEmptyArrayList() { expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; Ensure.IsNotEmpty( new ArrayList() ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void IsNotEmptyFailsOnEmptyHashTable() { expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; Ensure.IsNotEmpty( new Hashtable() ); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. extern alias pythontools; extern alias util; using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Automation; using System.Windows.Input; using EnvDTE; using Microsoft.PythonTools; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.UI.Python; using util::TestUtilities.UI; using static pythontools::Microsoft.PythonTools.Extensions; using Keyboard = util::TestUtilities.UI.Keyboard; using MessageBoxButton = TestUtilities.MessageBoxButton; using Mouse = util::TestUtilities.UI.Mouse; using Path = System.IO.Path; namespace PythonToolsUITests { //[TestClass] public class UITests { //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DeferredSaveWithDot(PythonVisualStudioApp app) { string fullname; // http://pytools.codeplex.com/workitem/623 // enable deferred saving on projects var props = app.Dte.get_Properties("Environment", "ProjectsAndSolution"); var prevValue = props.Item("SaveNewProjects").Value; props.Item("SaveNewProjects").Value = false; app.OnDispose(() => { props.Item("SaveNewProjects").Value = prevValue; }); using (var newProjDialog = app.FileNewProject()) { newProjDialog.FocusLanguageNode(); var consoleApp = newProjDialog.ProjectTypes.FindItem("Python Application"); consoleApp.Select(); newProjDialog.ProjectName = "Fob.Oar"; newProjDialog.OK(); } // wait for new solution to load... for (int i = 0; i < 100 && app.Dte.Solution.Projects.Count == 0; i++) { System.Threading.Thread.Sleep(1000); } using (var saveDialog = AutomationDialog.FromDte(app, "File.SaveAll")) { saveDialog.ClickButtonAndClose("Save"); } fullname = app.Dte.Solution.FullName; } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AbsolutePaths(PythonVisualStudioApp app) { var proj = File.ReadAllText(TestData.GetPath(@"TestData\AbsolutePath\AbsolutePath.pyproj")); proj = proj.Replace("[ABSPATH]", TestData.GetPath(@"TestData\AbsolutePath")); File.WriteAllText(TestData.GetPath(@"TestData\AbsolutePath\AbsolutePath.pyproj"), proj); var project = app.OpenProject(@"TestData\AbsolutePath.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; // find Program.py, send copy & paste, verify copy of file is there var programPy = window.WaitForChildOfProject(project, "Program.py"); Assert.IsNotNull(programPy); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CopyPasteFile(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\HelloWorld.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; // find Program.py, send copy & paste, verify copy of file is there var programPy = window.FindItem("Solution 'HelloWorld' (1 project)", "HelloWorld", "Program.py"); AutomationWrapper.Select(programPy); Keyboard.ControlC(); Keyboard.ControlV(); Assert.IsNotNull(window.WaitForItem("Solution 'HelloWorld' (1 project)", "HelloWorld", "Program - Copy.py")); AutomationWrapper.Select(programPy); Keyboard.ControlC(); Keyboard.ControlV(); Assert.IsNotNull(window.WaitForItem("Solution 'HelloWorld' (1 project)", "HelloWorld", "Program - Copy (2).py")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddNewFolder(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\HelloWorld.sln"); app.OpenSolutionExplorer().SelectProject(project); app.ExecuteCommand("Project.NewFolder"); Keyboard.Type("MyNewFolder"); Keyboard.PressAndRelease(Key.Enter); app.OpenSolutionExplorer().WaitForChildOfProject(project, "MyNewFolder"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddSearchPathRelativePath(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\AddSearchPaths.sln"); app.OpenSolutionExplorer().SelectProject(project); using (var dialog = SelectFolderDialog.AddFolderToSearchPath(app)) { dialog.FolderName = TestData.GetPath(@"TestData\Outlining"); dialog.SelectFolder(); } System.Threading.Thread.Sleep(1000); app.ExecuteCommand("File.SaveAll"); var text = File.ReadAllText(TestData.GetPath(@"TestData\AddSearchPaths\AddSearchPaths.pyproj")); string actual = Regex.Match(text, @"<SearchPath>.*</SearchPath>", RegexOptions.Singleline).Value; Assert.AreEqual("<SearchPath>..\\Outlining\\</SearchPath>", actual); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void LoadSearchPath(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\LoadSearchPaths.sln"); // Ensure we complete analysis. VS may crash if the invalid // path is not handled correctly. project.GetPythonProject().GetAnalyzer().WaitForCompleteAnalysis(_ => true); var tree = app.OpenSolutionExplorer(); const string sln = "Solution 'LoadSearchPaths' (1 project)"; const string proj = "LoadSearchPaths"; var sp = Strings.SearchPaths; // Entered in file as ..\AddSearchPaths\ var path1 = tree.WaitForItem(sln, proj, sp, "..\\AddSearchPaths"); Assert.IsNotNull(path1, "Could not find ..\\AddSearchPaths"); // Entered in file as ..\HelloWorld var path2 = tree.WaitForItem(sln, proj, sp, "..\\HelloWorld"); Assert.IsNotNull(path2, "Could not find ..\\HelloWorld"); // Entered in file as ..\LoadSearchPaths\NotHere\..\ - resolves to .\ var path3 = tree.WaitForItem(sln, proj, sp, "."); Assert.IsNotNull(path3, "Could not find ."); // Entered in file as .\NotHere\ var path4 = tree.WaitForItem(sln, proj, sp, "NotHere"); Assert.IsNotNull(path4, "Could not find NotHere"); Assert.AreEqual("NotHere", path4.Current.Name); AutomationWrapper.Select(path4); app.ExecuteCommand("Edit.Delete"); // should not prompt, https://pytools.codeplex.com/workitem/1233 Assert.IsNull(tree.WaitForItemRemoved(sln, proj, sp, "NotHere")); // Entered in file as Invalid*Search?Path var path5 = tree.WaitForItem(sln, proj, sp, "Invalid*Search?Path"); Assert.IsNotNull(path5, "Could not find Invalid*Search?Path"); Assert.AreEqual(path5.Current.Name, "Invalid*Search?Path"); AutomationWrapper.Select(path5); app.ExecuteCommand("Edit.Delete"); Assert.IsNull(tree.WaitForItemRemoved(sln, proj, sp, "Invalid*Search?Path")); // Ensure NotHere hasn't come back path4 = tree.WaitForItem(sln, proj, sp, "NotHere"); Assert.IsNull(path4, "NotHere came back"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddNewFolderNested(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\HelloWorld.sln"); app.OpenSolutionExplorer().SelectProject(project); app.ExecuteCommand("Project.NewFolder"); Keyboard.Type("FolderX"); Keyboard.PressAndRelease(Key.Enter); var folderNode = app.OpenSolutionExplorer().WaitForChildOfProject(project, "FolderX"); folderNode.Select(); app.ExecuteCommand("Project.NewFolder"); Keyboard.Type("FolderY"); Keyboard.PressAndRelease(Key.Enter); var innerFolderNode = app.OpenSolutionExplorer().WaitForChildOfProject(project, "FolderX", "FolderY"); innerFolderNode.Select(); var newItem = project.ProjectItems.Item("FolderX").ProjectItems.Item("FolderY").ProjectItems.AddFromFile( TestData.GetPath(@"TestData\DebuggerProject\BreakpointTest.py") ); app.OpenSolutionExplorer().WaitForChildOfProject(project, "FolderX", "FolderY", "BreakpointTest.py"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void RenameProjectToExisting(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\RenameProjectTestUI.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; // find Program.py, send copy & paste, verify copy of file is there var projectNode = window.FindItem("Solution 'RenameProjectTestUI' (1 project)", "HelloWorld"); // rename once, cancel renaming to existing file.... AutomationWrapper.Select(projectNode); Keyboard.PressAndRelease(Key.F2); System.Threading.Thread.Sleep(100); Keyboard.Type("HelloWorldExisting"); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.Enter); IntPtr dialog = app.WaitForDialog(); app.CheckMessageBox("HelloWorldExisting.pyproj", "overwrite"); // rename again, don't cancel... AutomationWrapper.Select(projectNode); Keyboard.PressAndRelease(Key.F2); System.Threading.Thread.Sleep(100); Keyboard.Type("HelloWorldExisting"); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.Enter); dialog = app.WaitForDialog(); app.CheckMessageBox(MessageBoxButton.Yes, "HelloWorldExisting.pyproj", "overwrite"); Assert.IsNotNull(window.WaitForItem("Solution 'RenameProjectTestUI' (1 project)", "HelloWorldExisting")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void RenameItemsTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\RenameItemsTestUI.sln"); var window = app.OpenSolutionExplorer(); // find Program.py, send copy & paste, verify copy of file is there var node = window.FindChildOfProject(project, "Program.py"); // rename once, cancel renaming to existing file.... node.Select(); Keyboard.PressAndRelease(Key.F2); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.A, Key.LeftCtrl); Keyboard.Type("NewName.txt"); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.Enter); IntPtr dialog = app.WaitForDialog(); app.CheckMessageBox(MessageBoxButton.Cancel, "file name extension"); // rename again, don't cancel... node.Select(); Keyboard.PressAndRelease(Key.F2); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.A, Key.LeftCtrl); Keyboard.Type("NewName.txt"); System.Threading.Thread.Sleep(100); Keyboard.PressAndRelease(Key.Enter); dialog = app.WaitForDialog(); app.CheckMessageBox(MessageBoxButton.Yes, "file name extension"); Assert.IsNotNull(window.WaitForChildOfProject(project, "NewName.txt")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CrossProjectCopy(PythonVisualStudioApp app) { app.OpenProject(@"TestData\HelloWorld2.sln", expectedProjects: 2); var proj1 = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld2"); var proj2 = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld"); var window = app.OpenSolutionExplorer(); window.FindChildOfProject(proj1, "TestFolder3").Select(); app.ExecuteCommand("Edit.Copy"); window.SelectProject(proj2); app.ExecuteCommand("Edit.Paste"); Assert.IsNotNull(window.WaitForChildOfProject(proj1, "TestFolder3")); Assert.IsNotNull(window.WaitForChildOfProject(proj2, "TestFolder3")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CrossProjectCutPaste(PythonVisualStudioApp app) { app.OpenProject(@"TestData\HelloWorld2.sln", expectedProjects: 2); var proj1 = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld2"); var proj2 = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld"); var window = app.OpenSolutionExplorer(); window.FindChildOfProject(proj1, "TestFolder2").Select(); app.ExecuteCommand("Edit.Cut"); window.SelectProject(proj2); app.ExecuteCommand("Edit.Paste"); Assert.IsNotNull(window.WaitForChildOfProject(proj2, "TestFolder2")); Assert.IsNull(window.WaitForChildOfProjectRemoved(proj1, "TestFolder2")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CutPaste(PythonVisualStudioApp app) { app.OpenProject(@"TestData\HelloWorld2.sln", expectedProjects: 2); var proj = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld2"); var window = app.OpenSolutionExplorer(); window.FindChildOfProject(proj, "TestFolder", "SubItem.py").Select(); app.ExecuteCommand("Edit.Cut"); window.SelectProject(proj); app.ExecuteCommand("Edit.Paste"); Assert.IsNotNull(window.WaitForChildOfProject(proj, "SubItem.py")); Assert.IsNull(window.WaitForChildOfProjectRemoved(proj, "TestFolder", "SubItem.py")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CopyFolderOnToSelf(PythonVisualStudioApp app) { app.OpenProject(@"TestData\HelloWorld2.sln", expectedProjects: 2); var proj = app.Dte.Solution.Projects.Cast<Project>().Single(p => p.Name == "HelloWorld2"); var window = app.OpenSolutionExplorer(); try { // Remove the destination folder in case a previous test has // created it. Directory.Delete(TestData.GetPath(@"TestData\HelloWorld2\TestFolder - Copy"), true); } catch { } window.FindChildOfProject(proj, "TestFolder").Select(); app.ExecuteCommand("Edit.Copy"); window.FindChildOfProject(proj, "TestFolder").Select(); app.ExecuteCommand("Edit.Paste"); Assert.IsNotNull(window.WaitForChildOfProject(proj, "TestFolder - Copy")); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DragDropTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\DragDropTest.sln"); var window = app.OpenSolutionExplorer(); var folder = window.FindChildOfProject(project, "TestFolder", "SubItem.py"); var point = folder.Element.GetClickablePoint(); Mouse.MoveTo(point); Mouse.Down(MouseButton.Left); point = window.FindChildOfProject(project).Element.GetClickablePoint(); Mouse.MoveTo(point); Mouse.Up(MouseButton.Left); window.WaitForChildOfProject(project, "SubItem.py"); } /// <summary> /// Drag a file onto another file in the same directory, nothing should happen /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DragDropFileToFileTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\DragDropTest.sln"); var window = app.OpenSolutionExplorer(); Mouse.MoveTo(window.FindChildOfProject(project, "TestFolder", "SubItem2.py").Element.GetClickablePoint()); Mouse.Down(MouseButton.Left); Mouse.MoveTo(window.FindChildOfProject(project, "TestFolder", "SubItem3.py").Element.GetClickablePoint()); Mouse.Up(MouseButton.Left); using (var dlg = AutomationDialog.WaitForDialog(app)) { } window.WaitForChildOfProject(project, "TestFolder", "SubItem2.py"); window.WaitForChildOfProject(project, "TestFolder", "SubItem3.py"); } /// <summary> /// Drag a file onto it's containing folder, dialog should appear /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DragDropFileToContainingFolderTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\DragDropTest.sln"); var window = app.OpenSolutionExplorer(); Mouse.MoveTo(window.FindChildOfProject(project, "TestFolder", "SubItem2.py").Element.GetClickablePoint()); Mouse.Down(MouseButton.Left); Mouse.MoveTo(window.FindChildOfProject(project, "TestFolder").Element.GetClickablePoint()); Mouse.Up(MouseButton.Left); using (var dlg = AutomationDialog.WaitForDialog(app)) { } window.WaitForChildOfProject(project, "TestFolder", "SubItem2.py"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DragLeaveTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\DragDropTest.sln"); var window = app.OpenSolutionExplorer(); // click on SubItem.py var point = window.FindChildOfProject(project, "TestFolder2", "SubItem.py").Element.GetClickablePoint(); Mouse.MoveTo(point); Mouse.Down(MouseButton.Left); // move to project and hover Mouse.MoveTo(window.FindChildOfProject(project).Element.GetClickablePoint()); System.Threading.Thread.Sleep(500); // move back and release Mouse.MoveTo(point); Mouse.Up(MouseButton.Left); window.WaitForChildOfProject(project, "TestFolder2", "SubItem.py"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DragLeaveFolderTest(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\DragDropTest.sln"); var window = app.OpenSolutionExplorer(); // click on SubItem.py var point = window.FindChildOfProject(project, "TestFolder2", "SubFolder").Element.GetClickablePoint(); Mouse.MoveTo(point); Mouse.Down(MouseButton.Left); // move to project and hover Mouse.MoveTo(window.FindChildOfProject(project).Element.GetClickablePoint()); System.Threading.Thread.Sleep(500); // move back and release Mouse.MoveTo(point); Mouse.Up(MouseButton.Left); window.WaitForChildOfProject(project, "TestFolder2", "SubFolder"); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void CopyFolderInToSelf(PythonVisualStudioApp app) { app.OpenProject(@"TestData\HelloWorld2.sln", expectedProjects: 2); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; var folder = window.FindItem("Solution 'HelloWorld2' (2 projects)", "HelloWorld2", "TestFolder"); AutomationWrapper.Select(folder); Keyboard.ControlC(); try { // Remove the destination folder in case a previous test has // created it. Directory.Delete(TestData.GetPath(@"TestData\HelloWorld2\TestFolder - Copy"), true); } catch { } var subItem = window.FindItem("Solution 'HelloWorld2' (2 projects)", "HelloWorld2", "TestFolder", "SubItem.py"); AutomationWrapper.Select(subItem); Keyboard.ControlV(); var item = window.WaitForItem("Solution 'HelloWorld2' (2 projects)", "HelloWorld2", "TestFolder - Copy", "SubItem.py"); if (item == null) { AutomationWrapper.DumpElement(window.Element); Assert.Fail("Did not find TestFolder - Copy"); } } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void MultiSelectCopyAndPaste(PythonVisualStudioApp app) { app.OpenProject(@"TestData\DebuggerProject.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; var files = new[] { "BreakAllTest.py", "BreakpointTest.py", "BreakpointTest2.py" }; bool anySelected = false; foreach (var f in files) { var node = window.FindItem("Solution 'DebuggerProject' (1 project)", "DebuggerProject", f); Assert.IsNotNull(node, f + " not found in DebuggerProject"); if (anySelected) { ((SelectionItemPattern)node.GetCurrentPattern(SelectionItemPattern.Pattern)).AddToSelection(); } else { node.Select(); anySelected = true; } } Keyboard.ControlC(); var projectNode = window.FindItem("Solution 'DebuggerProject' (1 project)", "DebuggerProject"); AutomationWrapper.Select(projectNode); Keyboard.ControlV(); foreach (var f in files.Select(f => f.Remove(f.LastIndexOf('.')) + " - Copy" + f.Substring(f.LastIndexOf('.')))) { Assert.IsNotNull( window.WaitForItem("Solution 'DebuggerProject' (1 project)", "DebuggerProject", f), f + " not found after copying"); } } /// <summary> /// http://pytools.codeplex.com/workitem/1222 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DjangoMultiSelectContextMenu(PythonVisualStudioApp app) { app.OpenProject(@"TestData\DjangoApplication.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; var manageNode = window.FindItem("Solution 'DjangoApplication' (1 project)", "DjangoApplication", "manage.py"); Mouse.MoveTo(manageNode.GetClickablePoint()); Mouse.Click(MouseButton.Left); Keyboard.Press(Key.LeftShift); Keyboard.PressAndRelease(Key.Down); Keyboard.Release(Key.LeftShift); Mouse.MoveTo(manageNode.GetClickablePoint()); Mouse.Click(MouseButton.Right); Keyboard.Type("j"); // Exclude from Project Assert.IsNull(window.WaitForItemRemoved("Solution 'DjangoApplication' (1 project)", "DjangoApplication", "manage.py")); } /// <summary> /// http://pytools.codeplex.com/workitem/1223 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void DjangoIncludeInProject(PythonVisualStudioApp app) { app.OpenProject(@"TestData\DjangoApplication.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; app.Dte.ExecuteCommand("Project.ShowAllFiles"); // start showing all var folderNode = window.WaitForItem("Solution 'DjangoApplication' (1 project)", "DjangoApplication", "Folder"); Mouse.MoveTo(folderNode.GetClickablePoint()); Mouse.Click(MouseButton.Right); Keyboard.Type("j"); // Exclude from Project app.Dte.ExecuteCommand("Project.ShowAllFiles"); // stop showing all Assert.IsNull(window.WaitForItemRemoved("Solution 'DjangoApplication' (1 project)", "DjangoApplication", "notinproject.py")); Assert.IsNotNull(window.WaitForItem("Solution 'DjangoApplication' (1 project)", "DjangoApplication", "Folder", "test.py")); } /// <summary> /// http://pytools.codeplex.com/workitem/1223 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddItemPreviousSiblingNotVisible(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\AddItemPreviousSiblingNotVisible.sln"); app.OpenSolutionExplorer(); var window = app.SolutionExplorerTreeView; var projectNode = window.WaitForItem("Solution 'AddItemPreviousSiblingNotVisible' (1 project)", "HelloWorld"); Assert.IsNotNull(projectNode); AutomationWrapper.Select(projectNode); var solutionService = app.GetService<IVsSolution>(typeof(SVsSolution)); Assert.IsNotNull(solutionService); IVsHierarchy selectedHierarchy; ErrorHandler.ThrowOnFailure(solutionService.GetProjectOfUniqueName(project.UniqueName, out selectedHierarchy)); Assert.IsNotNull(selectedHierarchy); HierarchyEvents events = new HierarchyEvents(); uint cookie; selectedHierarchy.AdviseHierarchyEvents(events, out cookie); using (var newItem = NewItemDialog.FromDte(app)) { var pythonFile = newItem.ProjectTypes.FindItem("Empty Python File"); pythonFile.Select(); newItem.FileName = "zmodule1.py"; newItem.OK(); } var test2 = window.WaitForItem("Solution 'AddItemPreviousSiblingNotVisible' (1 project)", "HelloWorld", "zmodule1.py"); Assert.IsNotNull(test2); selectedHierarchy.UnadviseHierarchyEvents(cookie); object caption; ErrorHandler.ThrowOnFailure( selectedHierarchy.GetProperty( events.SiblingPrev, (int)__VSHPROPID.VSHPROPID_Caption, out caption ) ); Assert.AreEqual("Program.py", caption); } /// <summary> /// https://pytools.codeplex.com/workitem/1251 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddExistingItem(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\AddExistingItem.sln"); app.OpenSolutionExplorer().SelectProject(project); using (var addExistingDlg = AddExistingItemDialog.FromDte(app)) { addExistingDlg.FileName = TestData.GetPath(@"TestData\AddExistingItem\Program2.py"); addExistingDlg.Add(); } app.OpenSolutionExplorer().WaitForChildOfProject(project, "Program2.py"); } /// <summary> /// https://pytools.codeplex.com/workitem/1221 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void AddNewFileOverwritingExistingFileNotInProject(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\AddExistingItem.sln"); app.OpenSolutionExplorer().SelectProject(project); const string filename = "Program2.py"; using (var addItemDlg = NewItemDialog.FromDte(app)) { var pythonFile = addItemDlg.ProjectTypes.FindItem("Empty Python File"); pythonFile.Select(); addItemDlg.FileName = filename; addItemDlg.OK(); } app.CheckMessageBox( MessageBoxButton.Yes, "A file named", filename, "already exists. Do you want to overwrite it?" ); app.OpenSolutionExplorer().WaitForChildOfProject(project, "Program2.py"); } class HierarchyEvents : IVsHierarchyEvents { public uint SiblingPrev; #region IVsHierarchyEvents Members public int OnInvalidateIcon(IntPtr hicon) { return VSConstants.S_OK; } public int OnInvalidateItems(uint itemidParent) { return VSConstants.S_OK; } public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) { SiblingPrev = itemidSiblingPrev; return VSConstants.S_OK; } public int OnItemDeleted(uint itemid) { return VSConstants.S_OK; } public int OnItemsAppended(uint itemidParent) { return VSConstants.S_OK; } public int OnPropertyChanged(uint itemid, int propid, uint flags) { return VSConstants.S_OK; } #endregion } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void NewProject(PythonVisualStudioApp app) { using (var newProjDialog = NewProjectDialog.FromDte(app)) { newProjDialog.FocusLanguageNode(); var consoleApp = newProjDialog.ProjectTypes.FindItem("Python Application"); consoleApp.Select(); newProjDialog.OK(); } // wait for new solution to load... for (int i = 0; i < 10 && app.Dte.Solution.Projects.Count == 0; i++) { System.Threading.Thread.Sleep(1000); } Assert.AreEqual(1, app.Dte.Solution.Projects.Count); var project = app.Dte.Solution.Projects.Item(1); Console.WriteLine("Project.Name: {0}", project.Name ?? "(null)"); var itemName = Path.ChangeExtension(project.Name, ".py"); Console.WriteLine("Expected item: {0}", itemName); Console.WriteLine("Items:"); foreach (var item in project.ProjectItems.OfType<ProjectItem>()) { Console.WriteLine(" {0}", item.Name ?? "(null)"); } Assert.IsNotNull(project.ProjectItems.Item(itemName)); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void TransferItem(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\HelloWorld.sln"); string filename, basename; int i = 0; do { i++; basename = "test" + i + " .py"; filename = Path.Combine(TestData.GetTempPath(), basename); } while (System.IO.File.Exists(filename)); System.IO.File.WriteAllText(filename, "def f(): pass"); var fileWindow = app.Dte.ItemOperations.OpenFile(filename); using (var dialog = ChooseLocationDialog.FromDte(app)) { dialog.SelectProject("HelloWorld"); dialog.OK(); } app.OpenSolutionExplorer().WaitForChildOfProject(project, basename); Assert.AreEqual(basename, fileWindow.Caption); System.IO.File.Delete(filename); } //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void SaveAs(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\SaveAsUI.sln"); var item = project.ProjectItems.Item("Program.py"); var window = item.Open(); window.Activate(); var selection = ((TextSelection)window.Selection); selection.SelectAll(); selection.Delete(); // save under a new file name using (var saveDialog = SaveDialog.FromDte(app)) { Assert.AreEqual(item.FileNames[0], saveDialog.FileName); saveDialog.FileName = "Program2.py"; saveDialog.WaitForInputIdle(); saveDialog.Save(); } Assert.IsNotNull(app.OpenSolutionExplorer().WaitForChildOfProject(project, "Program2.py")); } /// <summary> /// Verifies non-member items don't show in in find all files /// /// https://pytools.codeplex.com/workitem/1277 /// </summary> //[TestMethod, Priority(0)] [HostType("VSTestHost"), TestCategory("Installed")] public void TestSearchExcludedFiles(PythonVisualStudioApp app) { var project = app.OpenProject(@"TestData\FindInAllFiles.sln"); Assert.IsNotNull(project); var find = app.Dte.Find; find.Target = vsFindTarget.vsFindTargetSolution; find.FindWhat = "THIS_TEXT_IS_NOT_ANYWHERE_ELSE"; var results = find.Execute(); Assert.AreEqual(results, vsFindResult.vsFindResultNotFound); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CompoundEntities.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.ECS.Systems { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Slash.ECS.Components; using Slash.Reflection.Utils; public sealed class CompoundEntities<T> : IEnumerable<T> where T : class, new() { #region Fields private readonly IList<ComponentProperty> componentProperties; /// <summary> /// Existing entities. /// </summary> private readonly Dictionary<int, T> entities; private readonly EntityManager entityManager; #endregion #region Constructors and Destructors public CompoundEntities(EntityManager entityManager) { this.entityManager = entityManager; this.entities = new Dictionary<int, T>(); this.componentProperties = this.CollectComponentProperties(typeof(T)).ToList(); if (this.componentProperties != null) { entityManager.EntityInitialized += this.OnEntityInitialized; entityManager.EntityRemoved += this.OnEntityRemoved; } this.AllowEntity = (entityId, entity) => true; } #endregion #region Delegates public delegate void EntityAddedDelegate(int entityId, T entity); public delegate void EntityRemovedDelegate(int entityId, T entity); public delegate bool EntityFilter(int entityId, T entity); #endregion #region Events public event EntityAddedDelegate EntityAdded; public event EntityRemovedDelegate EntityRemoved; public EntityFilter AllowEntity { get; set; } #endregion #region Properties public IDictionary<int, T> Entities { get { return this.entities; } } #endregion #region Public Methods and Operators public T GetEntity(int entityId) { T entity; this.entities.TryGetValue(entityId, out entity); return entity; } public IEnumerator<T> GetEnumerator() { return this.entities.Values.GetEnumerator(); } #endregion #region Methods private IEnumerable<ComponentProperty> CollectComponentProperties(Type type) { // Return all property component types. var propertyInfos = ReflectionUtils.GetProperties(type); foreach (var propertyInfo in propertyInfos) { var compoundComponentAttribute = ReflectionUtils.GetAttribute<CompoundComponentAttribute>(propertyInfo); if (compoundComponentAttribute != null) { yield return new ComponentProperty(propertyInfo) { Attribute = compoundComponentAttribute }; } } // Return all field component types. var fieldInfos = ReflectionUtils.GetFields(type); foreach (var fieldInfo in fieldInfos) { var compoundComponentAttribute = ReflectionUtils.GetAttribute<CompoundComponentAttribute>(fieldInfo); if (compoundComponentAttribute != null) { yield return new ComponentProperty(fieldInfo) { Attribute = compoundComponentAttribute }; } } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } private void OnEntityAdded(int entityid, T entity) { var handler = this.EntityAdded; if (handler != null) { handler(entityid, entity); } } private void OnEntityInitialized(int entityId) { // Check if all required components present. foreach (var componentProperty in this.componentProperties) { componentProperty.RecentComponent = this.entityManager.GetComponent(entityId, componentProperty.Type); if (componentProperty.RecentComponent == null && !componentProperty.Attribute.IsOptional) { return; } } // Create compound entity. T entity = new T(); // Set components. foreach (var componentProperty in this.componentProperties) { if (componentProperty.RecentComponent != null) { componentProperty.SetValue(entity, componentProperty.RecentComponent); } } // Allow filtering. if (!this.AllowEntity(entityId, entity)) { return; } this.entities.Add(entityId, entity); // Notify listeners. this.OnEntityAdded(entityId, entity); } private void OnEntityRemoved(int entityId) { var entity = this.GetEntity(entityId); if (this.entities.Remove(entityId)) { this.OnEntityRemoved(entityId, entity); } } private void OnEntityRemoved(int entityid, T entity) { var handler = this.EntityRemoved; if (handler != null) { handler(entityid, entity); } } #endregion private class ComponentProperty { #region Fields private readonly FieldInfo fieldInfo; private readonly PropertyInfo propertyInfo; #endregion #region Constructors and Destructors public ComponentProperty(PropertyInfo propertyInfo) { this.propertyInfo = propertyInfo; this.Type = propertyInfo.PropertyType; } public ComponentProperty(FieldInfo fieldInfo) { this.fieldInfo = fieldInfo; this.Type = fieldInfo.FieldType; } #endregion #region Properties public CompoundComponentAttribute Attribute { get; set; } /// <summary> /// Most recent component created for this property. /// </summary> public object RecentComponent { get; set; } public Type Type { get; private set; } #endregion #region Public Methods and Operators public object GetValue(object obj) { if (this.propertyInfo != null) { return this.propertyInfo.GetValue(obj, null); } if (this.fieldInfo != null) { return this.fieldInfo.GetValue(obj); } return null; } public void SetValue(object obj, object value) { if (this.propertyInfo != null) { this.propertyInfo.SetValue(obj, value, null); } else if (this.fieldInfo != null) { this.fieldInfo.SetValue(obj, value); } } #endregion } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; /** Demos different path types. * This script is an example script demoing a number of different path types included in the project. * Since only the Pro version has access to many path types, it is only included in the pro version * \astarpro * */ public class PathTypesDemo : MonoBehaviour { public int activeDemo = 0; public Transform start; public Transform end; public Vector3 pathOffset; public Material lineMat; public Material squareMat; public float lineWidth; public int searchLength = 1000; public int spread = 100; public float replaceChance = 0.1F; public float aimStrength = 0; //public LineRenderer lineRenderer; private Path lastPath = null; List<GameObject> lastRender = new List<GameObject>(); List<Vector3> multipoints = new List<Vector3>(); // Update is called once per frame void Update () { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); Vector3 zeroIntersect = ray.origin + ray.direction * (ray.origin.y / -ray.direction.y); end.position = zeroIntersect; if (Input.GetKey (KeyCode.LeftShift) && Input.GetMouseButtonDown (0)) { multipoints.Add (zeroIntersect); } if (Input.GetKey (KeyCode.LeftControl) && Input.GetMouseButtonDown (0)) { multipoints.Clear (); } if (Input.GetMouseButtonDown (0) && Input.mousePosition.x > 225) { DemoPath (); } if (Input.GetMouseButton (0) && Input.GetKey (KeyCode.LeftAlt) && lastPath.IsDone()) { DemoPath (); } } /** Draw some helpful gui */ public void OnGUI () { GUILayout.BeginArea (new Rect (5,5,220,Screen.height-10),"","Box"); switch (activeDemo) { case 0: GUILayout.Label ("Basic path. Finds a path from point A to point B."); break; case 1: GUILayout.Label ("Multi Target Path. Finds a path quickly from one point to many others in a single search."); break; case 2: GUILayout.Label ("Randomized Path. Finds a path with a specified length in a random direction or biased towards some point when using a larger aim strenggth."); break; case 3: GUILayout.Label ("Flee Path. Tries to flee from a specified point. Remember to set Flee Strength!"); break; case 4: GUILayout.Label ("Finds all nodes which it costs less than some value to reach."); break; case 5: GUILayout.Label ("Searches the whole graph from a specific point. FloodPathTracer can then be used to quickly find a path to that point"); break; case 6: GUILayout.Label ("Traces a path to where the FloodPath started. Compare the claculation times for this path with ABPath!\nGreat for TD games"); break; } GUILayout.Space (5); GUILayout.Label ("Note that the paths are rendered without ANY post-processing applied, so they might look a bit edgy"); GUILayout.Space (5); GUILayout.Label ("Click anywhere to recalculate the path. Hold Alt to continuously recalculate the path while the mouse is pressed."); if (activeDemo == 2 || activeDemo == 3 || activeDemo == 4) { GUILayout.Label ("Search Distance ("+searchLength+")"); searchLength = Mathf.RoundToInt (GUILayout.HorizontalSlider (searchLength,0,100000)); } if (activeDemo == 2 || activeDemo == 3) { GUILayout.Label ("Spread ("+spread+")"); spread = Mathf.RoundToInt (GUILayout.HorizontalSlider (spread,0,40000)); GUILayout.Label ("Replace Chance ("+replaceChance+")"); replaceChance = GUILayout.HorizontalSlider (replaceChance,0,1); GUILayout.Label ((activeDemo == 2 ? "Aim strength" : "Flee strength") + " ("+aimStrength+")"); aimStrength = GUILayout.HorizontalSlider (aimStrength,0,1); } if (activeDemo == 1) { GUILayout.Label ("Hold shift and click to add new target points. Hold ctr and click to remove all target points"); } if (GUILayout.Button ("A to B path")) activeDemo = 0; if (GUILayout.Button ("Multi Target Path")) activeDemo = 1; if (GUILayout.Button ("Random Path")) activeDemo = 2; if (GUILayout.Button ("Flee path")) activeDemo = 3; if (GUILayout.Button ("Constant Path")) activeDemo = 4; if (GUILayout.Button ("Flood Path")) activeDemo = 5; if (GUILayout.Button ("Flood Path Tracer")) activeDemo = 6; GUILayout.EndArea (); } /** Get the path back */ public void OnPathComplete (Path p) { //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch (); //watch.Start (); //To prevent it from creating new GameObjects when the application is quitting when using multithreading. if(lastRender == null) return; if (p.error) { ClearPrevious (); return; } if (p.GetType () == typeof (MultiTargetPath)) { List<GameObject> unused = new List<GameObject> (lastRender); lastRender.Clear (); MultiTargetPath mp = p as MultiTargetPath; for (int i=0;i<mp.vectorPaths.Length;i++) { if (mp.vectorPaths[i] == null) continue; List<Vector3> vpath = mp.vectorPaths[i]; GameObject ob = null; if (unused.Count > i && unused[i].GetComponent<LineRenderer>() != null) { ob = unused[i]; unused.RemoveAt (i); } else { ob = new GameObject ("LineRenderer_"+i,typeof(LineRenderer)); } LineRenderer lr = ob.GetComponent<LineRenderer>(); lr.sharedMaterial = lineMat; lr.SetWidth (lineWidth,lineWidth); lr.SetVertexCount (vpath.Count); for (int j=0;j<vpath.Count;j++) { lr.SetPosition (j,vpath[j] + pathOffset); } lastRender.Add (ob); } for (int i=0;i<unused.Count;i++) { Destroy (unused[i]); } } else if (p.GetType () == typeof (ConstantPath)) { ClearPrevious (); //The following code will build a mesh with a square for each node visited ConstantPath constPath = p as ConstantPath; List<Node> nodes = constPath.allNodes; //Nodes might contain duplicates, this will get rid of them //Dictionary<Node,bool> map = new Dictionary<Node, bool>(); HashSet<Node> map = new HashSet<Node> (); Mesh mesh = new Mesh (); List<Vector3> verts = new List<Vector3>(); bool drawRaysInstead = false; //This will loop through the nodes from furthest away to nearest, not really necessary... but why not :D //Note that the reverse does not, as common sense would suggest, loop through from the closest to the furthest away //since is might contain duplicates and only the node duplicate placed at the highest index is guarenteed to be ordered correctly. for (int i=nodes.Count-1;i>=0;i--) { //Check if we have already processed this node before if (!map.Contains (nodes[i])) { Vector3 pos = (Vector3)nodes[i].position+pathOffset; if (verts.Count == 65000 && !drawRaysInstead) { Debug.LogError ("Too many nodes, rendering a mesh would throw 65K vertex error. Using Debug.DrawRay instead for the rest of the nodes"); drawRaysInstead = true; } if (drawRaysInstead) { Debug.DrawRay (pos,Vector3.up,Color.blue); continue; } map.Add (nodes[i]); //Add vertices in a square GridGraph gg = AstarData.GetGraph (nodes[i]) as GridGraph; float scale = 1F; if (gg != null) scale = gg.nodeSize; verts.Add (pos+new Vector3 (-0.5F,0,-0.5F)*scale); verts.Add (pos+new Vector3 (0.5F,0,-0.5F)*scale); verts.Add (pos+new Vector3 (-0.5F,0,0.5F)*scale); verts.Add (pos+new Vector3 (0.5F,0,0.5F)*scale); } } //Build triangles for the squares Vector3[] vs = verts.ToArray (); int[] tris = new int[(3*vs.Length)/2]; for (int i=0, j=0;i<vs.Length;j+=6, i+=4) { tris[j+0] = i; tris[j+1] = i+1; tris[j+2] = i+2; tris[j+3] = i+1; tris[j+4] = i+3; tris[j+5] = i+2; } Vector2[] uv = new Vector2[vs.Length]; //Set up some basic UV for (int i=0;i<uv.Length;i+=4) { uv[i] = new Vector2(0,0); uv[i+1] = new Vector2(1,0); uv[i+2] = new Vector2(0,1); uv[i+3] = new Vector2(1,1); } mesh.vertices = vs; mesh.triangles = tris; mesh.uv = uv; mesh.RecalculateNormals (); GameObject go = new GameObject("Mesh",typeof(MeshRenderer),typeof(MeshFilter)); MeshFilter fi = go.GetComponent<MeshFilter>(); fi.mesh = mesh; MeshRenderer re = go.GetComponent<MeshRenderer>(); re.material = squareMat; lastRender.Add (go); } else { ClearPrevious (); GameObject ob = new GameObject ("LineRenderer",typeof(LineRenderer)); LineRenderer lr = ob.GetComponent<LineRenderer>(); lr.sharedMaterial = lineMat; lr.SetWidth (lineWidth,lineWidth); lr.SetVertexCount (p.vectorPath.Count); for (int i=0;i<p.vectorPath.Count;i++) { lr.SetPosition (i,p.vectorPath[i] + pathOffset); } lastRender.Add (ob); } } /** Destroys all previous render objects */ public void ClearPrevious () { for (int i=0;i<lastRender.Count;i++) { Destroy (lastRender[i]); } lastRender.Clear (); } /** Clears renders on application quit */ public void OnApplicationQuit () { ClearPrevious (); lastRender = null; } private FloodPath lastFlood = null; /** Starts a path specified by PathTypesDemo.activeDemo */ public void DemoPath () { Path p = null; if (activeDemo == 0) { p = ABPath.Construct (start.position,end.position, OnPathComplete); } else if (activeDemo == 1) { MultiTargetPath mp = MultiTargetPath.Construct (multipoints.ToArray (), end.position, null, OnPathComplete); p = mp; } else if (activeDemo == 2) { RandomPath rp = RandomPath.Construct (start.position,searchLength, OnPathComplete); rp.spread = spread; rp.aimStrength = aimStrength; rp.aim = end.position; rp.replaceChance = replaceChance; p = rp; } else if (activeDemo == 3) { FleePath fp = FleePath.Construct (start.position, end.position, searchLength, OnPathComplete); fp.aimStrength = aimStrength; fp.replaceChance = replaceChance; fp.spread = spread; p = fp; } else if (activeDemo == 4) { ConstantPath constPath = ConstantPath.Construct (end.position, searchLength, OnPathComplete); p = constPath; } else if (activeDemo == 5) { FloodPath fp = FloodPath.Construct (end.position, null); lastFlood = fp; p = fp; } else if (activeDemo == 6 && lastFlood != null) { FloodPathTracer fp = FloodPathTracer.Construct (end.position, lastFlood, OnPathComplete); p = fp; } if (p != null) { AstarPath.StartPath (p); lastPath = p; } } }
using System; using System.Text; using System.Web; using Umbraco.Core; using Umbraco.Core.Configuration; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Web { public static class UriUtility { static string _appPath; static string _appPathPrefix; static UriUtility() { SetAppDomainAppVirtualPath(HttpRuntime.AppDomainAppVirtualPath); } // internal for unit testing only internal static void SetAppDomainAppVirtualPath(string appPath) { _appPath = appPath ?? "/"; _appPathPrefix = _appPath; if (_appPathPrefix == "/") _appPathPrefix = String.Empty; } // will be "/" or "/foo" public static string AppPath { get { return _appPath; } } // will be "" or "/foo" public static string AppPathPrefix { get { return _appPathPrefix; } } // adds the virtual directory if any // see also VirtualPathUtility.ToAbsolute public static string ToAbsolute(string url) { //return ResolveUrl(url); url = url.TrimStart('~'); return _appPathPrefix + url; } // strips the virtual directory if any // see also VirtualPathUtility.ToAppRelative public static string ToAppRelative(string virtualPath) { if (virtualPath.InvariantStartsWith(_appPathPrefix) && (virtualPath.Length == _appPathPrefix.Length || virtualPath[_appPathPrefix.Length] == '/')) virtualPath = virtualPath.Substring(_appPathPrefix.Length); if (virtualPath.Length == 0) virtualPath = "/"; return virtualPath; } // maps an internal umbraco uri to a public uri // ie with virtual directory, .aspx if required... public static Uri UriFromUmbraco(Uri uri) { var path = uri.GetSafeAbsolutePath(); if (path != "/") { if (!GlobalSettings.UseDirectoryUrls) path += ".aspx"; else if (UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash) path = path.EnsureEndsWith("/"); } path = ToAbsolute(path); return uri.Rewrite(path); } // maps a public uri to an internal umbraco uri // ie no virtual directory, no .aspx, lowercase... public static Uri UriToUmbraco(Uri uri) { // note: no need to decode uri here because we're returning a uri // so it will be re-encoded anyway var path = uri.GetSafeAbsolutePath(); path = path.ToLower(); path = ToAppRelative(path); // strip vdir if any //we need to check if the path is /default.aspx because this will occur when using a //web server pre IIS 7 when requesting the root document //if this is the case we need to change it to '/' if (path.StartsWith("/default.aspx", StringComparison.InvariantCultureIgnoreCase)) { string rempath = path.Substring("/default.aspx".Length, path.Length - "/default.aspx".Length); path = rempath.StartsWith("/") ? rempath : "/" + rempath; } if (path != "/") { path = path.TrimEnd('/'); } //if any part of the path contains .aspx, replace it with nothing. //sometimes .aspx is not at the end since we might have /home/sub1.aspx/customtemplate path = path.Replace(".aspx", ""); return uri.Rewrite(path); } #region ResolveUrl // http://www.codeproject.com/Articles/53460/ResolveUrl-in-ASP-NET-The-Perfect-Solution // note // if browsing http://example.com/sub/page1.aspx then // ResolveUrl("page2.aspx") returns "/page2.aspx" // Page.ResolveUrl("page2.aspx") returns "/sub/page2.aspx" (relative...) // public static string ResolveUrl(string relativeUrl) { if (relativeUrl == null) throw new ArgumentNullException("relativeUrl"); if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\') return relativeUrl; int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal); if (idxOfScheme != -1) { int idxOfQM = relativeUrl.IndexOf('?'); if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl; } StringBuilder sbUrl = new StringBuilder(); sbUrl.Append(_appPathPrefix); if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/'); // found question mark already? query string, do not touch! bool foundQM = false; bool foundSlash; // the latest char was a slash? if (relativeUrl.Length > 1 && relativeUrl[0] == '~' && (relativeUrl[1] == '/' || relativeUrl[1] == '\\')) { relativeUrl = relativeUrl.Substring(2); foundSlash = true; } else foundSlash = false; foreach (char c in relativeUrl) { if (!foundQM) { if (c == '?') foundQM = true; else { if (c == '/' || c == '\\') { if (foundSlash) continue; else { sbUrl.Append('/'); foundSlash = true; continue; } } else if (foundSlash) foundSlash = false; } } sbUrl.Append(c); } return sbUrl.ToString(); } #endregion #region Uri string utilities public static bool HasScheme(string uri) { return uri.IndexOf("://") > 0; } public static string StartWithScheme(string uri) { return StartWithScheme(uri, null); } public static string StartWithScheme(string uri, string scheme) { return HasScheme(uri) ? uri : String.Format("{0}://{1}", scheme ?? Uri.UriSchemeHttp, uri); } public static string EndPathWithSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.EnsureEndsWith('/'); if (pos > 0) path += uri.Substring(pos); return path; } public static string TrimPathEndSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.TrimEnd('/'); if (pos > 0) path += uri.Substring(pos); return path; } #endregion /// <summary> /// Returns an faull url with the host, port, etc... /// </summary> /// <param name="absolutePath">An absolute path (i.e. starts with a '/' )</param> /// <param name="httpContext"> </param> /// <returns></returns> /// <remarks> /// Based on http://stackoverflow.com/questions/3681052/get-absolute-url-from-relative-path-refactored-method /// </remarks> internal static Uri ToFullUrl(string absolutePath, HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (String.IsNullOrEmpty(absolutePath)) throw new ArgumentNullException("absolutePath"); if (!absolutePath.StartsWith("/")) throw new FormatException("The absolutePath specified does not start with a '/'"); return new Uri(absolutePath, UriKind.Relative).MakeAbsolute(httpContext.Request.Url); } } }
// 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.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { internal sealed class DynamicWinsockMethods { // In practice there will never be more than four of these, so its not worth a complicated // hash table structure. Store them in a list and search through it. private static readonly List<DynamicWinsockMethods> s_methodTable = new List<DynamicWinsockMethods>(); public static DynamicWinsockMethods GetMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { lock (s_methodTable) { DynamicWinsockMethods methods; for (int i = 0; i < s_methodTable.Count; i++) { methods = s_methodTable[i]; if (methods._addressFamily == addressFamily && methods._socketType == socketType && methods._protocolType == protocolType) { return methods; } } methods = new DynamicWinsockMethods(addressFamily, socketType, protocolType); s_methodTable.Add(methods); return methods; } } private readonly AddressFamily _addressFamily; private readonly SocketType _socketType; private readonly ProtocolType _protocolType; private readonly object _lockObject; private AcceptExDelegate _acceptEx; private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs; private ConnectExDelegate _connectEx; private TransmitPacketsDelegate _transmitPackets; private DisconnectExDelegate _disconnectEx; private DisconnectExDelegateBlocking _disconnectExBlocking; private WSARecvMsgDelegate _recvMsg; private WSARecvMsgDelegateBlocking _recvMsgBlocking; private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { _addressFamily = addressFamily; _socketType = socketType; _protocolType = protocolType; _lockObject = new object(); } public T GetDelegate<T>(SafeSocketHandle socketHandle) where T : class { if (typeof(T) == typeof(AcceptExDelegate)) { EnsureAcceptEx(socketHandle); Debug.Assert(_acceptEx != null); return (T)(object)_acceptEx; } else if (typeof(T) == typeof(GetAcceptExSockaddrsDelegate)) { EnsureGetAcceptExSockaddrs(socketHandle); Debug.Assert(_getAcceptExSockaddrs != null); return (T)(object)_getAcceptExSockaddrs; } else if (typeof(T) == typeof(ConnectExDelegate)) { EnsureConnectEx(socketHandle); Debug.Assert(_connectEx != null); return (T)(object)_connectEx; } else if (typeof(T) == typeof(DisconnectExDelegate)) { EnsureDisconnectEx(socketHandle); return (T)(object)_disconnectEx; } else if (typeof(T) == typeof(DisconnectExDelegateBlocking)) { EnsureDisconnectEx(socketHandle); return (T)(object)_disconnectExBlocking; } else if (typeof(T) == typeof(WSARecvMsgDelegate)) { EnsureWSARecvMsg(socketHandle); Debug.Assert(_recvMsg != null); return (T)(object)_recvMsg; } else if (typeof(T) == typeof(WSARecvMsgDelegateBlocking)) { EnsureWSARecvMsgBlocking(socketHandle); Debug.Assert(_recvMsgBlocking != null); return (T)(object)_recvMsgBlocking; } else if (typeof(T) == typeof(TransmitPacketsDelegate)) { EnsureTransmitPackets(socketHandle); Debug.Assert(_transmitPackets != null); return (T)(object)_transmitPackets; } Debug.Fail("Invalid type passed to DynamicWinsockMethods.GetDelegate"); return null; } // Private methods that actually load the function pointers. private IntPtr LoadDynamicFunctionPointer(SafeSocketHandle socketHandle, ref Guid guid) { IntPtr ptr = IntPtr.Zero; int length; SocketError errorCode; unsafe { errorCode = Interop.Winsock.WSAIoctl( socketHandle, Interop.Winsock.IoctlSocketConstants.SIOGETEXTENSIONFUNCTIONPOINTER, ref guid, sizeof(Guid), out ptr, sizeof(IntPtr), out length, IntPtr.Zero, IntPtr.Zero); } if (errorCode != SocketError.Success) { throw new SocketException(); } return ptr; } // NOTE: the volatile writes in the functions below are necessary to ensure that all writes // to the fields of the delegate instances are visible before the write to the field // that holds the reference to the delegate instance. private void EnsureAcceptEx(SafeSocketHandle socketHandle) { if (_acceptEx == null) { lock (_lockObject) { if (_acceptEx == null) { Guid guid = new Guid("{0xb5367df1,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrAcceptEx = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _acceptEx, Marshal.GetDelegateForFunctionPointer<AcceptExDelegate>(ptrAcceptEx)); } } } } private void EnsureGetAcceptExSockaddrs(SafeSocketHandle socketHandle) { if (_getAcceptExSockaddrs == null) { lock (_lockObject) { if (_getAcceptExSockaddrs == null) { Guid guid = new Guid("{0xb5367df2,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrGetAcceptExSockaddrs = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _getAcceptExSockaddrs, Marshal.GetDelegateForFunctionPointer<GetAcceptExSockaddrsDelegate>(ptrGetAcceptExSockaddrs)); } } } } private void EnsureConnectEx(SafeSocketHandle socketHandle) { if (_connectEx == null) { lock (_lockObject) { if (_connectEx == null) { Guid guid = new Guid("{0x25a207b9,0x0ddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}"); IntPtr ptrConnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _connectEx, Marshal.GetDelegateForFunctionPointer<ConnectExDelegate>(ptrConnectEx)); } } } } private void EnsureDisconnectEx(SafeSocketHandle socketHandle) { if (_disconnectEx == null) { lock (_lockObject) { if (_disconnectEx == null) { Guid guid = new Guid("{0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}"); IntPtr ptrDisconnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid); _disconnectExBlocking = Marshal.GetDelegateForFunctionPointer<DisconnectExDelegateBlocking>(ptrDisconnectEx); Volatile.Write(ref _disconnectEx, Marshal.GetDelegateForFunctionPointer<DisconnectExDelegate>(ptrDisconnectEx)); } } } } private void EnsureWSARecvMsg(SafeSocketHandle socketHandle) { if (_recvMsg == null) { lock (_lockObject) { if (_recvMsg == null) { Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}"); IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid); _recvMsgBlocking = Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg); Volatile.Write(ref _recvMsg, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegate>(ptrWSARecvMsg)); } } } } private void EnsureWSARecvMsgBlocking(SafeSocketHandle socketHandle) { if (_recvMsgBlocking == null) { lock (_lockObject) { if (_recvMsgBlocking == null) { Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}"); IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _recvMsgBlocking, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg)); } } } } private void EnsureTransmitPackets(SafeSocketHandle socketHandle) { if (_transmitPackets == null) { lock (_lockObject) { if (_transmitPackets == null) { Guid guid = new Guid("{0xd9689da0,0x1f90,0x11d3,{0x99,0x71,0x00,0xc0,0x4f,0x68,0xc8,0x76}}"); IntPtr ptrTransmitPackets = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _transmitPackets, Marshal.GetDelegateForFunctionPointer<TransmitPacketsDelegate>(ptrTransmitPackets)); } } } } } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal unsafe delegate bool AcceptExDelegate( SafeSocketHandle listenSocketHandle, SafeSocketHandle acceptSocketHandle, IntPtr buffer, int len, int localAddressLength, int remoteAddressLength, out int bytesReceived, NativeOverlapped* overlapped); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal delegate void GetAcceptExSockaddrsDelegate( IntPtr buffer, int receiveDataLength, int localAddressLength, int remoteAddressLength, out IntPtr localSocketAddress, out int localSocketAddressLength, out IntPtr remoteSocketAddress, out int remoteSocketAddressLength); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal unsafe delegate bool ConnectExDelegate( SafeSocketHandle socketHandle, IntPtr socketAddress, int socketAddressSize, IntPtr buffer, int dataLength, out int bytesSent, NativeOverlapped* overlapped); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal unsafe delegate bool DisconnectExDelegate( SafeSocketHandle socketHandle, NativeOverlapped* overlapped, int flags, int reserved); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal delegate bool DisconnectExDelegateBlocking( SafeSocketHandle socketHandle, IntPtr overlapped, int flags, int reserved); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal unsafe delegate SocketError WSARecvMsgDelegate( SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, NativeOverlapped* overlapped, IntPtr completionRoutine); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal delegate SocketError WSARecvMsgDelegateBlocking( SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine); [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] internal unsafe delegate bool TransmitPacketsDelegate( SafeSocketHandle socketHandle, IntPtr packetArray, int elementCount, int sendSize, NativeOverlapped* overlapped, TransmitFileOptions flags); }
// 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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Runtime.Caching { internal class MemoryCacheEntry : MemoryCacheKey { private readonly object _value; private readonly DateTime _utcCreated; private int _state; // expiration private DateTime _utcAbsExp; private TimeSpan _slidingExp; private ExpiresEntryRef _expiresEntryRef; private byte _expiresBucket; // index of the expiration list (bucket) // usage private readonly byte _usageBucket; // index of the usage list (== priority-1) private UsageEntryRef _usageEntryRef; // ref into the usage list private DateTime _utcLastUpdateUsage; // time we last updated usage private readonly CacheEntryRemovedCallback _callback; private SeldomUsedFields _fields; // optimization to reduce workingset when the entry hasn't any dependencies private class SeldomUsedFields { internal Collection<ChangeMonitor> _dependencies; // the entry's dependency needs to be disposed when the entry is released internal Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor> _dependents; // dependents must be notified when this entry is removed internal MemoryCache _cache; internal Tuple<MemoryCacheStore, MemoryCacheEntry> _updateSentinel; // the MemoryCacheEntry (and its associated store) of the OnUpdateSentinel for this entry, if there is one } internal object Value { get { return _value; } } internal bool HasExpiration() { return _utcAbsExp < DateTime.MaxValue; } internal DateTime UtcAbsExp { get { return _utcAbsExp; } set { _utcAbsExp = value; } } internal DateTime UtcCreated { get { return _utcCreated; } } internal ExpiresEntryRef ExpiresEntryRef { get { return _expiresEntryRef; } set { _expiresEntryRef = value; } } internal byte ExpiresBucket { get { return _expiresBucket; } set { _expiresBucket = value; } } internal bool InExpires() { return !_expiresEntryRef.IsInvalid; } internal TimeSpan SlidingExp { get { return _slidingExp; } } internal EntryState State { get { return (EntryState)_state; } set { _state = (int)value; } } internal byte UsageBucket { get { return _usageBucket; } } internal UsageEntryRef UsageEntryRef { get { return _usageEntryRef; } set { _usageEntryRef = value; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] internal DateTime UtcLastUpdateUsage { get { return _utcLastUpdateUsage; } set { _utcLastUpdateUsage = value; } } internal MemoryCacheEntry(string key, object value, DateTimeOffset absExp, TimeSpan slidingExp, CacheItemPriority priority, Collection<ChangeMonitor> dependencies, CacheEntryRemovedCallback removedCallback, MemoryCache cache) : base(key) { if (value == null) { throw new ArgumentNullException(nameof(value)); } _utcCreated = DateTime.UtcNow; _value = value; _slidingExp = slidingExp; if (_slidingExp > TimeSpan.Zero) { _utcAbsExp = _utcCreated + _slidingExp; } else { _utcAbsExp = absExp.UtcDateTime; } _expiresEntryRef = ExpiresEntryRef.INVALID; _expiresBucket = 0xff; _usageEntryRef = UsageEntryRef.INVALID; if (priority == CacheItemPriority.NotRemovable) { _usageBucket = 0xff; } else { _usageBucket = 0; } _callback = removedCallback; if (dependencies != null) { _fields = new SeldomUsedFields(); _fields._dependencies = dependencies; _fields._cache = cache; } } internal void AddDependent(MemoryCache cache, MemoryCacheEntryChangeMonitor dependent) { lock (this) { if (State > EntryState.AddedToCache) { return; } if (_fields == null) { _fields = new SeldomUsedFields(); } if (_fields._cache == null) { _fields._cache = cache; } if (_fields._dependents == null) { _fields._dependents = new Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>(); } _fields._dependents[dependent] = dependent; } } private void CallCacheEntryRemovedCallback(MemoryCache cache, CacheEntryRemovedReason reason) { if (_callback == null) { return; } CacheEntryRemovedArguments args = new CacheEntryRemovedArguments(cache, reason, new CacheItem(Key, _value)); try { _callback(args); } catch { // } } internal void CallNotifyOnChanged() { if (_fields != null && _fields._dependencies != null) { foreach (ChangeMonitor monitor in _fields._dependencies) { monitor.NotifyOnChanged(new OnChangedCallback(this.OnDependencyChanged)); } } } internal bool CompareExchangeState(EntryState value, EntryState comparand) { return (Interlocked.CompareExchange(ref _state, (int)value, (int)comparand) == (int)comparand); } // Associates this entry with an update sentinel. If this entry has a sliding expiration, we need to // touch the sentinel so that it doesn't expire. internal void ConfigureUpdateSentinel(MemoryCacheStore sentinelStore, MemoryCacheEntry sentinelEntry) { lock (this) { if (_fields == null) { _fields = new SeldomUsedFields(); } _fields._updateSentinel = Tuple.Create(sentinelStore, sentinelEntry); } } internal bool HasUsage() { return _usageBucket != 0xff; } internal bool InUsage() { return !_usageEntryRef.IsInvalid; } private void OnDependencyChanged(object state) { if (State == EntryState.AddedToCache) { _fields._cache.RemoveEntry(this.Key, this, CacheEntryRemovedReason.ChangeMonitorChanged); } } internal void Release(MemoryCache cache, CacheEntryRemovedReason reason) { State = EntryState.Closed; // Are there any cache entries that depend on this entry? // If so, we need to fire their dependencies. Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>.KeyCollection deps = null; // clone the dependents lock (this) { if (_fields != null && _fields._dependents != null && _fields._dependents.Count > 0) { deps = _fields._dependents.Keys; // set to null so RemoveDependent does not attempt to access it, since we're not // using a copy of the KeyCollection. _fields._dependents = null; Debug.Assert(_fields._dependents == null, "_fields._dependents == null"); } } if (deps != null) { foreach (MemoryCacheEntryChangeMonitor dependent in deps) { if (dependent != null) { dependent.OnCacheEntryReleased(); } } } CallCacheEntryRemovedCallback(cache, reason); // Dispose any dependencies if (_fields != null && _fields._dependencies != null) { foreach (ChangeMonitor monitor in _fields._dependencies) { monitor.Dispose(); } } } internal void RemoveDependent(MemoryCacheEntryChangeMonitor dependent) { lock (this) { if (_fields != null && _fields._dependents != null) { _fields._dependents.Remove(dependent); } } } internal void UpdateSlidingExp(DateTime utcNow, CacheExpires expires) { if (_slidingExp > TimeSpan.Zero) { DateTime utcNewExpires = utcNow + _slidingExp; if (utcNewExpires - _utcAbsExp >= CacheExpires.MIN_UPDATE_DELTA || utcNewExpires < _utcAbsExp) { expires.UtcUpdate(this, utcNewExpires); } } } internal void UpdateSlidingExpForUpdateSentinel() { // We don't need a lock to get information about the update sentinel SeldomUsedFields fields = _fields; if (fields != null) { Tuple<MemoryCacheStore, MemoryCacheEntry> sentinelInfo = fields._updateSentinel; // touch the update sentinel to keep it from expiring if (sentinelInfo != null) { MemoryCacheStore sentinelStore = sentinelInfo.Item1; MemoryCacheEntry sentinelEntry = sentinelInfo.Item2; sentinelStore.UpdateExpAndUsage(sentinelEntry, updatePerfCounters: false); // perf counters shouldn't be polluted by touching update sentinel entry } } } internal void UpdateUsage(DateTime utcNow, CacheUsage usage) { // update, but not more frequently than once per second. if (InUsage() && _utcLastUpdateUsage < utcNow - CacheUsage.CORRELATED_REQUEST_TIMEOUT) { _utcLastUpdateUsage = utcNow; usage.Update(this); if (_fields != null && _fields._dependencies != null) { foreach (ChangeMonitor monitor in _fields._dependencies) { MemoryCacheEntryChangeMonitor m = monitor as MemoryCacheEntryChangeMonitor; if (m == null) { continue; } foreach (MemoryCacheEntry e in m.Dependencies) { MemoryCacheStore store = e._fields._cache.GetStore(e); e.UpdateUsage(utcNow, store.Usage); } } } } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/11/2010 10:01:48 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Xml.Serialization; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// The Pyramid Image is designed with the expectation that the image will be too big to access all at once. /// It is stored with multiple resolutions in a "mwi or DotSpatial Image" format. It is raw bytes in argb order. /// The header content is stored in xml format. /// </summary> public class PyramidImage : ImageData { #region Private Variables private PyramidHeader _header; #endregion #region Constructors /// <summary> /// Creates a new instance of PyramidImage /// </summary> public PyramidImage() { } /// <summary> /// Creates a new PyramidImage by reading in the header content for the specified fileName. /// </summary> /// <param name="fileName"></param> public PyramidImage(string fileName) { Filename = Path.ChangeExtension(fileName, ".mwi"); if (File.Exists(fileName)) ReadHeader(fileName); } /// <summary> /// Creates a new Pyramid image, and uses the raster bounds to specify the number or rows and columns. /// No data is written at this time. /// </summary> /// <param name="fileName"></param> /// <param name="bounds"></param> public PyramidImage(string fileName, IRasterBounds bounds) { Filename = fileName; Bounds = bounds; CreateHeaders(bounds.NumRows, bounds.NumColumns, bounds.AffineCoefficients); Width = _header.ImageHeaders[0].NumColumns; Height = _header.ImageHeaders[0].NumRows; } #endregion #region Methods /// <summary> /// For big images this won't work, but this gets the 0 scale original image as a bitmap. /// </summary> /// <returns></returns> public override Bitmap GetBitmap() { PyramidImageHeader ph = Header.ImageHeaders[0]; Rectangle bnds = new Rectangle(0, 0, ph.NumColumns, ph.NumRows); byte[] data = ReadWindow(0, 0, ph.NumRows, ph.NumColumns, 0); Bitmap bmp = new Bitmap(ph.NumColumns, ph.NumRows); BitmapData bData = bmp.LockBits(bnds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(data, 0, bData.Scan0, data.Length); bmp.UnlockBits(bData); return bmp; } /// <summary> /// For big images the scale that is just one step larger than the specified window will be used. /// </summary> /// <param name="envelope"></param> /// <param name="window"></param> /// <returns></returns> public override Bitmap GetBitmap(Extent envelope, Rectangle window) { if (window.Width == 0 || window.Height == 0) return null; if (_header == null) return null; if (_header.ImageHeaders == null) return null; if (_header.ImageHeaders[0] == null) return null; Rectangle expWindow = window.ExpandBy(1); Envelope expEnvelope = envelope.ToEnvelope().Reproportion(window, expWindow); Envelope env = expEnvelope.Intersection(Bounds.Extent.ToEnvelope()); if (env == null || env.IsNull || env.Height == 0 || env.Width == 0) return null; PyramidImageHeader he = _header.ImageHeaders[0]; int scale; double cwa = expWindow.Width / expEnvelope.Width; double cha = expWindow.Height / expEnvelope.Height; for (scale = 0; scale < _header.ImageHeaders.Length; scale++) { PyramidImageHeader ph = _header.ImageHeaders[scale]; if (cwa > ph.NumColumns / Bounds.Width || cha > ph.NumRows / Bounds.Height) { if (scale > 0) scale -= 1; break; } he = ph; } RasterBounds overviewBounds = new RasterBounds(he.NumRows, he.NumColumns, he.Affine); Rectangle r = overviewBounds.CellsContainingExtent(envelope); if (r.Width == 0 || r.Height == 0) return null; byte[] vals = ReadWindow(r.Y, r.X, r.Height, r.Width, scale); Bitmap bmp = new Bitmap(r.Width, r.Height); BitmapData bData = bmp.LockBits(new Rectangle(0, 0, r.Width, r.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(vals, 0, bData.Scan0, vals.Length); bmp.UnlockBits(bData); // Use the cell coordinates to determine the affine coefficients for the cells retrieved. double[] affine = new double[6]; Array.Copy(he.Affine, affine, 6); affine[0] = affine[0] + r.X * affine[1] + r.Y * affine[2]; affine[3] = affine[3] + r.X * affine[4] + r.Y * affine[5]; if (window.Width == 0 || window.Height == 0) { return null; } Bitmap result = new Bitmap(window.Width, window.Height); Graphics g = Graphics.FromImage(result); // // Gets the scaling factor for converting from geographic to pixel coordinates double dx = (window.Width / envelope.Width); double dy = (window.Height / envelope.Height); double[] a = affine; // gets the affine scaling factors. float m11 = Convert.ToSingle(a[1] * dx); float m22 = Convert.ToSingle(a[5] * -dy); float m21 = Convert.ToSingle(a[2] * dx); float m12 = Convert.ToSingle(a[4] * -dy); float l = (float)(a[0] - .5 * (a[1] + a[2])); // Left of top left pixel float t = (float)(a[3] - .5 * (a[4] + a[5])); // top of top left pixel float xShift = (float)((l - envelope.MinX) * dx); float yShift = (float)((envelope.MaxY - t) * dy); g.Transform = new Matrix(m11, m12, m21, m22, xShift, yShift); g.PixelOffsetMode = PixelOffsetMode.Half; if (m11 > 1 || m22 > 1) { g.InterpolationMode = InterpolationMode.NearestNeighbor; } g.DrawImage(bmp, new PointF(0, 0)); bmp.Dispose(); g.Dispose(); return result; } /// <inheritdoc/> public override void Open() { ReadHeader(Filename); } /// <summary> /// Creates the headers using the existing RasterBounds for this image /// </summary> public void CreateHeaders() { CreateHeaders(Bounds.NumRows, Bounds.NumColumns, Bounds.AffineCoefficients); } /// <summary> /// This takes an original image and calculates the header content for all the lower resolution tiles. /// This does not actually write the bytes for those images. /// </summary> /// <param name="originalImage">The raster bounds for the original image.</param> public void CreateHeaders(RasterBounds originalImage) { Bounds = originalImage; CreateHeaders(originalImage.NumRows, originalImage.NumColumns, originalImage.AffineCoefficients); } /// <summary> /// This takes an original image and calculates the header content for all the lower resolution tiles. /// This does not actually write the bytes for those images. /// </summary> /// <param name="numRows">The number of rows in the original image</param> /// <param name="numColumns">The number of columns in the original image</param> /// <param name="affineCoefficients"> /// the array of doubles in ABCDEF order /// X' = A + Bx + Cy /// Y' = D + Ex + Fy /// </param> public void CreateHeaders(int numRows, int numColumns, double[] affineCoefficients) { _header = new PyramidHeader(); List<PyramidImageHeader> headers = new List<PyramidImageHeader>(); int scale = 0; long offset = 0; int nr = numRows; int nc = numColumns; while (nr > 2 && nc > 2) { PyramidImageHeader ph = new PyramidImageHeader(); ph.SetAffine(affineCoefficients, scale); ph.SetNumRows(numRows, scale); ph.SetNumColumns(numColumns, scale); ph.Offset = offset; offset += (ph.NumRows * ph.NumColumns * 4); nr = nr / 2; nc = nc / 2; scale++; headers.Add(ph); } _header.ImageHeaders = headers.ToArray(); } /// <summary> /// This assumes that the base image has been written to the file. This will now attempt to calculate /// the down-sampled images. /// </summary> public void CreatePyramids2() { double count = _header.ImageHeaders[0].NumRows; ProgressMeter pm = new ProgressMeter(ProgressHandler, "Generating Pyramids", count); int prog = 0; for (int scale = 0; scale < _header.ImageHeaders.Length - 1; scale++) { PyramidImageHeader ph = _header.ImageHeaders[scale]; int rows = ph.NumRows; int cols = ph.NumColumns; // Horizontal Blur Pass byte[] r1 = ReadWindow(0, 0, 1, cols, scale); byte[] r2 = ReadWindow(1, 0, 1, cols, scale); byte[] vals = Blur(null, r1, r2); vals = DownSample(vals); WriteWindow(vals, 0, 0, 1, cols / 2, scale + 1); prog++; pm.CurrentValue = prog; byte[] r3 = ReadWindow(2, 0, 1, cols, scale); vals = Blur(r1, r2, r3); vals = DownSample(vals); WriteWindow(vals, 1, 0, 1, cols / 2, scale + 1); prog++; pm.CurrentValue = prog; for (int row = 3; row < rows - 1; row++) { r1 = r2; r2 = r3; r3 = ReadWindow(row, 0, 1, cols, scale); prog++; pm.CurrentValue = prog; if (row % 2 == 1) continue; vals = Blur(r1, r2, r3); vals = DownSample(vals); WriteWindow(vals, row / 2 - 1, 0, 1, cols / 2, scale + 1); } if ((rows - 1) % 2 == 0) { vals = Blur(r2, r3, r2); vals = DownSample(vals); WriteWindow(vals, rows / 2 - 1, 0, 1, cols / 2, scale + 1); } prog++; pm.CurrentValue = prog; } pm.Reset(); } /// <summary> /// This assumes that the base image has been written to the file. This will now attempt to calculate /// the down-sampled images. /// </summary> public void CreatePyramids() { int w = _header.ImageHeaders[0].NumColumns; int h = _header.ImageHeaders[0].NumRows; int blockHeight = 32000000 / w; if (blockHeight > h) blockHeight = h; int numBlocks = (int)Math.Ceiling(h / (double)blockHeight); ProgressMeter pm = new ProgressMeter(ProgressHandler, "Generating Pyramids", _header.ImageHeaders.Length * numBlocks); for (int block = 0; block < numBlocks; block++) { // Normally block height except for the lowest block which is usually smaller int bh = blockHeight; if (block == numBlocks - 1) bh = h - block * blockHeight; // Read a block of bytes into a bitmap byte[] vals = ReadWindow(block * blockHeight, 0, bh, w, 0); Bitmap bmp = new Bitmap(w, bh); BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, bh), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(vals, 0, bd.Scan0, vals.Length); bmp.UnlockBits(bd); // cycle through the scales, and write the resulting smaller bitmap in an appropriate spot int sw = w; // scale width int sh = bh; // scale height int sbh = blockHeight; for (int scale = 1; scale < _header.ImageHeaders.Length - 1; scale++) { sw = sw / 2; sh = sh / 2; sbh = sbh / 2; if (sh == 0 || sw == 0) { break; } Bitmap subSet = new Bitmap(sw, sh); Graphics g = Graphics.FromImage(subSet); g.DrawImage(bmp, 0, 0, sw, sh); bmp.Dispose(); // since we keep getting smaller, don't bother keeping the big image in memory any more. bmp = subSet; // keep the most recent image alive for making even smaller subsets. g.Dispose(); BitmapData bdata = bmp.LockBits(new Rectangle(0, 0, sw, sh), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] res = new byte[sw * sh * 4]; Marshal.Copy(bdata.Scan0, res, 0, res.Length); bmp.UnlockBits(bdata); WriteWindow(res, sbh * block, 0, sh, sw, scale); pm.CurrentValue = block * _header.ImageHeaders.Length + scale; } vals = null; bmp.Dispose(); } pm.Reset(); } /// <summary> /// downsamples this row by selecting every other byte /// </summary> /// <param name="row"></param> /// <returns></returns> private static byte[] DownSample(byte[] row) { int len = row.Length / 2; byte[] result = new byte[len]; for (int col = 0; col < len / 4; col++) { result[col * 4] = row[col * 8]; // A result[col * 4 + 1] = row[col * 8 + 1]; // R result[col * 4 + 2] = row[col * 8 + 2]; // G result[col * 4 + 3] = row[col * 8 + 3]; // B } return result; } /// <summary> /// This is normally weighted for calculations for the middle row. If the top or bottom row /// is null, it will use mirror symetry by grabbing values from the other row instead. /// </summary> /// <param name="r1"></param> /// <param name="r2"></param> /// <param name="r3"></param> private static byte[] Blur(byte[] r1, byte[] r2, byte[] r3) { byte[] result = new byte[r2.Length]; byte[] top = r1; byte[] bottom = r3; double[] temp = new double[r2.Length]; if (top == null) { top = new byte[r3.Length]; Array.Copy(r3, top, r3.Length); } if (bottom == null) { bottom = new byte[r1.Length]; Array.Copy(r1, bottom, r1.Length); } // Convolve vertically first, storing output in temp for (int i = 0; i < r2.Length; i++) { temp[i] = bottom[i] * .25 + r2[i] * .5 + top[i] * .25; } // Convolve horiziontally second, only on the temp row for (int i = 0; i < r2.Length; i++) { result[i] = Blur(temp, i); } return result; } private static byte Blur(double[] values, int index) { double a = index < 4 ? values[index + 4] : values[index - 4]; double b = values[index]; double c = index < values.Length - 4 ? values[index + 4] : values[index - 4]; return (byte)(a * .25 + b * .5 + c * .25); } /// <summary> /// This writes a window of byte values (ARGB order) to the file. This assumes that the headers already exist. /// If the headers have not been created or the bounds extend beyond the header numRows and numColumns for the /// specified scale, this will throw an exception. /// </summary> /// <param name="startRow">The integer start row</param> /// <param name="startColumn">The integer start column</param> /// <param name="numRows">The integer number of rows in the window</param> /// <param name="numColumns">The integer number of columns in the window</param> /// <param name="scale">The integer scale. 0 is the original image.</param> /// <returns>The bytes created by this process</returns> /// <exception cref="PyramidUndefinedHeaderException">Occurs when attempting to write data before the headers are defined</exception> /// <exception cref="PyramidOutOfBoundsException">Occurs if the range specified is outside the bounds for the specified image scale</exception> public byte[] ReadWindow(int startRow, int startColumn, int numRows, int numColumns, int scale) { byte[] bytes = new byte[numRows * numColumns * 4]; if (_header == null || _header.ImageHeaders.Length <= scale || _header.ImageHeaders[scale] == null) { throw new PyramidUndefinedHeaderException(); } PyramidImageHeader ph = _header.ImageHeaders[scale]; if (startRow < 0 || startColumn < 0 || numRows + startRow > ph.NumRows || numColumns + startColumn > ph.NumColumns) { throw new PyramidOutOfBoundsException(); } if (startColumn == 0 && numColumns == ph.NumColumns) { // write all in one pass. FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read); fs.Seek(ph.Offset, SeekOrigin.Begin); fs.Seek((startRow * ph.NumColumns) * 4, SeekOrigin.Current); fs.Read(bytes, 0, bytes.Length); fs.Close(); } else { // write all in one pass. FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read); fs.Seek(ph.Offset, SeekOrigin.Begin); fs.Seek((startRow * ph.NumColumns) * 4, SeekOrigin.Current); int before = startColumn * 4; int after = (ph.NumColumns - (startColumn + numColumns)) * 4; for (int row = startRow; row < startRow + numRows; row++) { fs.Seek(before, SeekOrigin.Current); fs.Read(bytes, (row - startRow) * numColumns * 4, numColumns * 4); fs.Seek(after, SeekOrigin.Current); } fs.Close(); } return bytes; } /// <summary> /// This writes a window of byte values (ARGB order) to the file. This assumes that the headers already exist. /// If the headers have not been created or the bounds extend beyond the header numRows and numColumns for the /// specified scale, this will throw an exception. /// </summary> /// <param name="bytes">The byte array</param> /// <param name="startRow">The integer start row</param> /// <param name="startColumn">The integer start column</param> /// <param name="numRows">The integer number of rows in the window</param> /// <param name="numColumns">The integer number of columns in the window</param> /// <param name="scale">The integer scale. 0 is the original image.</param> /// <exception cref="PyramidUndefinedHeaderException">Occurs when attempting to write data before the headers are defined</exception> /// <exception cref="PyramidOutOfBoundsException">Occurs if the range specified is outside the bounds for the specified image scale</exception> public void WriteWindow(byte[] bytes, int startRow, int startColumn, int numRows, int numColumns, int scale) { ProgressMeter pm = new ProgressMeter(ProgressHandler, "Saving Pyramid Values", numRows); WriteWindow(bytes, startRow, startColumn, numRows, numColumns, scale, pm); pm.Reset(); } /// <summary> /// This writes a window of byte values (ARGB order) to the file. This assumes that the headers already exist. /// If the headers have not been created or the bounds extend beyond the header numRows and numColumns for the /// specified scale, this will throw an exception. /// </summary> /// <param name="bytes">The byte array</param> /// <param name="startRow">The integer start row</param> /// <param name="startColumn">The integer start column</param> /// <param name="numRows">The integer number of rows in the window</param> /// <param name="numColumns">The integer number of columns in the window</param> /// <param name="scale">The integer scale. 0 is the original image.</param> /// <param name="pm">The progress meter to advance by row. Calls Next() for each row.</param> /// <exception cref="PyramidUndefinedHeaderException">Occurs when attempting to write data before the headers are defined</exception> /// <exception cref="PyramidOutOfBoundsException">Occurs if the range specified is outside the bounds for the specified image scale</exception> public void WriteWindow(byte[] bytes, int startRow, int startColumn, int numRows, int numColumns, int scale, ProgressMeter pm) { if (_header == null || _header.ImageHeaders.Length <= scale || _header.ImageHeaders[scale] == null) { throw new PyramidUndefinedHeaderException(); } PyramidImageHeader ph = _header.ImageHeaders[scale]; if (startRow < 0 || startColumn < 0 || numRows + startRow > ph.NumRows || numColumns + startColumn > ph.NumColumns) { throw new PyramidOutOfBoundsException(); } if (startColumn == 0 && numColumns == ph.NumColumns) { // write all in one pass. FileStream fs = new FileStream(Filename, FileMode.OpenOrCreate, FileAccess.Write); fs.Seek(ph.Offset, SeekOrigin.Begin); fs.Seek((startRow * ph.NumColumns) * 4, SeekOrigin.Current); fs.Write(bytes, 0, bytes.Length); fs.Close(); } else { // write one row at a time FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Write); fs.Seek(ph.Offset, SeekOrigin.Begin); fs.Seek((startRow * ph.NumColumns) * 4, SeekOrigin.Current); int before = startColumn * 4; int after = (ph.NumColumns - (startColumn + numColumns)) * 4; for (int row = startRow; row < startRow + numRows; row++) { fs.Seek(before, SeekOrigin.Current); fs.Write(bytes, (row - startRow) * numColumns * 4, numColumns * 4); fs.Seek(after, SeekOrigin.Current); pm.Next(); } fs.Write(bytes, 0, bytes.Length); fs.Close(); } } /// <summary> /// Reads the header only from the specified mwi file. The header is in xml format. /// This is a test. We may have to jurry rig the thing to ensure it ignores the actual /// image content. /// </summary> /// <param name="fileName">Whether this is the mwi or mwh file, this reads the mwh file for the fileName.</param> public void ReadHeader(string fileName) { string header = Path.ChangeExtension(fileName, "mwh"); XmlSerializer s = new XmlSerializer(typeof(PyramidHeader)); TextReader r = new StreamReader(header); _header = (PyramidHeader)s.Deserialize(r); PyramidImageHeader ph = _header.ImageHeaders[0]; Bounds = new RasterBounds(ph.NumRows, ph.NumColumns, ph.Affine); Width = _header.ImageHeaders[0].NumColumns; Height = _header.ImageHeaders[0].NumRows; r.Close(); } /// <summary> /// Writes the header to the specified fileName. /// </summary> /// <param name="fileName">The string fileName to write the header to.</param> public void WriteHeader(string fileName) { string header = Path.ChangeExtension(fileName, "mwh"); if (File.Exists(header)) { File.Delete(header); } XmlSerializer s = new XmlSerializer(typeof(PyramidHeader)); TextWriter w = new StreamWriter(header, false); s.Serialize(w, _header); w.Close(); } /// <summary> /// Gets a block of data directly, converted into a bitmap. This is a general /// implementation, so assumes you are reading and writing to the 0 scale. /// This is always in ARGB format. /// </summary> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> /// <param name="xSize">The integer number of pixel columns in the block. </param> /// <param name="ySize">The integer number of pixel rows in the block.</param> /// <returns>A Bitmap that is xSize, ySize.</returns> public override Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize) { byte[] vals = ReadWindow(yOffset, xOffset, ySize, xSize, 0); Bitmap bmp = new Bitmap(xSize, ySize); BitmapData bd = bmp.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); for (int row = 0; row < ySize; row++) { Marshal.Copy(vals, row * xSize * 4, bd.Scan0, xSize * 4); } bmp.UnlockBits(bd); return bmp; } /// <summary> /// Saves a bitmap of data as a continuous block into the specified location. This /// is a general implementation, so assumes you are reading and writing to the 0 scale. /// This should be in ARGB pixel format or it will fail. /// </summary> /// <param name="value">The bitmap value to save.</param> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> public override void WriteBlock(Bitmap value, int xOffset, int yOffset) { byte[] vals = new byte[value.Width * value.Height * 4]; BitmapData bd = value.LockBits(new Rectangle(0, 0, value.Width, value.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); for (int row = 0; row < value.Height; row++) { Marshal.Copy(bd.Scan0, vals, row * bd.Width * 4, bd.Width * 4); } value.UnlockBits(bd); WriteWindow(vals, yOffset, xOffset, value.Height, value.Width, 0); } /// <summary> /// Updates overviews. In the case of a Pyramid image, this recalculates the values. /// </summary> public override void UpdateOverviews() { CreatePyramids(); } #endregion #region Properties /// <summary> /// Gets or sets the pyramid image header /// </summary> public PyramidHeader Header { get { return _header; } set { _header = value; } } #endregion } }
using System.Diagnostics; using System.Text; namespace Community.CsharpSqlite { using sqlite3_int64 = System.Int64; using i64 = System.Int64; using sqlite3_uint64 = System.UInt64; using u32 = System.UInt32; using System; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** Memory allocation functions used throughout sqlite. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include <stdarg.h> /* ** This routine runs when the memory allocator sees that the ** total memory allocation is about to exceed the soft heap ** limit. */ static void softHeapLimitEnforcer( object NotUsed, sqlite3_int64 NotUsed2, int allocSize ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_release_memory( allocSize ); } /* ** Set the soft heap-size limit for the library. Passing a zero or ** negative value indicates no limit. */ void sqlite3_soft_heap_limit( int n ) { int iLimit; int overage; if ( n < 0 ) { iLimit = 0; } else { iLimit = n; } #if !SQLITE_OMIT_AUTOINIT sqlite3_initialize(); #endif if ( iLimit > 0 ) { sqlite3MemoryAlarm( softHeapLimitEnforcer, 0, iLimit ); } else { sqlite3MemoryAlarm( null, null, 0 ); } overage = (int)( sqlite3_memory_used() - (i64)n ); if ( overage > 0 ) { sqlite3_release_memory( overage ); } } /* ** Attempt to release up to n bytes of non-essential memory currently ** held by SQLite. An example of non-essential memory is memory used to ** cache database pages that are not currently in use. */ static int sqlite3_release_memory( int n ) { #if SQLITE_ENABLE_MEMORY_MANAGEMENT int nRet = 0; nRet += sqlite3PcacheReleaseMemory(n-nRet); return nRet; #else UNUSED_PARAMETER( n ); return SQLITE_OK; #endif } /* ** State information local to the memory allocation subsystem. */ //static SQLITE_WSD struct Mem0Global { public class Mem0Global {/* Number of free pages for scratch and page-cache memory */ public int nScratchFree; public int nPageFree; public sqlite3_mutex mutex; /* Mutex to serialize access */ /* ** The alarm callback and its arguments. The mem0.mutex lock will ** be held while the callback is running. Recursive calls into ** the memory subsystem are allowed, but no new callbacks will be ** issued. */ public sqlite3_int64 alarmThreshold; public dxalarmCallback alarmCallback; // (*alarmCallback)(void*, sqlite3_int64,int); public object alarmArg; /* ** Pointers to the end of sqlite3GlobalConfig.pScratch and ** sqlite3GlobalConfig.pPage to a block of memory that records ** which pages are available. */ public byte[][][] aByte; public int[] aByteSize; public int[] aByte_used; public int[][] aInt; public Mem[] aMem; public BtCursor[] aBtCursor; public struct memstat { public int alloc; // # of allocation requests public int dealloc; // # of deallocations public int cached; // # of cache hits public int next; // # Next slot to use public int max; // # Max slot used } public memstat msByte; public memstat msInt; public memstat msMem; public memstat msBtCursor; public Mem0Global() { } public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int Byte_Allocation, int Int_Allocation, int Mem_Allocation, int BtCursor_Allocation ) { this.nScratchFree = nScratchFree; this.nPageFree = nPageFree; this.mutex = mutex; this.alarmThreshold = alarmThreshold; this.alarmCallback = alarmCallback; this.alarmArg = alarmArg; this.msByte.next = -1; this.msInt.next = -1; this.msMem.next = -1; this.aByteSize = new int[] { 32, 256, 1024, 8192, 0 }; this.aByte_used = new int[] { -1, -1, -1, -1, -1 }; this.aByte = new byte[this.aByteSize.Length][][]; for ( int i = 0; i < this.aByteSize.Length; i++ ) this.aByte[i] = new byte[Byte_Allocation][]; this.aInt = new int[Int_Allocation][]; this.aMem = new Mem[Mem_Allocation <= 4 ? 4 : Mem_Allocation]; this.aBtCursor = new BtCursor[BtCursor_Allocation <= 4 ? 4 : BtCursor_Allocation]; } } //mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 }; //#define mem0 GLOBAL(struct Mem0Global, mem0) static Mem0Global mem0 = new Mem0Global( ); /* ** Initialize the memory allocation subsystem. */ static int sqlite3MallocInit() { if ( sqlite3GlobalConfig.m.xMalloc == null ) { sqlite3MemSetDefault(); } mem0 = new Mem0Global(0, 0, null, 0, null, null, 1, 1, 8, 8); //memset(&mem0, 0, sizeof(mem0)); if ( sqlite3GlobalConfig.bCoreMutex ) { mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM ); } if ( sqlite3GlobalConfig.pScratch != null && sqlite3GlobalConfig.szScratch >= 100 && sqlite3GlobalConfig.nScratch >= 0 ) { int i; sqlite3GlobalConfig.szScratch = ROUNDDOWN8( sqlite3GlobalConfig.szScratch - 4 ); //mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch) // [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch]; //for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; } //mem0.nScratchFree = sqlite3GlobalConfig.nScratch; } else { sqlite3GlobalConfig.pScratch = null; sqlite3GlobalConfig.szScratch = 0; } if ( sqlite3GlobalConfig.pPage != null && sqlite3GlobalConfig.szPage >= 512 && sqlite3GlobalConfig.nPage >= 1 ) { int i; int overhead; int sz = ROUNDDOWN8( sqlite3GlobalConfig.szPage ); int n = sqlite3GlobalConfig.nPage; overhead = ( 4 * n + sz - 1 ) / sz; sqlite3GlobalConfig.nPage -= overhead; //mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage) //[sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage]; //for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; } //mem0.nPageFree = sqlite3GlobalConfig.nPage; } else { sqlite3GlobalConfig.pPage = null; sqlite3GlobalConfig.nPage = 0; } return sqlite3GlobalConfig.m.xInit( sqlite3GlobalConfig.m.pAppData ); } /* ** Deinitialize the memory allocation subsystem. */ static void sqlite3MallocEnd() { if ( sqlite3GlobalConfig.m.xShutdown != null ) { sqlite3GlobalConfig.m.xShutdown( sqlite3GlobalConfig.m.pAppData ); } mem0 = new Mem0Global();//memset(&mem0, 0, sizeof(mem0)); } /* ** Return the amount of memory currently checked out. */ static sqlite3_int64 sqlite3_memory_used() { int n = 0, mx = 0; sqlite3_int64 res; sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 ); res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */ return res; } /* ** Return the maximum amount of memory that has ever been ** checked out since either the beginning of this process ** or since the most recent reset. */ static sqlite3_int64 sqlite3_memory_highwater( int resetFlag ) { int n = 0, mx = 0; sqlite3_int64 res; sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, resetFlag ); res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */ return res; } /* ** Change the alarm callback */ static int sqlite3MemoryAlarm( dxalarmCallback xCallback, //void(*xCallback)(void pArg, sqlite3_int64 used,int N), object pArg, sqlite3_int64 iThreshold ) { sqlite3_mutex_enter( mem0.mutex ); mem0.alarmCallback = xCallback; mem0.alarmArg = pArg; mem0.alarmThreshold = iThreshold; sqlite3_mutex_leave( mem0.mutex ); return SQLITE_OK; } /* ** Trigger the alarm */ static void sqlite3MallocAlarm( int nByte ) { dxalarmCallback xCallback;//void (*xCallback)(void*,sqlite3_int64,int); sqlite3_int64 nowUsed; object pArg;// void* pArg; if ( mem0.alarmCallback == null ) return; xCallback = mem0.alarmCallback; nowUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ); pArg = mem0.alarmArg; mem0.alarmCallback = null; sqlite3_mutex_leave( mem0.mutex ); xCallback( pArg, nowUsed, nByte ); sqlite3_mutex_enter( mem0.mutex ); mem0.alarmCallback = xCallback; mem0.alarmArg = pArg; } /* ** Do a memory allocation with statistics and alarms. Assume the ** lock is already held. */ static int mallocWithAlarm( int n, ref int[] pp ) { int nFull; int[] p; Debug.Assert( sqlite3_mutex_held( mem0.mutex ) ); nFull = sqlite3GlobalConfig.m.xRoundup( n ); sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n ); if ( mem0.alarmCallback != null ) { int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ); if ( nUsed + nFull >= mem0.alarmThreshold ) { sqlite3MallocAlarm( nFull ); } } p = sqlite3GlobalConfig.m.xMallocInt( nFull ); //if( p==null && mem0.alarmCallback!=null ){ // sqlite3MallocAlarm(nFull); // p = sqlite3GlobalConfig.m.xMalloc(nFull); //} if ( p != null ) { nFull = sqlite3MallocSize( p ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull ); } pp = p; return nFull; } static int mallocWithAlarm( int n, ref byte[] pp ) { int nFull; byte[] p; Debug.Assert( sqlite3_mutex_held( mem0.mutex ) ); nFull = sqlite3GlobalConfig.m.xRoundup( n ); sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n ); if ( mem0.alarmCallback != null ) { int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ); if ( nUsed + nFull >= mem0.alarmThreshold ) { sqlite3MallocAlarm( nFull ); } } p = sqlite3GlobalConfig.m.xMalloc( nFull ); if ( p == null && mem0.alarmCallback != null ) { sqlite3MallocAlarm( nFull ); p = sqlite3GlobalConfig.m.xMalloc( nFull ); } if ( p != null ) { nFull = sqlite3MallocSize( p ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull ); } pp = p; return nFull; } /* ** Allocate memory. This routine is like sqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. */ static Mem sqlite3Malloc( Mem pMem ) { return sqlite3GlobalConfig.m.xMallocMem( pMem ); } static int[] sqlite3Malloc( int[] pInt, int n ) { int[] p = null; if ( n < 0 || n >= 0x7fffff00 ) { /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near ** this amount. The only way to reach the limit is with sqlite3_malloc() */ p = null; } else if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); mallocWithAlarm( n, ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { p = sqlite3GlobalConfig.m.xMallocInt( n ); } return p; } static byte[] sqlite3Malloc( int n ) { byte[] p = null; if ( n < 0 || n >= 0x7fffff00 ) { /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near ** this amount. The only way to reach the limit is with sqlite3_malloc() */ p = null; } else if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); mallocWithAlarm( n, ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { p = sqlite3GlobalConfig.m.xMalloc( n ); } return p; } /* ** This version of the memory allocation is for use by the application. ** First make sure the memory subsystem is initialized, then do the ** allocation. */ static byte[] sqlite3_malloc( int n ) { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return null; #endif return sqlite3Malloc( n ); } /* ** Each thread may only have a single outstanding allocation from ** xScratchMalloc(). We verify this constraint in the single-threaded ** case by setting scratchAllocOut to 1 when an allocation ** is outstanding clearing it when the allocation is freed. */ #if SQLITE_THREADSAFE && !(NDEBUG) static int scratchAllocOut = 0; #endif /* ** Allocate memory that is to be used and released right away. ** This routine is similar to alloca() in that it is not intended ** for situations where the memory might be held long-term. This ** routine is intended to get memory to old large transient data ** structures that would not normally fit on the stack of an ** embedded processor. */ static byte[][] sqlite3ScratchMalloc( byte[][] apCell, int n ) { apCell = sqlite3GlobalConfig.pScratch2; if ( apCell == null ) apCell = new byte[n < 200 ? 200 : n][]; else if ( apCell.Length < n ) Array.Resize( ref apCell, n ); sqlite3GlobalConfig.pScratch2 = null; return apCell; } static byte[] sqlite3ScratchMalloc( int n ) { byte[] p = null; Debug.Assert( n > 0 ); #if SQLITE_THREADSAFE && !(NDEBUG) /* Verify that no more than one scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ assert( scratchAllocOut==0 ); #endif if ( sqlite3GlobalConfig.szScratch < n ) { goto scratch_overflow; } else { sqlite3_mutex_enter( mem0.mutex ); if ( mem0.nScratchFree == 0 ) { sqlite3_mutex_leave( mem0.mutex ); goto scratch_overflow; } else { int i; //i = mem0.aScratchFree[--mem0.nScratchFree]; //i *= sqlite3GlobalConfig.szScratch; for ( i = 0; i < sqlite3GlobalConfig.pScratch.Length; i++ ) { if ( sqlite3GlobalConfig.pScratch[i] == null || sqlite3GlobalConfig.pScratch[i].Length < n ) continue; p = sqlite3GlobalConfig.pScratch[i];// (void*)&((char*)sqlite3GlobalConfig.pScratch)[i]; sqlite3GlobalConfig.pScratch[i] = null; break; } sqlite3_mutex_leave( mem0.mutex ); if ( p == null ) goto scratch_overflow; sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_USED, 1 ); sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n ); //assert( (((u8*)p - (u8*)0) & 7)==0 ); } } #if SQLITE_THREADSAFE && !(NDEBUG) scratchAllocOut = p!=0; #endif return p; scratch_overflow: if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n ); n = mallocWithAlarm( n, ref p ); if ( p != null ) sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, n ); sqlite3_mutex_leave( mem0.mutex ); } else { p = sqlite3GlobalConfig.m.xMalloc( n ); } #if SQLITE_THREADSAFE && !(NDEBUG) scratchAllocOut = p!=0; #endif return p; } static void sqlite3ScratchFree( byte[][] p ) { if ( p != null ) { #if SQLITE_THREADSAFE && !(NDEBUG) /* Verify that no more than one scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ assert( scratchAllocOut==1 ); scratchAllocOut = 0; #endif if ( sqlite3GlobalConfig.pScratch2 == null || sqlite3GlobalConfig.pScratch2.Length < p.Length ) { if ( sqlite3GlobalConfig.bMemstat ) { int iSize = sqlite3MallocSize( p ); sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -iSize ); sqlite3GlobalConfig.pScratch2 = p;// sqlite3GlobalConfig.m.xFree(ref p); sqlite3_mutex_leave( mem0.mutex ); } else { sqlite3GlobalConfig.pScratch2 = p;//sqlite3GlobalConfig.m.xFree(ref p); } } else // larger Scratch 2 already in use, let the C# GC handle { //int i; //i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch); //i /= sqlite3GlobalConfig.szScratch; //Debug.Assert(i >= 0 && i < sqlite3GlobalConfig.nScratch); //sqlite3_mutex_enter(mem0.mutex); //Debug.Assert(mem0.nScratchFree < (u32)sqlite3GlobalConfig.nScratch); //mem0.aScratchFree[mem0.nScratchFree++] = i; //sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); //sqlite3_mutex_leave(mem0.mutex); } p = null; } } /* ** TRUE if p is a lookaside memory allocation from db */ #if !SQLITE_OMIT_LOOKASIDE static int isLookaside(sqlite3 *db, void *p){ return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd; } #else //#define isLookaside(A,B) 0 static bool isLookaside( sqlite3 db, object p ) { return false; } #endif /* ** Return the size of a memory allocation previously obtained from ** sqlite3Malloc() or sqlite3_malloc(). */ static int sqlite3MallocSize( byte[][] p ) { return p.Length * p[0].Length; } static int sqlite3MallocSize( int[] p ) { return p.Length; } static int sqlite3MallocSize( byte[] p ) { return sqlite3GlobalConfig.m.xSize( p ); } static int sqlite3DbMallocSize( sqlite3 db, byte[] p ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); if ( isLookaside( db, p ) ) { return db.lookaside.sz; } else { return sqlite3GlobalConfig.m.xSize( p ); } } /* ** Free memory previously obtained from sqlite3Malloc(). */ static void sqlite3_free( ref byte[] p ) { if ( p == null ) return; if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) ); sqlite3GlobalConfig.m.xFree( ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { sqlite3GlobalConfig.m.xFree( ref p ); } p = null; } static void sqlite3_free( ref Mem p ) { if ( p == null ) return; if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); //sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) ); sqlite3GlobalConfig.m.xFreeMem( ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { sqlite3GlobalConfig.m.xFreeMem( ref p ); } p = null; } /* ** Free memory that might be associated with a particular database ** connection. */ static void sqlite3DbFree( sqlite3 db, ref byte[] p ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); #if !SQLITE_OMIT_LOOKASIDE if( isLookaside(db, p) ){ LookasideSlot *pBuf = (LookasideSlot*)p; pBuf.pNext = db.lookaside.pFree; db.lookaside.pFree = pBuf; db.lookaside.nOut--; }else #endif { sqlite3_free( ref p ); } } /* ** Change the size of an existing memory allocation */ static byte[] sqlite3Realloc( byte[] pOld, int nBytes ) { int nOld, nNew; byte[] pNew; if ( pOld == null ) { pOld = sqlite3Malloc( nBytes ); return pOld; } if ( nBytes < 0 ) { sqlite3_free( ref pOld ); return null; } if ( nBytes >= 0x7fffff00 ) { /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ return null; } nOld = sqlite3MallocSize( pOld ); nNew = sqlite3GlobalConfig.m.xRoundup( nBytes ); if ( nOld == nNew ) { pNew = pOld; } else if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes ); if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) + nNew - nOld >= mem0.alarmThreshold ) { sqlite3MallocAlarm( nNew - nOld ); } pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew ); if ( pNew == null && mem0.alarmCallback != null ) { sqlite3MallocAlarm( nBytes ); pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew ); } if ( pNew != null ) { nNew = sqlite3MallocSize( pNew ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nNew - nOld ); } sqlite3_mutex_leave( mem0.mutex ); } else { pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew ); } return pNew; } /* ** The public interface to sqlite3Realloc. Make sure that the memory ** subsystem is initialized prior to invoking sqliteRealloc. */ static byte[] sqlite3_realloc( byte[] pOld, int n ) { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return null; #endif return sqlite3Realloc( pOld, n ); } /* ** Allocate and zero memory. */ static byte[] sqlite3MallocZero( int n ) { byte[] p = sqlite3Malloc( n ); if ( p != null ) { Array.Clear( p, 0, n );// memset(p, 0, n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. */ static Mem sqlite3DbMallocZero( sqlite3 db, Mem m ) { return new Mem(); } static byte[] sqlite3DbMallocZero( sqlite3 db, int n ) { byte[] p = sqlite3DbMallocRaw( db, n ); if ( p != null ) { Array.Clear( p, 0, n );// memset(p, 0, n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. ** ** If db!=0 and db->mallocFailed is true (indicating a prior malloc ** failure on the same database connection) then always return 0. ** Hence for a particular database connection, once malloc starts ** failing, it fails consistently until mallocFailed is reset. ** This is an important assumption. There are many places in the ** code that do things like this: ** ** int *a = (int*)sqlite3DbMallocRaw(db, 100); ** int *b = (int*)sqlite3DbMallocRaw(db, 200); ** if( b ) a[10] = 9; ** ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed ** that all prior mallocs (ex: "a") worked too. */ static byte[] sqlite3DbMallocRaw( sqlite3 db, int n ) { byte[] p; Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); #if !SQLITE_OMIT_LOOKASIDE if( db ){ LookasideSlot *pBuf; if( db->mallocFailed ){ return 0; } if( db->lookaside.bEnabled && n<=db->lookaside.sz && (pBuf = db->lookaside.pFree)!=0 ){ db->lookaside.pFree = pBuf->pNext; db->lookaside.nOut++; if( db->lookaside.nOut>db->lookaside.mxOut ){ db->lookaside.mxOut = db->lookaside.nOut; } return (void*)pBuf; } } #else //if( db && db->mallocFailed ){ // return 0; //} #endif p = sqlite3Malloc( n ); //if( !p && db ){ // db->mallocFailed = 1; //} return p; } /* ** Resize the block of memory pointed to by p to n bytes. If the ** resize fails, set the mallocFailed flag in the connection object. */ static byte[] sqlite3DbRealloc( sqlite3 db, byte[] p, int n ) { byte[] pNew = null; Debug.Assert( db != null ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); //if( db->mallocFailed==0 ){ if ( p == null ) { return sqlite3DbMallocRaw( db, n ); } #if !SQLITE_OMIT_LOOKASIDE if( isLookaside(db, p) ){ if( n<=db->lookaside.sz ){ return p; } pNew = sqlite3DbMallocRaw(db, n); if( pNew ){ memcpy(pNew, p, db->lookaside.sz); sqlite3DbFree(db, ref p); } }else #else { { #endif pNew = sqlite3_realloc( p, n ); //if( !pNew ){ // db->mallocFailed = 1; //} } } return pNew; } /* ** Attempt to reallocate p. If the reallocation fails, then free p ** and set the mallocFailed flag in the database connection. */ static byte[] sqlite3DbReallocOrFree( sqlite3 db, byte[] p, int n ) { byte[] pNew; pNew = sqlite3DbRealloc( db, p, n ); if ( null == pNew ) { sqlite3DbFree( db, ref p ); } return pNew; } /* ** Make a copy of a string in memory obtained from sqliteMalloc(). These ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This ** is because when memory debugging is turned on, these two functions are ** called via macros that record the current file and line number in the ** ThreadData structure. */ //char *sqlite3DbStrDup(sqlite3 *db, const char *z){ // char *zNew; // size_t n; // if( z==0 ){ // return 0; // } // n = sqlite3Strlen30(z) + 1; // assert( (n&0x7fffffff)==n ); // zNew = sqlite3DbMallocRaw(db, (int)n); // if( zNew ){ // memcpy(zNew, z, n); // } // return zNew; //} //char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){ // char *zNew; // if( z==0 ){ // return 0; // } // assert( (n&0x7fffffff)==n ); // zNew = sqlite3DbMallocRaw(db, n+1); // if( zNew ){ // memcpy(zNew, z, n); // zNew[n] = 0; // } // return zNew; //} /* ** Create a string from the zFromat argument and the va_list that follows. ** Store the string in memory obtained from sqliteMalloc() and make pz ** point to that string. */ static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, params string[] ap ) { //va_list ap; string z; va_start( ap, zFormat ); z = sqlite3VMPrintf( db, zFormat, ap ); va_end( ap ); sqlite3DbFree( db, ref pz ); pz = z; } /* ** This function must be called before exiting any API function (i.e. ** returning control to the user) that has called sqlite3_malloc or ** sqlite3_realloc. ** ** The returned value is normally a copy of the second argument to this ** function. However, if a malloc() failure has occurred since the previous ** invocation SQLITE_NOMEM is returned instead. ** ** If the first argument, db, is not NULL and a malloc() error has occurred, ** then the connection error-code (the value returned by sqlite3_errcode()) ** is set to SQLITE_NOMEM. */ static int sqlite3ApiExit( int zero, int rc ) { sqlite3 db = null; return sqlite3ApiExit( db, rc ); } static int sqlite3ApiExit( sqlite3 db, int rc ) { /* If the db handle is not NULL, then we must hold the connection handle ** mutex here. Otherwise the read (and possible write) of db.mallocFailed ** is unsafe, as is the call to sqlite3Error(). */ Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); if ( /*db != null && db.mallocFailed != 0 || */ rc == SQLITE_IOERR_NOMEM ) { sqlite3Error( db, SQLITE_NOMEM, "" ); //db.mallocFailed = 0; rc = SQLITE_NOMEM; } return rc & ( db != null ? db.errMask : 0xff ); } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// An Equipment Attachment associated with a piece of Equipment. /// </summary> [MetaDataExtension (Description = "An Equipment Attachment associated with a piece of Equipment.")] public partial class EquipmentAttachment : AuditableEntity, IEquatable<EquipmentAttachment> { /// <summary> /// Default constructor, required by entity framework /// </summary> public EquipmentAttachment() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="EquipmentAttachment" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for an EquipmentAttachment (required).</param> /// <param name="Equipment">Equipment (required).</param> /// <param name="TypeName">The name of the attachment type (required).</param> /// <param name="Description">A description of the equipment attachment if the Equipment Attachment Type Name is insufficient..</param> public EquipmentAttachment(int Id, Equipment Equipment, string TypeName, string Description = null) { this.Id = Id; this.Equipment = Equipment; this.TypeName = TypeName; this.Description = Description; } /// <summary> /// A system-generated unique identifier for an EquipmentAttachment /// </summary> /// <value>A system-generated unique identifier for an EquipmentAttachment</value> [MetaDataExtension (Description = "A system-generated unique identifier for an EquipmentAttachment")] public int Id { get; set; } /// <summary> /// Gets or Sets Equipment /// </summary> public Equipment Equipment { get; set; } /// <summary> /// Foreign key for Equipment /// </summary> [ForeignKey("Equipment")] [JsonIgnore] public int? EquipmentId { get; set; } /// <summary> /// The name of the attachment type /// </summary> /// <value>The name of the attachment type</value> [MetaDataExtension (Description = "The name of the attachment type")] [MaxLength(100)] public string TypeName { get; set; } /// <summary> /// A description of the equipment attachment if the Equipment Attachment Type Name is insufficient. /// </summary> /// <value>A description of the equipment attachment if the Equipment Attachment Type Name is insufficient.</value> [MetaDataExtension (Description = "A description of the equipment attachment if the Equipment Attachment Type Name is insufficient.")] [MaxLength(2048)] public string Description { 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 EquipmentAttachment {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Equipment: ").Append(Equipment).Append("\n"); sb.Append(" TypeName: ").Append(TypeName).Append("\n"); sb.Append(" Description: ").Append(Description).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) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((EquipmentAttachment)obj); } /// <summary> /// Returns true if EquipmentAttachment instances are equal /// </summary> /// <param name="other">Instance of EquipmentAttachment to be compared</param> /// <returns>Boolean</returns> public bool Equals(EquipmentAttachment other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Equipment == other.Equipment || this.Equipment != null && this.Equipment.Equals(other.Equipment) ) && ( this.TypeName == other.TypeName || this.TypeName != null && this.TypeName.Equals(other.TypeName) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ); } /// <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 hash = hash * 59 + this.Id.GetHashCode(); if (this.Equipment != null) { hash = hash * 59 + this.Equipment.GetHashCode(); } if (this.TypeName != null) { hash = hash * 59 + this.TypeName.GetHashCode(); } if (this.Description != null) { hash = hash * 59 + this.Description.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(EquipmentAttachment left, EquipmentAttachment right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(EquipmentAttachment left, EquipmentAttachment right) { return !Equals(left, right); } #endregion Operators } }
// 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.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[]? _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; // only ever null if ctor throws /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string? _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary>cached task for read ops that complete synchronously</summary> private Task<int>? _lastSynchronouslyCompletedTask = null; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; /// <summary>Caches whether Serialization Guard has been disabled for file writes</summary> private static int s_cachedSerializationSwitch = 0; [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access) : this(handle, access, true, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) : this(handle, access, ownsHandle, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) : this(handle, access, ownsHandle, bufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync) { SafeFileHandle safeHandle = new SafeFileHandle(handle, ownsHandle: ownsHandle); try { ValidateAndInitFromHandle(safeHandle, access, bufferSize, isAsync); } catch { // We don't want to take ownership of closing passed in handles // *unless* the constructor completes successfully. GC.SuppressFinalize(safeHandle); // This would also prevent Close from being called, but is unnecessary // as we've removed the object from the finalizer queue. // // safeHandle.SetHandleAsInvalid(); throw; } // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = safeHandle; } public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } private void ValidateAndInitFromHandle(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.GetValueOrDefault()) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _exposedHandle = true; _bufferLength = bufferSize; InitFromHandle(handle, access, isAsync); } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { ValidateAndInitFromHandle(handle, access, bufferSize, isAsync); // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = handle; } public FileStream(string path, FileMode mode) : this(path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string? badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; if ((access & FileAccess.Write) == FileAccess.Write) { SerializationInfo.ThrowIfDeserializationInProgress("AllowFileWrites", ref s_cachedSerializationSwitch); } _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share, path); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null!; throw; } } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle => SafeFileHandle.DangerousGetHandle(); public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override int Read(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); return _useAsyncIO ? ReadAsyncTask(array, offset, count, CancellationToken.None).GetAwaiter().GetResult() : ReadSpan(new Span<byte>(array, offset, count)); } public override int Read(Span<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } return ReadSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Read(byte[], int, int) prior to this Read(Span<byte>) // overload being introduced. In that case, this Read(Span<byte>) overload should use the behavior // of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to // Read(byte[],int,int), which will do the right thing if we're in async mode. return base.Read(buffer); } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. // Similarly, if we weren't opened for asynchronous I/O, call to the base implementation so that // Read is invoked asynchronously. if (GetType() != typeof(FileStream) || !_useAsyncIO) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncTask(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Read. // Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.ReadAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } Task<int>? t = ReadAsyncInternal(buffer, cancellationToken, out int synchronousResult); return t != null ? new ValueTask<int>(t) : new ValueTask<int>(synchronousResult); } private Task<int> ReadAsyncTask(byte[] array, int offset, int count, CancellationToken cancellationToken) { Task<int>? t = ReadAsyncInternal(new Memory<byte>(array, offset, count), cancellationToken, out int synchronousResult); if (t == null) { t = _lastSynchronouslyCompletedTask; Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully"); if (t == null || t.Result != synchronousResult) { _lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult); } } return t; } public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); if (_useAsyncIO) { WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, count), CancellationToken.None).GetAwaiter().GetResult(); } else { WriteSpan(new ReadOnlySpan<byte>(array, offset, count)); } } public override void Write(ReadOnlySpan<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } WriteSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Write(byte[], int, int) prior to this Write(ReadOnlySpan<byte>) // overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload should use the behavior // of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to // Write(byte[],int,int), which will do the right thing if we're in async mode. base.Write(buffer); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (!_useAsyncIO || GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Write. // Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.WriteAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } return WriteAsyncInternal(buffer, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API 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 virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead => !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite => !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; /// <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(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); } /// <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(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name => _path ?? SR.IO_UnknownFileName; /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual bool IsAsync => _useAsyncIO; /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <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 && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(_fileHandle, 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>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // 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>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); 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(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; private static bool IsIoRelatedException(Exception e) => // These all derive from IOException // DirectoryNotFoundException // DriveNotFoundException // EndOfStreamException // FileLoadException // FileNotFoundException // PathTooLongException // PipeException e is IOException || // Note that SecurityException is only thrown on runtimes that support CAS // e is SecurityException || e is UnauthorizedAccessException || e is NotSupportedException || (e is ArgumentException && !(e is ArgumentNullException)); /// <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); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <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() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(_fileHandle, rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary> /// Reads a byte from the file stream. Returns the byte cast to an int /// or -1 if reading from the end of the stream. /// </summary> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); _readLength = FillReadBufferForReadByte(); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <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) { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) FlushWriteBufferForWriteByte(); // 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 (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object? state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!IsAsync) return base.BeginRead(array, offset, numBytes, callback, state); else return TaskToApm.Begin(ReadAsyncTask(array, offset, numBytes, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object? state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (!IsAsync) return base.BeginWrite(array, offset, numBytes, callback, state); else return TaskToApm.Begin(WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, numBytes), CancellationToken.None).AsTask(), callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) return base.EndRead(asyncResult); else return TaskToApm.End<int>(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) base.EndWrite(asyncResult); else TaskToApm.End(asyncResult); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Redshift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for RestoreFromClusterSnapshot operation /// </summary> public class RestoreFromClusterSnapshotResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { RestoreFromClusterSnapshotResponse response = new RestoreFromClusterSnapshotResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("RestoreFromClusterSnapshotResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, RestoreFromClusterSnapshotResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if ( context.TestExpression("Cluster", targetDepth)) { response.Cluster = ClusterUnmarshaller.Instance.Unmarshall(context); continue; } } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("AccessToSnapshotDenied")) { return new AccessToSnapshotDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterAlreadyExists")) { return new ClusterAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterParameterGroupNotFound")) { return new ClusterParameterGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterQuotaExceeded")) { return new ClusterQuotaExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterSecurityGroupNotFound")) { return new ClusterSecurityGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterSnapshotNotFound")) { return new ClusterSnapshotNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterSubnetGroupNotFoundFault")) { return new ClusterSubnetGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("HsmClientCertificateNotFoundFault")) { return new HsmClientCertificateNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("HsmConfigurationNotFoundFault")) { return new HsmConfigurationNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientClusterCapacity")) { return new InsufficientClusterCapacityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidClusterSnapshotState")) { return new InvalidClusterSnapshotStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidClusterSubnetGroupStateFault")) { return new InvalidClusterSubnetGroupStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidElasticIpFault")) { return new InvalidElasticIpException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRestore")) { return new InvalidRestoreException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidSubnet")) { return new InvalidSubnetException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidVPCNetworkStateFault")) { return new InvalidVPCNetworkStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededFault")) { return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NumberOfNodesPerClusterLimitExceeded")) { return new NumberOfNodesPerClusterLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NumberOfNodesQuotaExceeded")) { return new NumberOfNodesQuotaExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedOperation")) { return new UnauthorizedOperationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonRedshiftException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static RestoreFromClusterSnapshotResponseUnmarshaller _instance = new RestoreFromClusterSnapshotResponseUnmarshaller(); internal static RestoreFromClusterSnapshotResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static RestoreFromClusterSnapshotResponseUnmarshaller Instance { get { return _instance; } } } }
#region Copyright & license notice /* * Copyright: Copyright (c) 2007 Amazon Technologies, Inc. * License: Apache License, Version 2.0 */ #endregion using System; using System.Reflection; using System.Collections.Generic; using System.Text; using System.ComponentModel; using Amazon.WebServices.MechanicalTurk.Advanced; namespace Amazon.WebServices.MechanicalTurk { /// <summary> /// Various reflection utility functions used in the SDK /// </summary> internal class ReflectionUtil { private static int MAX_PAGE_SIZE = 100; private static string token = "lock"; private static string REQUEST_POSTFIX="Request"; private static Type[] EMPTY_PARAMS = new Type[] { }; private static Type[] SINGLE_INT_PARAM = new Type[] { typeof(System.Int32) }; private static object[] SINGLE_INT_ARGUMENT = new object[] { 1 }; private static Dictionary<Type, ReflectionCache> htTypeCache = new Dictionary<Type, ReflectionCache>(); private static Dictionary<Type, Dictionary<PropertyInfo, PropertyInfo>> htTypeCacheForOptionalProperties = new Dictionary<Type, Dictionary<PropertyInfo, PropertyInfo>>(); private static Dictionary<Type, ConstructorInfo> htCtorCache = new Dictionary<Type, ConstructorInfo>(); // cache for default constructors private static Dictionary<Type, ConstructorInfo> htCtorArrayCache = new Dictionary<Type, ConstructorInfo>(); // cache for array constructors private static Dictionary<Type, int> htPageDefaultsCache = new Dictionary<Type, int>(); // cache to store page size defaults private ReflectionUtil() { } #region Cache accessors public static ReflectionCache GetCache(Type t) { ReflectionCache ret = null; if (htTypeCache.ContainsKey(t)) { ret = htTypeCache[t]; } else { lock (token) { if (htTypeCache.ContainsKey(t)) { ret = htTypeCache[t]; } else { ret = new ReflectionCache(t); htTypeCache[t] = ret; } } } return ret; } private static ConstructorInfo GetCachedCtor(Type itemType) { ConstructorInfo ci = null; if (htCtorCache.ContainsKey(itemType)) { ci = htCtorCache[itemType]; } else { lock (token) { if (htCtorCache.ContainsKey(itemType)) { ci = htCtorCache[itemType]; } else { Type envType = itemType.Assembly.GetType(itemType.FullName.Substring(0, itemType.FullName.Length - REQUEST_POSTFIX.Length), true); // get default constructor ci = envType.GetConstructor(EMPTY_PARAMS); htCtorCache[itemType] = ci; } } } return ci; } private static ConstructorInfo GetCachedArrayCtor(Type itemType) { ConstructorInfo ciArr = null; if (htCtorArrayCache.ContainsKey(itemType)) { ciArr = htCtorArrayCache[itemType]; } else { lock (token) { if (htCtorArrayCache.ContainsKey(itemType)) { ciArr = htCtorArrayCache[itemType]; } else { Type arrType = itemType.Assembly.GetType(itemType.FullName + "[]", true); ciArr = arrType.GetConstructor(SINGLE_INT_PARAM); } } } return ciArr; } private static Dictionary<PropertyInfo, PropertyInfo> GetCachedOptionalProperties(Type itemType) { Dictionary<PropertyInfo, PropertyInfo> htOptionalProps = null; // get the optional properties for the type (If not in cache, use reflection) if (htTypeCacheForOptionalProperties.ContainsKey(itemType)) { htOptionalProps = htTypeCacheForOptionalProperties[itemType]; } else { lock (token) { if (htTypeCacheForOptionalProperties.ContainsKey(itemType)) { htOptionalProps = htTypeCacheForOptionalProperties[itemType]; } else { htOptionalProps = new Dictionary<PropertyInfo, PropertyInfo>(); // find all public properties that have the XmlIgnore attribute // set and end with "Specified" and build a map<PropertyInfo, PropertyInfo> // for it. This map will be evaluated prior to sending the request PropertyInfo[] props = itemType.GetProperties(); foreach (PropertyInfo pi in props) { if (pi.Name.EndsWith("Specified") && pi.GetCustomAttributes(typeof(System.Xml.Serialization.XmlIgnoreAttribute), false) != null) { PropertyInfo piRef = itemType.GetProperty(pi.Name.Replace("Specified", string.Empty)); if (piRef != null) { htOptionalProps[piRef] = pi; } } } // cache result for subsequent calls htTypeCacheForOptionalProperties[itemType] = htOptionalProps; } } } return htOptionalProps; } private static int GetCachedPageSize(Type itemType, object curRequestItem) { int pageSizeDefault = -1; if (htPageDefaultsCache.ContainsKey(itemType)) { pageSizeDefault = htPageDefaultsCache[itemType]; } else { lock (token) { if (htPageDefaultsCache.ContainsKey(itemType)) { pageSizeDefault = htPageDefaultsCache[itemType]; } else { if (GetCache(curRequestItem.GetType()).GetProperty("PageSize", false) == null) { // not a paged request pageSizeDefault = -1; } else { // find it scoped to the request first string defaultValue = MTurkConfig.CurrentInstance.GetConfig("MechanicalTurk.Defaults.PageSize." + itemType.Name, MTurkConfig.CurrentInstance.GetConfig("MechanicalTurk.Defaults.PageSize", null)); if (defaultValue == null) { pageSizeDefault = -1; // no client defaults configured, use service defaults } else { pageSizeDefault = int.Parse(defaultValue, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); } } if (pageSizeDefault > MAX_PAGE_SIZE) { // cap to max pageSizeDefault = MAX_PAGE_SIZE; } htPageDefaultsCache[itemType] = pageSizeDefault; } } } return pageSizeDefault; } #endregion public static object CreateInstance(Type t) { return GetCache(t).DefaultConstructor.Invoke(EMPTY_PARAMS); } public static PropertyInfo GetProperty(Type t, string propName) { return GetCache(t).GetProperty(propName); } public static object GetPropertyValue(string propName, object target) { return GetProperty(target.GetType(), propName).GetValue(target, null); } public static void SetPropertyValue(string propName, object target, object newValue) { GetProperty(target.GetType(), propName).SetValue(target, newValue, null); } public static MethodInfo GetMethod(Type t, string methodName) { return GetCache(t).GetMethod(methodName); } public static object InvokeMethod(object target, string methodName, object[] arguments) { return GetMethod(target.GetType(), methodName).Invoke(target, arguments); } /// <summary> /// Creates the MTurk request envelope for a specific itemType /// (e.g. "CreateHIT" envelope for the "CreateHITRequest" item). /// The envelope is an object that contains the common AWS properties, /// such as access key ID etc. /// </summary> public static object CreateRequestEnvelope(object requestItem) { object ret = null; ConstructorInfo ci = null; Type itemType = null; object[] requestItems = null; if (requestItem.GetType().IsArray) { requestItems = (object[])requestItem; itemType = requestItems.GetValue(0).GetType(); } else { itemType = requestItem.GetType(); } ci = GetCachedCtor(itemType); // create a new envelope instance ret = ci.Invoke(null); if (requestItems == null) { // wrap the single item in an array ConstructorInfo ciArr = GetCachedArrayCtor(itemType); // create an array for this type (length 1) requestItems = (object[])ciArr.Invoke(SINGLE_INT_ARGUMENT); // wrap item requestItems[0] = requestItem; } // set the request property for the newly created envelope ReflectionUtil.SetPropertyValue("Request", ret, requestItems); return ret; } /// <summary> /// Evaluates whether any optional properties in a request item have been set. If this /// is the case, then the correlating "Specified" property will be set to, otherwise /// the property does not get serialized in the soap request. /// /// See e.g. http://blogs.msdn.com/eugeneos/archive/2007/02/05/solving-the-disappearing-data-issue-when-using-add-web-reference-or-wsdl-exe-with-wcf-services.aspx /// for more details (using WCF is out of question for the API) /// </summary> /// <param name="request">Array of request items passed in an MTurk request /// (such as CreateItemRequest[])</param> public static void PreProcessOptionalRequestProperties(object request) { if (request != null) { Type requestType = request.GetType(); if (requestType.IsArray) { // caches the optional property to its "Specified" member (e.g. "PageSize->PageSizeSpecified") Dictionary<PropertyInfo, PropertyInfo> htOptionalProps = null; object[] requestItems = request as object[]; Type itemType = null; object curRequestItem = null; for (int i = 0; i < requestItems.Length; i++) { curRequestItem = requestItems[i]; itemType = curRequestItem.GetType(); htOptionalProps = GetCachedOptionalProperties(itemType); // evaluate optional properties and set the "Specified" property to true, // if the reference property was modified. From a client perspective, this // alleviates the pain of setting the "Specified" properties to true explicitly if (htOptionalProps.Count > 0) { PropertyInfo piSpecified = null; object valRef = null; bool valSpecified = false; Type propTypeRef = null; // flag indicating, whether the "xxxSpecified" property needs to be set bool requiresSpecSet = false; foreach (PropertyInfo piRef in htOptionalProps.Keys) { // check first, if it was explicitly set to true valSpecified = false; piSpecified = htOptionalProps[piRef]; valSpecified = (bool)piSpecified.GetValue(curRequestItem, null); if (!valSpecified) { valRef = piRef.GetValue(curRequestItem, null); if (valRef != null) { // Generally, value types require to be explicitly set, // otherwise they can'typeOfTargetObject be set back to their default // values easily (e.g. setting a value back from "true" to "false") // The following code will set the "Specified" property to true // if the reference value is different from the default value // for the reference value type requiresSpecSet = false; propTypeRef = valRef.GetType(); if (propTypeRef.IsValueType) { if (valRef is bool) { requiresSpecSet = (bool)valRef; } else if (valRef is DateTime) { requiresSpecSet = !DateTime.MinValue.Equals(valRef); } else if (propTypeRef.IsEnum) { requiresSpecSet = !(valRef.Equals(Enum.GetValues(propTypeRef).GetValue(0))); } else { requiresSpecSet = !(Decimal.Parse(valRef.ToString(), System.Globalization.CultureInfo.InvariantCulture.NumberFormat).Equals(Decimal.Zero)); } } else if (propTypeRef.IsArray) { requiresSpecSet = ((object[])valRef).Length > 0; } else if (propTypeRef.IsClass) { requiresSpecSet = true; } else { MTurkLog.Warn("Cannot preprocess optional property {0} for type {1} (No handler for property type {2}).", piRef.Name, itemType.FullName, propTypeRef.FullName); } // set the "xxSpecified" property, so the referenced member gets soap serialized if (requiresSpecSet) { piSpecified.SetValue(curRequestItem, true, null); } } } } } } } } } /// <summary> /// Sets the common list properties (pagenumber/size) to defaults if they /// were not explicitly set. Applies only to list requests /// </summary> public static void SetPagingProperties(object request) { if (request.GetType().IsArray) { object[] requestItems = (object[])request; object curRequestItem = null; Type itemType = null; for (int i = 0; i < requestItems.Length; i++) { curRequestItem = requestItems[i]; itemType = curRequestItem.GetType(); int pageSizeDefault = GetCachedPageSize(itemType, curRequestItem); if (pageSizeDefault == -1) { break; // not a paged request } else { // if it was not explicitly set, then use default size int pageSize = (int)GetPropertyValue("PageSize", curRequestItem); if (pageSize == 0) { SetPropertyValue("PageSize", curRequestItem, pageSizeDefault); int pageNum = (int)GetPropertyValue("PageNumber", curRequestItem); if (pageNum == 0) { SetPropertyValue("PageNumber", curRequestItem, 1); } } } } } } /// <summary> /// Shallow "clone": Clones the public properties from a source to a target object (of the same type) /// </summary> /// <param name="source">The source.</param> /// <param name="target">The target.</param> public static void Clone(object source, object target) { if (source == null) { throw new ArgumentException("Can't clone from null source", "source"); } if (target == null) { throw new ArgumentException("Can't clone to null target", "target"); } if (!source.GetType().Equals(target.GetType())) { throw new ArgumentException("Can't clone. Type mismatch between source and target object", "source"); } ReflectionCache cacheSrc = GetCache(source.GetType()); ReflectionCache cacheTarget = GetCache(target.GetType()); PropertyInfo[] propsSrc = cacheSrc.PublicProperties; PropertyInfo propTarget = null; foreach (PropertyInfo propSrc in propsSrc) { propTarget = cacheTarget.GetProperty(propSrc.Name); if (propTarget != null && propSrc.CanRead && propTarget.CanWrite) { propTarget.SetValue(target, propSrc.GetValue(source, null), null); } } } /// <summary> /// Returns the value for a property path. /// </summary> /// <param name="objRoot">The root object for the path. Needs to be of the cached type</param> /// <param name="propertyPath">The property path (e.g. "LocaleValue.Country")</param> /// <returns>The result for the property path or null, if any of the values in the /// path returned null</returns> public static object GetPropertyPathValue(object objRoot, string propertyPath) { if (objRoot == null) { throw new ArgumentException("Cannot resolve value for path. Root object is null.", "objRoot"); } return GetCache(objRoot.GetType()).GetPropertyPathValue(objRoot, propertyPath); } /// <summary> /// Sets the property path value. If one of the properties in the path is null, a new instance /// for its type is created. /// </summary> /// <param name="objRoot">The root object for the path. Needs to be of the cached type</param> /// <param name="propertyPath">The property path (e.g. "LocaleValue.Country")</param> /// <param name="newValueForProperty">New value for the last property in the path</param> public static void SetPropertyPathValue(object objRoot, string propertyPath, object newValueForProperty) { if (objRoot == null) { throw new ArgumentException("Cannot resolve value for path. Root object is null.", "objRoot"); } GetCache(objRoot.GetType()).SetPropertyPathValue(objRoot, propertyPath, newValueForProperty); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices{ using System; using System.Reflection; using System.Diagnostics.Contracts; [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class UnmanagedFunctionPointerAttribute : Attribute { CallingConvention m_callingConvention; public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { m_callingConvention = callingConvention; } public CallingConvention CallingConvention { get { return m_callingConvention; } } public CharSet CharSet; public bool BestFitMapping; public bool ThrowOnUnmappableChar; // This field is ignored and marshaling behaves as if it was true (for historical reasons). public bool SetLastError; // P/Invoke via delegate always preserves signature, HRESULT swapping is not supported. //public bool PreserveSig; } [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class TypeIdentifierAttribute : Attribute { public TypeIdentifierAttribute() { } public TypeIdentifierAttribute(string scope, string identifier) { Scope_ = scope; Identifier_ = identifier; } public String Scope { get { return Scope_; } } public String Identifier { get { return Identifier_; } } internal String Scope_; internal String Identifier_; } // To be used on methods that sink reverse P/Invoke calls. // This attribute is a CoreCLR-only security measure, currently ignored by the desktop CLR. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class AllowReversePInvokeCallsAttribute : Attribute { public AllowReversePInvokeCallsAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class DispIdAttribute : Attribute { internal int _val; public DispIdAttribute(int dispId) { _val = dispId; } public int Value { get { return _val; } } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ComInterfaceType { InterfaceIsDual = 0, InterfaceIsIUnknown = 1, InterfaceIsIDispatch = 2, [System.Runtime.InteropServices.ComVisible(false)] InterfaceIsIInspectable = 3, } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class InterfaceTypeAttribute : Attribute { internal ComInterfaceType _val; public InterfaceTypeAttribute(ComInterfaceType interfaceType) { _val = interfaceType; } public InterfaceTypeAttribute(short interfaceType) { _val = (ComInterfaceType)interfaceType; } public ComInterfaceType Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComDefaultInterfaceAttribute : Attribute { internal Type _val; public ComDefaultInterfaceAttribute(Type defaultInterface) { _val = defaultInterface; } public Type Value { get { return _val; } } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ClassInterfaceType { None = 0, AutoDispatch = 1, AutoDual = 2 } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ClassInterfaceAttribute : Attribute { internal ClassInterfaceType _val; public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) { _val = classInterfaceType; } public ClassInterfaceAttribute(short classInterfaceType) { _val = (ClassInterfaceType)classInterfaceType; } public ClassInterfaceType Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComVisibleAttribute : Attribute { internal bool _val; public ComVisibleAttribute(bool visibility) { _val = visibility; } public bool Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibImportClassAttribute : Attribute { internal String _importClassName; public TypeLibImportClassAttribute(Type importClass) { _importClassName = importClass.ToString(); } public String Value { get { return _importClassName; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class LCIDConversionAttribute : Attribute { internal int _val; public LCIDConversionAttribute(int lcid) { _val = lcid; } public int Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComRegisterFunctionAttribute : Attribute { public ComRegisterFunctionAttribute() { } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComUnregisterFunctionAttribute : Attribute { public ComUnregisterFunctionAttribute() { } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ProgIdAttribute : Attribute { internal String _val; public ProgIdAttribute(String progId) { _val = progId; } public String Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ImportedFromTypeLibAttribute : Attribute { internal String _val; public ImportedFromTypeLibAttribute(String tlbFile) { _val = tlbFile; } public String Value { get {return _val;} } } [Obsolete("The IDispatchImplAttribute is deprecated.", false)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum IDispatchImplType { SystemDefinedImpl = 0, InternalImpl = 1, CompatibleImpl = 2, } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false)] [Obsolete("This attribute is deprecated and will be removed in a future version.", false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class IDispatchImplAttribute : Attribute { internal IDispatchImplType _val; public IDispatchImplAttribute(IDispatchImplType implType) { _val = implType; } public IDispatchImplAttribute(short implType) { _val = (IDispatchImplType)implType; } public IDispatchImplType Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Class, Inherited = true)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComSourceInterfacesAttribute : Attribute { internal String _val; public ComSourceInterfacesAttribute(String sourceInterfaces) { _val = sourceInterfaces; } public ComSourceInterfacesAttribute(Type sourceInterface) { _val = sourceInterface.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; } public String Value { get {return _val;} } } [AttributeUsage(AttributeTargets.All, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComConversionLossAttribute : Attribute { public ComConversionLossAttribute() { } } [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibTypeFlags { FAppObject = 0x0001, FCanCreate = 0x0002, FLicensed = 0x0004, FPreDeclId = 0x0008, FHidden = 0x0010, FControl = 0x0020, FDual = 0x0040, FNonExtensible = 0x0080, FOleAutomation = 0x0100, FRestricted = 0x0200, FAggregatable = 0x0400, FReplaceable = 0x0800, FDispatchable = 0x1000, FReverseBind = 0x2000, } [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibFuncFlags { FRestricted = 0x0001, FSource = 0x0002, FBindable = 0x0004, FRequestEdit = 0x0008, FDisplayBind = 0x0010, FDefaultBind = 0x0020, FHidden = 0x0040, FUsesGetLastError = 0x0080, FDefaultCollelem = 0x0100, FUiDefault = 0x0200, FNonBrowsable = 0x0400, FReplaceable = 0x0800, FImmediateBind = 0x1000, } [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibVarFlags { FReadOnly = 0x0001, FSource = 0x0002, FBindable = 0x0004, FRequestEdit = 0x0008, FDisplayBind = 0x0010, FDefaultBind = 0x0020, FHidden = 0x0040, FRestricted = 0x0080, FDefaultCollelem = 0x0100, FUiDefault = 0x0200, FNonBrowsable = 0x0400, FReplaceable = 0x0800, FImmediateBind = 0x1000, } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibTypeAttribute : Attribute { internal TypeLibTypeFlags _val; public TypeLibTypeAttribute(TypeLibTypeFlags flags) { _val = flags; } public TypeLibTypeAttribute(short flags) { _val = (TypeLibTypeFlags)flags; } public TypeLibTypeFlags Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibFuncAttribute : Attribute { internal TypeLibFuncFlags _val; public TypeLibFuncAttribute(TypeLibFuncFlags flags) { _val = flags; } public TypeLibFuncAttribute(short flags) { _val = (TypeLibFuncFlags)flags; } public TypeLibFuncFlags Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Field, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibVarAttribute : Attribute { internal TypeLibVarFlags _val; public TypeLibVarAttribute(TypeLibVarFlags flags) { _val = flags; } public TypeLibVarAttribute(short flags) { _val = (TypeLibVarFlags)flags; } public TypeLibVarFlags Value { get {return _val;} } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000 } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] // Note that this enum should remain in-[....] with the CorNativeType enum in corhdr.h public enum UnmanagedType { Bool = 0x2, // 4 byte boolean value (true != 0, false == 0) I1 = 0x3, // 1 byte signed value U1 = 0x4, // 1 byte unsigned value I2 = 0x5, // 2 byte signed value U2 = 0x6, // 2 byte unsigned value I4 = 0x7, // 4 byte signed value U4 = 0x8, // 4 byte unsigned value I8 = 0x9, // 8 byte signed value U8 = 0xa, // 8 byte unsigned value R4 = 0xb, // 4 byte floating point R8 = 0xc, // 8 byte floating point Currency = 0xf, // A currency BStr = 0x13, // OLE Unicode BSTR LPStr = 0x14, // Ptr to SBCS string LPWStr = 0x15, // Ptr to Unicode string LPTStr = 0x16, // Ptr to OS preferred (SBCS/Unicode) string ByValTStr = 0x17, // OS preferred (SBCS/Unicode) inline string (only valid in structs) IUnknown = 0x19, // COM IUnknown pointer. IDispatch = 0x1a, // COM IDispatch pointer Struct = 0x1b, // Structure Interface = 0x1c, // COM interface SafeArray = 0x1d, // OLE SafeArray ByValArray = 0x1e, // Array of fixed size (only valid in structs) SysInt = 0x1f, // Hardware natural sized signed integer SysUInt = 0x20, VBByRefStr = 0x22, AnsiBStr = 0x23, // OLE BSTR containing SBCS characters TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0) FunctionPtr = 0x26, // Function pointer AsAny = 0x28, // Paired with Object type and does runtime marshalling determination LPArray = 0x2a, // C style array LPStruct = 0x2b, // Pointer to a structure CustomMarshaler = 0x2c, Error = 0x2d, [System.Runtime.InteropServices.ComVisible(false)] IInspectable = 0x2e, [System.Runtime.InteropServices.ComVisible(false)] HString = 0x2f, // Windows Runtime HSTRING } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class MarshalAsAttribute : Attribute { [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()); } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter) != null; } [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ; } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; } [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(int token, RuntimeModule scope) { UnmanagedType unmanagedType, arraySubType; VarEnum safeArraySubType; int sizeParamIndex = 0, sizeConst = 0; string marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null; int iidParamIndex = 0; ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token); if (nativeType.Length == 0) return null; MetadataImport.GetMarshalAs(nativeType, out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex, out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex); RuntimeType safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope); RuntimeType marshalTypeRef = null; try { marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope); } catch (System.TypeLoadException) { // The user may have supplied a bad type name string causing this TypeLoadException // Regardless, we return the bad type name Contract.Assert(marshalTypeName != null); } return new MarshalAsAttribute( unmanagedType, safeArraySubType, safeArrayUserDefinedType, arraySubType, (short)sizeParamIndex, sizeConst, marshalTypeName, marshalTypeRef, marshalCookie, iidParamIndex); } internal MarshalAsAttribute(UnmanagedType val, VarEnum safeArraySubType, RuntimeType safeArrayUserDefinedSubType, UnmanagedType arraySubType, short sizeParamIndex, int sizeConst, string marshalType, RuntimeType marshalTypeRef, string marshalCookie, int iidParamIndex) { _val = val; SafeArraySubType = safeArraySubType; SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType; IidParameterIndex = iidParamIndex; ArraySubType = arraySubType; SizeParamIndex = sizeParamIndex; SizeConst = sizeConst; MarshalType = marshalType; MarshalTypeRef = marshalTypeRef; MarshalCookie = marshalCookie; } internal UnmanagedType _val; public MarshalAsAttribute(UnmanagedType unmanagedType) { _val = unmanagedType; } public MarshalAsAttribute(short unmanagedType) { _val = (UnmanagedType)unmanagedType; } public UnmanagedType Value { get { return _val; } } // Fields used with SubType = SafeArray. public VarEnum SafeArraySubType; public Type SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). public int IidParameterIndex; // Fields used with SubType = ByValArray and LPArray. // Array size = parameter(PI) * PM + C public UnmanagedType ArraySubType; public short SizeParamIndex; // param index PI public int SizeConst; // constant C // Fields used with SubType = CustomMarshaler [System.Runtime.InteropServices.ComVisible(true)] public String MarshalType; // Name of marshaler class [System.Runtime.InteropServices.ComVisible(true)] public Type MarshalTypeRef; // Type of marshaler class public String MarshalCookie; // cookie to pass to marshaler } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComImportAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeType type) { if ((type.Attributes & TypeAttributes.Import) == 0) return null; return new ComImportAttribute(); } internal static bool IsDefined(RuntimeType type) { return (type.Attributes & TypeAttributes.Import) != 0; } public ComImportAttribute() { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class GuidAttribute : Attribute { internal String _val; public GuidAttribute(String guid) { _val = guid; } public String Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class PreserveSigAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) == 0) return null; return new PreserveSigAttribute(); } internal static bool IsDefined(RuntimeMethodInfo method) { return (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; } public PreserveSigAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class InAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsIn ? new InAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsIn; } public InAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class OutAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsOut ? new OutAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsOut; } public OutAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class OptionalAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsOptional ? new OptionalAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsOptional; } public OptionalAttribute() { } } [Flags] public enum DllImportSearchPath { UseDllDirectoryForDependencies = 0x100, ApplicationDirectory = 0x200, UserDirectories = 0x400, System32 = 0x800, SafeDirectories = 0x1000, AssemblyDirectory = 0x2, LegacyBehavior = 0x0 } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class DefaultDllImportSearchPathsAttribute : Attribute { internal DllImportSearchPath _paths; public DefaultDllImportSearchPathsAttribute(DllImportSearchPath paths) { _paths = paths; } public DllImportSearchPath Paths { get { return _paths; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class DllImportAttribute : Attribute { [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) return null; MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule()); string entryPoint, dllName = null; int token = method.MetadataToken; PInvokeAttributes flags = 0; scope.GetPInvokeMap(token, out flags, out entryPoint, out dllName); CharSet charSet = CharSet.None; switch (flags & PInvokeAttributes.CharSetMask) { case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break; // Invalid: default to CharSet.None default: break; } CallingConvention callingConvention = CallingConvention.Cdecl; switch (flags & PInvokeAttributes.CallConvMask) { case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break; case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break; case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break; case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; // Invalid: default to CallingConvention.Cdecl default: break; } bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; bool preserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; return new DllImportAttribute( dllName, entryPoint, charSet, exactSpelling, setLastError, preserveSig, callingConvention, bestFitMapping, throwOnUnmappableChar); } internal static bool IsDefined(RuntimeMethodInfo method) { return (method.Attributes & MethodAttributes.PinvokeImpl) != 0; } internal DllImportAttribute( string dllName, string entryPoint, CharSet charSet, bool exactSpelling, bool setLastError, bool preserveSig, CallingConvention callingConvention, bool bestFitMapping, bool throwOnUnmappableChar) { _val = dllName; EntryPoint = entryPoint; CharSet = charSet; ExactSpelling = exactSpelling; SetLastError = setLastError; PreserveSig = preserveSig; CallingConvention = callingConvention; BestFitMapping = bestFitMapping; ThrowOnUnmappableChar = throwOnUnmappableChar; } internal String _val; public DllImportAttribute(String dllName) { _val = dllName; } public String Value { get { return _val; } } public String EntryPoint; public CharSet CharSet; public bool SetLastError; public bool ExactSpelling; public bool PreserveSig; public CallingConvention CallingConvention; public bool BestFitMapping; public bool ThrowOnUnmappableChar; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class StructLayoutAttribute : Attribute { private const int DEFAULT_PACKING_SIZE = 8; [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeType type) { if (!IsDefined(type)) return null; int pack = 0, size = 0; LayoutKind layoutKind = LayoutKind.Auto; switch (type.Attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; default: Contract.Assume(false); break; } CharSet charSet = CharSet.None; switch (type.Attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; default: Contract.Assume(false); break; } type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size); // Metadata parameter checking should not have allowed 0 for packing size. // The runtime later converts a packing size of 0 to 8 so do the same here // because it's more useful from a user perspective. if (pack == 0) pack = DEFAULT_PACKING_SIZE; return new StructLayoutAttribute(layoutKind, pack, size, charSet); } internal static bool IsDefined(RuntimeType type) { if (type.IsInterface || type.HasElementType || type.IsGenericParameter) return false; return true; } internal LayoutKind _val; internal StructLayoutAttribute(LayoutKind layoutKind, int pack, int size, CharSet charSet) { _val = layoutKind; Pack = pack; Size = size; CharSet = charSet; } public StructLayoutAttribute(LayoutKind layoutKind) { _val = layoutKind; } public StructLayoutAttribute(short layoutKind) { _val = (LayoutKind)layoutKind; } public LayoutKind Value { get { return _val; } } public int Pack; public int Size; public CharSet CharSet; } [AttributeUsage(AttributeTargets.Field, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class FieldOffsetAttribute : Attribute { [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { int fieldOffset; if (field.DeclaringType != null && field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out fieldOffset)) return new FieldOffsetAttribute(fieldOffset); return null; } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; } internal int _val; public FieldOffsetAttribute(int offset) { _val = offset; } public int Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComAliasNameAttribute : Attribute { internal String _val; public ComAliasNameAttribute(String alias) { _val = alias; } public String Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AutomationProxyAttribute : Attribute { internal bool _val; public AutomationProxyAttribute(bool val) { _val = val; } public bool Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class PrimaryInteropAssemblyAttribute : Attribute { internal int _major; internal int _minor; public PrimaryInteropAssemblyAttribute(int major, int minor) { _major = major; _minor = minor; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class CoClassAttribute : Attribute { internal Type _CoClass; public CoClassAttribute(Type coClass) { _CoClass = coClass; } public Type CoClass { get { return _CoClass; } } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComEventInterfaceAttribute : Attribute { internal Type _SourceInterface; internal Type _EventProvider; public ComEventInterfaceAttribute(Type SourceInterface, Type EventProvider) { _SourceInterface = SourceInterface; _EventProvider = EventProvider; } public Type SourceInterface { get {return _SourceInterface;} } public Type EventProvider { get {return _EventProvider;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibVersionAttribute : Attribute { internal int _major; internal int _minor; public TypeLibVersionAttribute(int major, int minor) { _major = major; _minor = minor; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComCompatibleVersionAttribute : Attribute { internal int _major; internal int _minor; internal int _build; internal int _revision; public ComCompatibleVersionAttribute(int major, int minor, int build, int revision) { _major = major; _minor = minor; _build = build; _revision = revision; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } public int BuildNumber { get {return _build;} } public int RevisionNumber { get {return _revision;} } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class BestFitMappingAttribute : Attribute { internal bool _bestFitMapping; public BestFitMappingAttribute(bool BestFitMapping) { _bestFitMapping = BestFitMapping; } public bool BestFitMapping { get { return _bestFitMapping; } } public bool ThrowOnUnmappableChar; } [AttributeUsage(AttributeTargets.Module, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class DefaultCharSetAttribute : Attribute { internal CharSet _CharSet; public DefaultCharSetAttribute(CharSet charSet) { _CharSet = charSet; } public CharSet CharSet { get { return _CharSet; } } } [Obsolete("This attribute has been deprecated. Application Domains no longer respect Activation Context boundaries in IDispatch calls.", false)] [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class SetWin32ContextInIDispatchAttribute : Attribute { public SetWin32ContextInIDispatchAttribute() { } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class ManagedToNativeComInteropStubAttribute : Attribute { internal Type _classType; internal String _methodName; public ManagedToNativeComInteropStubAttribute(Type classType, String methodName) { _classType = classType; _methodName = methodName; } public Type ClassType { get { return _classType; } } public String MethodName { get { return _methodName; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Extractor { using System; using System.Text; using System.IO; using System.Collections; using NPOI.HSSF.UserModel; using NPOI.HSSF.Record; using NPOI.POIFS.FileSystem; using NPOI; using NPOI.HPSF; using NPOI.SS.Formula.Eval; using NPOI.HSSF.EventUserModel; using NPOI.HSSF.Model; //using NPOI.HSSF.Util; using NPOI.SS.Util; using System.Globalization; /// <summary> /// A text extractor for Excel files, that is based /// on the hssf eventusermodel api. /// It will typically use less memory than /// ExcelExtractor, but may not provide /// the same richness of formatting. /// Returns the textual content of the file, suitable for /// indexing by something like Lucene, but not really /// intended for display to the user. /// </summary> internal class EventBasedExcelExtractor : POIOLE2TextExtractor { private POIFSFileSystem fs; private bool includeSheetNames = true; private bool formulasNotResults = false; public EventBasedExcelExtractor(POIFSFileSystem fs) : base(null) { this.fs = fs; } /// <summary> /// Would return the document information metadata for the document, /// if we supported it /// </summary> /// <value>The doc summary information.</value> public override DocumentSummaryInformation DocSummaryInformation { get { throw new NotImplementedException("Metadata extraction not supported in streaming mode, please use ExcelExtractor"); } } /// <summary> /// Would return the summary information metadata for the document, /// if we supported it /// </summary> /// <value>The summary information.</value> public override SummaryInformation SummaryInformation { get { throw new NotImplementedException("Metadata extraction not supported in streaming mode, please use ExcelExtractor"); } } /// <summary> /// Should sheet names be included? Default is true /// </summary> /// <value>if set to <c>true</c> [include sheet names].</value> public bool IncludeSheetNames { get { return this.includeSheetNames; } set { this.includeSheetNames = value; } } /// <summary> /// Should we return the formula itself, and not /// the result it produces? Default is false /// </summary> /// <value>if set to <c>true</c> [formulas not results].</value> public bool FormulasNotResults { get { return this.formulasNotResults; } set { this.formulasNotResults = value; } } /// <summary> /// Retreives the text contents of the file /// </summary> /// <value>All the text from the document.</value> public override String Text { get { String text = null; try { TextListener tl = TriggerExtraction(); text = tl.text.ToString(); if (!text.EndsWith("\n", StringComparison.Ordinal)) { text = text + "\n"; } } catch (IOException) { throw; } return text; } } /// <summary> /// Triggers the extraction. /// </summary> /// <returns></returns> private TextListener TriggerExtraction() { TextListener tl = new TextListener(includeSheetNames,formulasNotResults); FormatTrackingHSSFListener ft = new FormatTrackingHSSFListener(tl); tl.ft = ft; // Register and process HSSFEventFactory factory = new HSSFEventFactory(); HSSFRequest request = new HSSFRequest(); request.AddListenerForAllRecords(ft); factory.ProcessWorkbookEvents(request, fs); return tl; } private class TextListener : HSSFListener { public FormatTrackingHSSFListener ft; private SSTRecord sstRecord; private IList sheetNames = new ArrayList(); public StringBuilder text = new StringBuilder(); private int sheetNum = -1; private int rowNum; private bool outputNextStringValue = false; private int nextRow = -1; private bool includeSheetNames; private bool formulasNotResults; public TextListener(bool includeSheetNames, bool formulasNotResults) { this.includeSheetNames = includeSheetNames; this.formulasNotResults = formulasNotResults; } /// <summary> /// Process an HSSF Record. Called when a record occurs in an HSSF file. /// </summary> /// <param name="record"></param> public void ProcessRecord(Record record) { String thisText = null; int thisRow = -1; switch (record.Sid) { case BoundSheetRecord.sid: BoundSheetRecord sr = (BoundSheetRecord)record; sheetNames.Add(sr.Sheetname); break; case BOFRecord.sid: BOFRecord bof = (BOFRecord)record; if (bof.Type == BOFRecord.TYPE_WORKSHEET) { sheetNum++; rowNum = -1; if (includeSheetNames) { if (text.Length > 0) text.Append("\n"); text.Append(sheetNames[sheetNum]); } } break; case SSTRecord.sid: sstRecord = (SSTRecord)record; break; case FormulaRecord.sid: FormulaRecord frec = (FormulaRecord)record; thisRow = frec.Row; if (formulasNotResults) { thisText = HSSFFormulaParser.ToFormulaString((HSSFWorkbook)null, frec.ParsedExpression); } else { if (frec.HasCachedResultString) { // Formula result is a string // This is stored in the next record outputNextStringValue = true; nextRow = frec.Row; } else { thisText = FormatNumberDateCell(frec, frec.Value); } } break; case StringRecord.sid: if (outputNextStringValue) { // String for formula StringRecord srec = (StringRecord)record; thisText = srec.String; thisRow = nextRow; outputNextStringValue = false; } break; case LabelRecord.sid: LabelRecord lrec = (LabelRecord)record; thisRow = lrec.Row; thisText = lrec.Value; break; case LabelSSTRecord.sid: LabelSSTRecord lsrec = (LabelSSTRecord)record; thisRow = lsrec.Row; if (sstRecord == null) { throw new Exception("No SST record found"); } thisText = sstRecord.GetString(lsrec.SSTIndex).ToString(); break; case NoteRecord.sid: NoteRecord nrec = (NoteRecord)record; thisRow = nrec.Row; // TODO: Find object to match nrec.GetShapeId() break; case NumberRecord.sid: NumberRecord numrec = (NumberRecord)record; thisRow = numrec.Row; thisText = FormatNumberDateCell(numrec, numrec.Value); break; default: break; } if (thisText != null) { if (thisRow != rowNum) { rowNum = thisRow; if (text.Length > 0) text.Append("\n"); } else { text.Append("\t"); } text.Append(thisText); } } /// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return value.ToString(CultureInfo.InvariantCulture); } else { // Is it a date? if (NPOI.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && NPOI.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = NPOI.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return df.Format(d); } else { if (formatString == "General") { // Some sort of wierd default return value.ToString(CultureInfo.InvariantCulture); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return df.Format(value); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; namespace System.Data.SqlClient { public sealed partial class SqlConnection : DbConnection { private bool _AsyncCommandInProgress; // SQLStatistics support internal SqlStatistics _statistics; private bool _collectstats; private bool _fireInfoMessageEventOnUserErrors; // False by default // root task associated with current async invocation private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion; private string _connectionString; private int _connectRetryCount; // connection resiliency private object _reconnectLock = new object(); internal Task _currentReconnectionTask; private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections private Guid _originalConnectionId = Guid.Empty; private CancellationTokenSource _reconnectionCancellationSource; internal SessionData _recoverySessionData; internal bool _supressStateChangeForReconnection; private int _reconnectCount; // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened // using SqlConnection.Open() method. internal bool _applyTransientFaultHandling = false; public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available CacheConnectionStringProperties(); } // This method will be called once connection string is set or changed. private void CacheConnectionStringProperties() { SqlConnectionString connString = ConnectionOptions as SqlConnectionString; if (connString != null) { _connectRetryCount = connString.ConnectRetryCount; } } // // PUBLIC PROPERTIES // // used to start/stop collection of statistics data and do verify the current state // // devnote: start/stop should not performed using a property since it requires execution of code // // start statistics // set the internal flag (_statisticsEnabled) to true. // Create a new SqlStatistics object if not already there. // connect the parser to the object. // if there is no parser at this time we need to connect it after creation. // public bool StatisticsEnabled { get { return (_collectstats); } set { { if (value) { // start if (ConnectionState.Open == State) { if (null == _statistics) { _statistics = new SqlStatistics(); ADP.TimerCurrent(out _statistics._openTimestamp); } // set statistics on the parser // update timestamp; Debug.Assert(Parser != null, "Where's the parser?"); Parser.Statistics = _statistics; } } else { // stop if (null != _statistics) { if (ConnectionState.Open == State) { // remove statistics from parser // update timestamp; TdsParser parser = Parser; Debug.Assert(parser != null, "Where's the parser?"); parser.Statistics = null; ADP.TimerCurrent(out _statistics._closeTimestamp); } } } _collectstats = value; } } } internal bool AsyncCommandInProgress { get { return (_AsyncCommandInProgress); } set { _AsyncCommandInProgress = value; } } internal SqlConnectionString.TypeSystem TypeSystem { get { return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion; } } internal int ConnectRetryInterval { get { return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval; } } override public string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(new SqlConnectionPoolKey(value)); _connectionString = value; // Change _connectionString value only after value is validated CacheConnectionStringProperties(); } } override public int ConnectionTimeout { get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); } } override public string Database { // if the connection is open, we need to ask the inner connection what it's // current catalog is because it may have gotten changed, otherwise we can // just return what the connection string had. get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); } return result; } } override public string DataSource { get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); } return result; } } public int PacketSize { // if the connection is open, we need to ask the inner connection what it's // current packet size is because it may have gotten changed, otherwise we // can just return what the connection string had. get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; if (null != innerConnection) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); } return result; } } public Guid ClientConnectionId { get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null != innerConnection) { return innerConnection.ClientConnectionId; } else { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return _originalConnectionId; } return Guid.Empty; } } } override public string ServerVersion { get { return GetOpenTdsConnection().ServerVersion; } } override public ConnectionState State { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return ConnectionState.Open; } return InnerConnection.State; } } internal SqlStatistics Statistics { get { return _statistics; } } public string WorkstationId { get { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; string result = ((null != constr) ? constr.WorkstationId : string.Empty); return result; } } // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication // // PUBLIC EVENTS // public event SqlInfoMessageEventHandler InfoMessage; public bool FireInfoMessageEventOnUserErrors { get { return _fireInfoMessageEventOnUserErrors; } set { _fireInfoMessageEventOnUserErrors = value; } } // Approx. number of times that the internal connection has been reconnected internal int ReconnectCount { get { return _reconnectCount; } } internal bool ForceNewConnection { get; set; } protected override void OnStateChange(StateChangeEventArgs stateChange) { if (!_supressStateChangeForReconnection) { base.OnStateChange(stateChange); } } // // PUBLIC METHODS // new public SqlTransaction BeginTransaction() { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(IsolationLevel.Unspecified, null); } new public SqlTransaction BeginTransaction(IsolationLevel iso) { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(iso, null); } public SqlTransaction BeginTransaction(string transactionName) { // Use transaction names only on the outermost pair of nested // BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names // are ignored for nested BEGIN's. The only way to rollback a nested // transaction is to have a save point from a SAVE TRANSACTION call. return BeginTransaction(IsolationLevel.Unspecified, transactionName); } [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) { WaitForPendingReconnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlTransaction transaction; bool isFirstAttempt = true; do { transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt"); isFirstAttempt = false; } while (transaction.InternalTransaction.ConnectionHasBeenRestored); // The GetOpenConnection line above doesn't keep a ref on the outer connection (this), // and it could be collected before the inner connection can hook it to the transaction, resulting in // a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen. GC.KeepAlive(this); return transaction; } finally { SqlStatistics.StopTimer(statistics); } } override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); try { statistics = SqlStatistics.StartTimer(Statistics); InnerConnection.ChangeDatabase(database); } finally { SqlStatistics.StopTimer(statistics); } } static public void ClearAllPools() { SqlConnectionFactory.SingletonInstance.ClearAllPools(); } static public void ClearPool(SqlConnection connection) { ADP.CheckArgumentNull(connection, "connection"); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; if (null != connectionOptions) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } } private void CloseInnerConnection() { // CloseConnection() now handles the lock // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close opperation, but this is // outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock. InnerConnection.CloseConnection(this, ConnectionFactory); } override public void Close() { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { CancellationTokenSource cts = _reconnectionCancellationSource; if (cts != null) { cts.Cancel(); } AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection if (State != ConnectionState.Open) {// if we cancelled before the connection was opened OnStateChange(DbConnectionInternal.StateChangeClosed); } } CancelOpenAndWait(); CloseInnerConnection(); GC.SuppressFinalize(this); if (null != Statistics) { ADP.TimerCurrent(out _statistics._closeTimestamp); } } finally { SqlStatistics.StopTimer(statistics); } } new public SqlCommand CreateCommand() { return new SqlCommand(null, this); } private void DisposeMe(bool disposing) { if (!disposing) { // For non-pooled connections we need to make sure that if the SqlConnection was not closed, // then we release the GCHandle on the stateObject to allow it to be GCed // For pooled connections, we will rely on the pool reclaiming the connection var innerConnection = (InnerConnection as SqlInternalConnectionTds); if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) { var parser = innerConnection.Parser; if ((parser != null) && (parser._physicalStateObj != null)) { parser._physicalStateObj.DecrementPendingCallbacks(release: false); } } } } override public void Open() { if (StatisticsEnabled) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); if (!TryOpen(null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } finally { SqlStatistics.StopTimer(statistics); } } internal void RegisterWaitingForReconnect(Task waitingTask) { if (((SqlConnectionString)ConnectionOptions).MARS) { return; } Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null); if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register throw SQL.MARSUnspportedOnConnection(); } } private async Task ReconnectAsync(int timeout) { try { long commandTimeoutExpiration = 0; if (timeout > 0) { commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout); } CancellationTokenSource cts = new CancellationTokenSource(); _reconnectionCancellationSource = cts; CancellationToken ctoken = cts.Token; int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string for (int attempt = 0; attempt < retryCount; attempt++) { if (ctoken.IsCancellationRequested) { return; } try { try { ForceNewConnection = true; await OpenAsync(ctoken).ConfigureAwait(false); // On success, increment the reconnect count - we don't really care if it rolls over since it is approx. _reconnectCount = unchecked(_reconnectCount + 1); #if DEBUG Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !"); #endif } finally { ForceNewConnection = false; } return; } catch (SqlException e) { if (attempt == retryCount - 1) { throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) { throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId); } } await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false); } } finally { _recoverySessionData = null; _supressStateChangeForReconnection = false; } Debug.Assert(false, "Should not reach this point"); } internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { Task runningReconnect = _currentReconnectionTask; // This loop in the end will return not completed reconnect task or null while (runningReconnect != null && runningReconnect.IsCompleted) { // clean current reconnect task (if it is the same one we checked Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect); // make sure nobody started new task (if which case we did not clean it) runningReconnect = _currentReconnectionTask; } if (runningReconnect == null) { if (_connectRetryCount > 0) { SqlInternalConnectionTds tdsConn = GetOpenTdsConnection(); if (tdsConn._sessionRecoveryAcknowledged) { TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj; if (!stateObj.ValidateSNIConnection()) { if (tdsConn.Parser._sessionPool != null) { if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0) { // >1 MARS session if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null); } } SessionData cData = tdsConn.CurrentSessionData; cData.AssertUnrecoverableStateCountIsCorrect(); if (cData._unrecoverableStatesCount == 0) { bool callDisconnect = false; lock (_reconnectLock) { runningReconnect = _currentReconnectionTask; // double check after obtaining the lock if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; _recoverySessionData = cData; if (beforeDisconnect != null) { beforeDisconnect(); } try { _supressStateChangeForReconnection = true; tdsConn.DoomThisConnection(); } catch (SqlException) { } runningReconnect = Task.Run(() => ReconnectAsync(timeout)); // if current reconnect is not null, somebody already started reconnection task - some kind of race condition Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected"); _currentReconnectionTask = runningReconnect; } } else { callDisconnect = true; } } if (callDisconnect && beforeDisconnect != null) { beforeDisconnect(); } } else { if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null); } } // ValidateSNIConnection } // sessionRecoverySupported } // connectRetryCount>0 } else { // runningReconnect = null if (beforeDisconnect != null) { beforeDisconnect(); } } return runningReconnect; } // this is straightforward, but expensive method to do connection resiliency - it take locks and all prepartions as for TDS request partial void RepairInnerConnection() { WaitForPendingReconnection(); if (_connectRetryCount == 0) { return; } SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds; if (tdsConn != null) { tdsConn.ValidateConnectionForExecute(null); tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this); } } private void WaitForPendingReconnection() { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); } } private void CancelOpenAndWait() { // copy from member to avoid changes by background thread var completion = _currentCompletion; if (completion != null) { completion.Item1.TrySetCanceled(); ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne(); } Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source"); } public override Task OpenAsync(CancellationToken cancellationToken) { if (StatisticsEnabled) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(); TaskCompletionSource<object> result = new TaskCompletionSource<object>(); if (cancellationToken.IsCancellationRequested) { result.SetCanceled(); return result.Task; } bool completed; try { completed = TryOpen(completion); } catch (Exception e) { result.SetException(e); return result.Task; } if (completed) { result.SetResult(null); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(() => completion.TrySetCanceled()); } OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration); _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task); completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default); return result.Task; } return result.Task; } finally { SqlStatistics.StopTimer(statistics); } } private class OpenAsyncRetry { private SqlConnection _parent; private TaskCompletionSource<DbConnectionInternal> _retry; private TaskCompletionSource<object> _result; private CancellationTokenRegistration _registration; public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration) { _parent = parent; _retry = retry; _result = result; _registration = registration; } internal void Retry(Task<DbConnectionInternal> retryTask) { _registration.Dispose(); try { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(_parent.Statistics); if (retryTask.IsFaulted) { Exception e = retryTask.Exception.InnerException; _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(retryTask.Exception.InnerException); } else if (retryTask.IsCanceled) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetCanceled(); } else { bool result; // protect continuation from races with close and cancel lock (_parent.InnerConnection) { result = _parent.TryOpen(_retry); } if (result) { _parent._currentCompletion = null; _result.SetResult(null); } else { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending))); } } } finally { SqlStatistics.StopTimer(statistics); } } catch (Exception e) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(e); } } } private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry) { SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions; _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0); if (ForceNewConnection) { if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } else { if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } // does not require GC.KeepAlive(this) because of OnStateChange var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds); Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?"); if (!tdsInnerConnection.ConnectionOptions.Pooling) { // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles GC.ReRegisterForFinalize(this); } if (StatisticsEnabled) { ADP.TimerCurrent(out _statistics._openTimestamp); tdsInnerConnection.Parser.Statistics = _statistics; } else { tdsInnerConnection.Parser.Statistics = null; _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence } return true; } // // INTERNAL PROPERTIES // internal bool HasLocalTransaction { get { return GetOpenTdsConnection().HasLocalTransaction; } } internal bool HasLocalTransactionFromAPI { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return false; //we will not go into reconnection if we are inside the transaction } return GetOpenTdsConnection().HasLocalTransactionFromAPI; } } internal bool IsKatmaiOrNewer { get { if (_currentReconnectionTask != null) { // holds true even if task is completed return true; // if CR is enabled, connection, if established, will be Katmai+ } return GetOpenTdsConnection().IsKatmaiOrNewer; } } internal TdsParser Parser { get { SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection(); return tdsConnection.Parser; } } // // INTERNAL METHODS // internal void ValidateConnectionForExecute(string method, SqlCommand command) { Task asyncWaitingForReconnection = _asyncWaitingForReconnection; if (asyncWaitingForReconnection != null) { if (!asyncWaitingForReconnection.IsCompleted) { throw SQL.MARSUnspportedOnConnection(); } else { Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection); } } if (_currentReconnectionTask != null) { Task currentReconnectionTask = _currentReconnectionTask; if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) { return; // execution will wait for this task later } } SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method); innerConnection.ValidateConnectionForExecute(command); } // Surround name in brackets and then escape any end bracket to protect against SQL Injection. // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well // as native OleDb and Odbc. static internal string FixupDatabaseTransactionName(string name) { if (!ADP.IsEmpty(name)) { return SqlServerEscapeHelper.EscapeIdentifier(name); } else { return name; } } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) { Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!"); if (breakConnection && (ConnectionState.Open == State)) { if (wrapCloseInAction != null) { int capturedCloseCount = _closeCount; Action closeAction = () => { if (capturedCloseCount == _closeCount) { Close(); } }; wrapCloseInAction(closeAction); } else { Close(); } } if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error, // below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } else { // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler this.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } } // // PRIVATE METHODS // internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.ClosedConnectionError(); } return innerConnection; } internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.OpenConnectionRequired(method, InnerConnection.State); } return innerConnection; } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) { bool notified; OnInfoMessage(imevent, out notified); } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { notified = true; try { handler(this, imevent); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } else { notified = false; } } // // SQL DEBUGGING SUPPORT // // this only happens once per connection // SxS: using named file mapping APIs internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag) { // Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect outerTask = outerTask.ContinueWith(task => { RemoveWeakReference(value); return task; }, TaskScheduler.Default).Unwrap(); } public void ResetStatistics() { if (null != Statistics) { Statistics.Reset(); if (ConnectionState.Open == State) { // update timestamp; ADP.TimerCurrent(out _statistics._openTimestamp); } } } public IDictionary RetrieveStatistics() { if (null != Statistics) { UpdateStatistics(); return Statistics.GetHashtable(); } else { return new SqlStatistics().GetHashtable(); } } private void UpdateStatistics() { if (ConnectionState.Open == State) { // update timestamp ADP.TimerCurrent(out _statistics._closeTimestamp); } // delegate the rest of the work to the SqlStatistics class Statistics.UpdateStatistics(); } } // SqlConnection } // System.Data.SqlClient namespace
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.PythonTools { /// <summary> /// Implements classification of text by using a ScriptEngine which supports the /// TokenCategorizer service. /// /// Languages should subclass this type and override the Engine property. They /// should then export the provider using MEF indicating the content type /// which it is applicable to. /// </summary> [Export(typeof(IClassifierProvider)), ContentType(PythonCoreConstants.ContentType)] internal class PythonClassifierProvider : IClassifierProvider { private Dictionary<TokenCategory, IClassificationType> _categoryMap; private IClassificationType _comment; private IClassificationType _stringLiteral; private IClassificationType _keyword; private IClassificationType _operator; private IClassificationType _groupingClassification; private IClassificationType _dotClassification; private IClassificationType _commaClassification; private readonly IContentType _type; internal readonly IServiceProvider _serviceProvider; [ImportingConstructor] public PythonClassifierProvider(IContentTypeRegistryService contentTypeRegistryService, [Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider) { _type = contentTypeRegistryService.GetContentType(PythonCoreConstants.ContentType); _serviceProvider = serviceProvider; } /// <summary> /// Import the classification registry to be used for getting a reference /// to the custom classification type later. /// </summary> [Import] public IClassificationTypeRegistryService _classificationRegistry = null; // Set via MEF #region Python Classification Type Definitions [Export] [Name(PythonPredefinedClassificationTypeNames.Grouping)] [BaseDefinition(PythonPredefinedClassificationTypeNames.Operator)] internal static ClassificationTypeDefinition GroupingClassificationDefinition = null; // Set via MEF [Export] [Name(PythonPredefinedClassificationTypeNames.Dot)] [BaseDefinition(PythonPredefinedClassificationTypeNames.Operator)] internal static ClassificationTypeDefinition DotClassificationDefinition = null; // Set via MEF [Export] [Name(PythonPredefinedClassificationTypeNames.Comma)] [BaseDefinition(PythonPredefinedClassificationTypeNames.Operator)] internal static ClassificationTypeDefinition CommaClassificationDefinition = null; // Set via MEF [Export] [Name(PythonPredefinedClassificationTypeNames.Operator)] [BaseDefinition(PredefinedClassificationTypeNames.Operator)] internal static ClassificationTypeDefinition OperatorClassificationDefinition = null; // Set via MEF [Export] [Name(PythonPredefinedClassificationTypeNames.Builtin)] [BaseDefinition(PredefinedClassificationTypeNames.Identifier)] internal static ClassificationTypeDefinition BuiltinClassificationDefinition = null; // Set via MEF #endregion #region IDlrClassifierProvider public IClassifier GetClassifier(ITextBuffer buffer) { if (_categoryMap == null) { _categoryMap = FillCategoryMap(_classificationRegistry); } PythonClassifier res; if (!buffer.Properties.TryGetProperty<PythonClassifier>(typeof(PythonClassifier), out res) && buffer.ContentType.IsOfType(ContentType.TypeName)) { res = new PythonClassifier(this, buffer); buffer.Properties.AddProperty(typeof(PythonClassifier), res); } return res; } public virtual IContentType ContentType { get { return _type; } } public IClassificationType Comment { get { return _comment; } } public IClassificationType StringLiteral { get { return _stringLiteral; } } public IClassificationType Keyword { get { return _keyword; } } public IClassificationType Operator { get { return _operator; } } public IClassificationType GroupingClassification { get { return _groupingClassification; } } public IClassificationType DotClassification { get { return _dotClassification; } } public IClassificationType CommaClassification { get { return _commaClassification; } } #endregion internal Dictionary<TokenCategory, IClassificationType> CategoryMap { get { return _categoryMap; } } private Dictionary<TokenCategory, IClassificationType> FillCategoryMap(IClassificationTypeRegistryService registry) { var categoryMap = new Dictionary<TokenCategory, IClassificationType>(); categoryMap[TokenCategory.DocComment] = _comment = registry.GetClassificationType(PredefinedClassificationTypeNames.Comment); categoryMap[TokenCategory.LineComment] = registry.GetClassificationType(PredefinedClassificationTypeNames.Comment); categoryMap[TokenCategory.Comment] = registry.GetClassificationType(PredefinedClassificationTypeNames.Comment); categoryMap[TokenCategory.NumericLiteral] = registry.GetClassificationType(PredefinedClassificationTypeNames.Number); categoryMap[TokenCategory.CharacterLiteral] = registry.GetClassificationType(PredefinedClassificationTypeNames.Character); categoryMap[TokenCategory.StringLiteral] = _stringLiteral = registry.GetClassificationType(PredefinedClassificationTypeNames.String); categoryMap[TokenCategory.Keyword] = _keyword = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword); categoryMap[TokenCategory.Directive] = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword); categoryMap[TokenCategory.Identifier] = registry.GetClassificationType(PredefinedClassificationTypeNames.Identifier); categoryMap[TokenCategory.Operator] = _operator = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Operator); categoryMap[TokenCategory.Delimiter] = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Operator); categoryMap[TokenCategory.Grouping] = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Operator); categoryMap[TokenCategory.WhiteSpace] = registry.GetClassificationType(PredefinedClassificationTypeNames.WhiteSpace); categoryMap[TokenCategory.RegularExpressionLiteral] = registry.GetClassificationType(PredefinedClassificationTypeNames.Literal); categoryMap[TokenCategory.BuiltinIdentifier] = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Builtin); _groupingClassification = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Grouping); _commaClassification = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Comma); _dotClassification = registry.GetClassificationType(PythonPredefinedClassificationTypeNames.Dot); return categoryMap; } } #region Editor Format Definitions [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = PythonPredefinedClassificationTypeNames.Operator)] [Name(PythonPredefinedClassificationTypeNames.Operator)] [UserVisible(true)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] internal sealed class OperatorFormat : ClassificationFormatDefinition { public OperatorFormat() { DisplayName = SR.GetString(SR.OperatorClassificationType); // Matches "Operator" ForegroundColor = Colors.Black; } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = PythonPredefinedClassificationTypeNames.Grouping)] [Name(PythonPredefinedClassificationTypeNames.Grouping)] [UserVisible(true)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] internal sealed class GroupingFormat : ClassificationFormatDefinition { public GroupingFormat() { DisplayName = SR.GetString(SR.GroupingClassificationType); // Matches "Operator" ForegroundColor = Colors.Black; } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = PythonPredefinedClassificationTypeNames.Comma)] [Name(PythonPredefinedClassificationTypeNames.Comma)] [UserVisible(true)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] internal sealed class CommaFormat : ClassificationFormatDefinition { public CommaFormat() { DisplayName = SR.GetString(SR.CommaClassificationType); // Matches "Operator" ForegroundColor = Colors.Black; } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = PythonPredefinedClassificationTypeNames.Dot)] [Name(PythonPredefinedClassificationTypeNames.Dot)] [UserVisible(true)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] internal sealed class DotFormat : ClassificationFormatDefinition { public DotFormat() { DisplayName = SR.GetString(SR.DotClassificationType); // Matches "Operator" ForegroundColor = Colors.Black; } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = PythonPredefinedClassificationTypeNames.Builtin)] [Name(PythonPredefinedClassificationTypeNames.Builtin)] [UserVisible(true)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] internal sealed class BuiltinFormat : ClassificationFormatDefinition { public BuiltinFormat() { DisplayName = SR.GetString(SR.BuiltinClassificationType); // Matches "Keyword" ForegroundColor = Colors.Blue; } } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Composite Swagger Client that represents merging body complex and /// complex model swagger clients /// </summary> public partial class AzureCompositeModel : Microsoft.Rest.ServiceClient<AzureCompositeModel>, IAzureCompositeModel, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription ID. /// </summary> public string SubscriptionId { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IBasicOperations. /// </summary> public virtual IBasicOperations Basic { get; private set; } /// <summary> /// Gets the IPrimitiveOperations. /// </summary> public virtual IPrimitiveOperations Primitive { get; private set; } /// <summary> /// Gets the IArrayOperations. /// </summary> public virtual IArrayOperations Array { get; private set; } /// <summary> /// Gets the IDictionaryOperations. /// </summary> public virtual IDictionaryOperations Dictionary { get; private set; } /// <summary> /// Gets the IInheritanceOperations. /// </summary> public virtual IInheritanceOperations Inheritance { get; private set; } /// <summary> /// Gets the IPolymorphismOperations. /// </summary> public virtual IPolymorphismOperations Polymorphism { get; private set; } /// <summary> /// Gets the IPolymorphicrecursiveOperations. /// </summary> public virtual IPolymorphicrecursiveOperations Polymorphicrecursive { get; private set; } /// <summary> /// Gets the IReadonlypropertyOperations. /// </summary> public virtual IReadonlypropertyOperations Readonlyproperty { get; private set; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AzureCompositeModel(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AzureCompositeModel(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Basic = new BasicOperations(this); this.Primitive = new PrimitiveOperations(this); this.Array = new ArrayOperations(this); this.Dictionary = new DictionaryOperations(this); this.Inheritance = new InheritanceOperations(this); this.Polymorphism = new PolymorphismOperations(this); this.Polymorphicrecursive = new PolymorphicrecursiveOperations(this); this.Readonlyproperty = new ReadonlypropertyOperations(this); this.BaseUri = new System.Uri("http://localhost"); this.SubscriptionId = "123456"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<Fish>("fishtype")); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<Fish>("fishtype")); CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } /// <summary> /// Product Types /// </summary> /// <remarks> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// </remarks> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CatalogArray>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productDictionaryOfArray'> /// Dictionary of Array of product /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CatalogDictionary>> CreateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, System.Collections.Generic.IDictionary<string, System.Collections.Generic.IList<Product>> productDictionaryOfArray = default(System.Collections.Generic.IDictionary<string, System.Collections.Generic.IList<Product>>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (subscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogDictionaryOfArray bodyParameter = new CatalogDictionaryOfArray(); if (productDictionaryOfArray != null) { bodyParameter.ProductDictionaryOfArray = productDictionaryOfArray; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CatalogDictionary>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CatalogDictionary>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CatalogArray>> UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, Product>> productArrayOfDictionary = default(System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, Product>>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (subscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // CTTypesetter.cs: Implements the managed CTTypesetter // // Authors: Mono Team // // Copyright 2010 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.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; namespace MonoMac.CoreText { #region Typesetter Values [Since (3,2)] public static class CTTypesetterOptionKey { public static readonly NSString DisableBidiProcessing; public static readonly NSString ForceEmbeddingLevel; static CTTypesetterOptionKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { DisableBidiProcessing = Dlfcn.GetStringConstant (handle, "kCTTypesetterOptionDisableBidiProcessing"); ForceEmbeddingLevel = Dlfcn.GetStringConstant (handle, "kCTTypesetterOptionForcedEmbeddingLevel"); } finally { Dlfcn.dlclose (handle); } } } [Since (3,2)] public class CTTypesetterOptions { public CTTypesetterOptions () : this (new NSMutableDictionary ()) { } public CTTypesetterOptions (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} public bool DisableBidiProcessing { get { return CFDictionary.GetBooleanValue (Dictionary.Handle, CTTypesetterOptionKey.DisableBidiProcessing.Handle); } set { Adapter.AssertWritable (Dictionary); CFMutableDictionary.SetValue (Dictionary.Handle, CTTypesetterOptionKey.DisableBidiProcessing.Handle, value); } } public int? ForceEmbeddingLevel { get {return Adapter.GetInt32Value (Dictionary, CTTypesetterOptionKey.ForceEmbeddingLevel);} set {Adapter.SetValue (Dictionary, CTTypesetterOptionKey.ForceEmbeddingLevel, value);} } } #endregion [Since (3,2)] public class CTTypesetter : INativeObject, IDisposable { internal IntPtr handle; internal CTTypesetter (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } public IntPtr Handle { get {return handle;} } ~CTTypesetter () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Typesetter Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateWithAttributedString (IntPtr @string); public CTTypesetter (NSAttributedString value) { if (value == null) throw ConstructorError.ArgumentNull (this, "value"); handle = CTTypesetterCreateWithAttributedString (value.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateWithAttributedStringAndOptions (IntPtr @string, IntPtr options); public CTTypesetter (NSAttributedString value, CTTypesetterOptions options) { if (value == null) throw ConstructorError.ArgumentNull (this, "value"); handle = CTTypesetterCreateWithAttributedStringAndOptions (value.Handle, options == null ? IntPtr.Zero : options.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } #endregion #region Typeset Line Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateLineWithOffset (IntPtr typesetter, NSRange stringRange, double offset); public CTLine GetLine (NSRange stringRange, double offset) { var h = CTTypesetterCreateLineWithOffset (handle, stringRange, offset); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateLine (IntPtr typesetter, NSRange stringRange); public CTLine GetLine (NSRange stringRange) { var h = CTTypesetterCreateLine (handle, stringRange); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } #endregion #region Typeset Line Breaking [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestLineBreakWithOffset (IntPtr typesetter, int startIndex, double width, double offset); public int SuggestLineBreak (int startIndex, double width, double offset) { return CTTypesetterSuggestLineBreakWithOffset (handle, startIndex, width, offset); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestLineBreak (IntPtr typesetter, int startIndex, double width); public int SuggestLineBreak (int startIndex, double width) { return CTTypesetterSuggestLineBreak (handle, startIndex, width); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestClusterBreakWithOffset (IntPtr typesetter, int startIndex, double width, double offset); public int SuggestClusterBreak (int startIndex, double width, double offset) { return CTTypesetterSuggestClusterBreakWithOffset (handle, startIndex, width, offset); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestClusterBreak (IntPtr typesetter, int startIndex, double width); public int SuggestClusterBreak (int startIndex, double width) { return CTTypesetterSuggestClusterBreak (handle, startIndex, width); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Cache.Store { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for store session. /// </summary> public class CacheStoreSessionTest { /** Cache 1 name. */ protected const string Cache1 = "cache1"; /** Cache 2 name. */ protected const string Cache2 = "cache2"; /** Operations. */ private static ConcurrentBag<ICollection<Operation>> _dumps; /// <summary> /// Set up routine. /// </summary> [TestFixtureSetUp] public void BeforeTests() { Ignition.Start(GetIgniteConfiguration()); } /// <summary> /// Gets the ignite configuration. /// </summary> protected virtual IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = @"Config/Cache/Store/cache-store-session.xml" }; } /// <summary> /// Gets the store count. /// </summary> protected virtual int StoreCount { get { return 2; } } /// <summary> /// Tear down routine. /// </summary> [TestFixtureTearDown] public void AfterTests() { try { TestUtils.AssertHandleRegistryHasItems(Ignition.GetIgnite(), 2, 1000); } finally { Ignition.StopAll(true); } } /// <summary> /// Test basic session API. /// </summary> [Test] [Timeout(30000)] public void TestSession() { _dumps = new ConcurrentBag<ICollection<Operation>>(); var ignite = Ignition.GetIgnite(); var cache1 = ignite.GetCache<int, int>(Cache1); var cache2 = ignite.GetCache<int, int>(Cache2); // 1. Test rollback. using (var tx = ignite.GetTransactions().TxStart()) { cache1.Put(1, 1); cache2.Put(2, 2); tx.Rollback(); } // SessionEnd should not be called. Assert.AreEqual(0, _dumps.Count); // 2. Test puts. using (var tx = ignite.GetTransactions().TxStart()) { cache1.Put(1, 1); cache2.Put(2, 2); tx.Commit(); } Assert.AreEqual(StoreCount, _dumps.Count); foreach (var ops in _dumps) { Assert.AreEqual(2 + StoreCount, ops.Count); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Write && Cache1 == op.CacheName && 1 == op.Key && 1 == op.Value)); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Write && Cache2 == op.CacheName && 2 == op.Key && 2 == op.Value)); Assert.AreEqual(StoreCount, ops.Count(op => op.Type == OperationType.SesEnd && op.Commit)); } _dumps = new ConcurrentBag<ICollection<Operation>>(); // 3. Test removes. using (var tx = ignite.GetTransactions().TxStart()) { cache1.Remove(1); cache2.Remove(2); tx.Commit(); } Assert.AreEqual(StoreCount, _dumps.Count); foreach (var ops in _dumps) { Assert.AreEqual(2 + StoreCount, ops.Count); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Delete && Cache1 == op.CacheName && 1 == op.Key)); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Delete && Cache2 == op.CacheName && 2 == op.Key)); Assert.AreEqual(StoreCount, ops.Count(op => op.Type == OperationType.SesEnd && op.Commit)); } } /// <summary> /// Dump operations. /// </summary> /// <param name="dump">Dump.</param> private static void DumpOperations(ICollection<Operation> dump) { _dumps.Add(dump); } /// <summary> /// Test store implementation. /// </summary> // ReSharper disable once UnusedMember.Global public class Store : CacheStoreAdapter<object, object> { /** Store session. */ [StoreSessionResource] #pragma warning disable 649 private ICacheStoreSession _ses; #pragma warning restore 649 /** <inheritdoc /> */ public override object Load(object key) { throw new NotImplementedException(); } /** <inheritdoc /> */ public override void Write(object key, object val) { GetOperations().Add(new Operation(_ses.CacheName, OperationType.Write, (int)key, (int)val)); } /** <inheritdoc /> */ public override void Delete(object key) { GetOperations().Add(new Operation(_ses.CacheName, OperationType.Delete, (int)key, 0)); } /** <inheritdoc /> */ public override void SessionEnd(bool commit) { Operation op = new Operation(_ses.CacheName, OperationType.SesEnd) { Commit = commit }; ICollection<Operation> ops = GetOperations(); ops.Add(op); DumpOperations(ops); } /// <summary> /// Get collection with operations. /// </summary> /// <returns>Operations.</returns> private ICollection<Operation> GetOperations() { object ops; if (!_ses.Properties.TryGetValue("ops", out ops)) { ops = new List<Operation>(); _ses.Properties["ops"] = ops; } return (ICollection<Operation>) ops; } } /// <summary> /// Logged operation. /// </summary> private class Operation { /// <summary> /// Constructor. /// </summary> /// <param name="cacheName">Cache name.</param> /// <param name="type">Operation type.</param> public Operation(string cacheName, OperationType type) { CacheName = cacheName; Type = type; } /// <summary> /// Constructor. /// </summary> /// <param name="cacheName">Cache name.</param> /// <param name="type">Operation type.</param> /// <param name="key">Key.</param> /// <param name="val">Value.</param> public Operation(string cacheName, OperationType type, int key, int val) : this(cacheName, type) { Key = key; Value = val; } /// <summary> /// Cache name. /// </summary> public string CacheName { get; private set; } /// <summary> /// Operation type. /// </summary> public OperationType Type { get; private set; } /// <summary> /// Key. /// </summary> public int Key { get; private set; } /// <summary> /// Value. /// </summary> public int Value { get; private set; } /// <summary> /// Commit flag. /// </summary> public bool Commit { get; set; } } /// <summary> /// Operation types. /// </summary> private enum OperationType { /** Write. */ Write, /** Delete. */ Delete, /** Session end. */ SesEnd } } }
using PowerArgs; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace Watch { [ArgExceptionBehavior(ArgExceptionPolicy.StandardExceptionHandling)] public class ConsoleArgs { [HelpHook, ArgShortcut("-?"), ArgDescription("Shows this help")] public bool Help { get; set; } [ArgActionMethod, ArgDescription("Watch system clipboard for changes"), ArgShortcut("c")] public void Clipboard(ClipboardArgs args) { bool stopThread = false; var t = new Thread(new ThreadStart(() => { string previousClipText = TextCopy.Clipboard.GetText(); while (!stopThread) { string currentText = String.Empty; if (!String.Equals((currentText = TextCopy.Clipboard.GetText()), previousClipText) && currentText != null) { // save the text so we can compare it // later previousClipText = currentText; // run program Run(args.TargetProgram, args?.Arguments?.Replace("{CLIPTEXT}", EncodeClipboardTextArgument(currentText)), args.Repeat); } Thread.Sleep(args.Interval); } })); t.SetApartmentState(ApartmentState.STA); t.Start(); Console.WriteLine("Press Key to End"); Console.ReadKey(); try { stopThread = true; t.Abort(); } catch (Exception e) {} } /// <summary> /// Token replacement text must be escaped properly /// to avoid injecting unintended arguments into the /// Target Program. /// </summary> /// <param name="original"></param> /// <returns></returns> private string EncodeClipboardTextArgument(string original) { if (string.IsNullOrEmpty(original)) return original; string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0"); value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"").Replace(System.Environment.NewLine, ""); return value; } [ArgActionMethod, ArgDescription("Watch file or directory for changes"), ArgShortcut("fs")] public void Filesystem(FileSystemArgs args) { using (var watcher = new FileSystemWatcher()) { if (File.Exists(args.Path)) { watcher.Path = Path.GetDirectoryName(args.Path); watcher.Filter = Path.GetFileName(args.Path); } else if (Directory.Exists(args.Path)) { watcher.Path = args.Path; } else { Console.WriteLine("Path must be a file or directory"); Environment.Exit(-1); } watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Attributes | NotifyFilters.Security | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Add event handlers. watcher.Changed += (sender, e) => Run(args.TargetProgram, args.Arguments, args.Repeat); watcher.Created += (sender, e) => Run(args.TargetProgram, args.Arguments, args.Repeat); watcher.Deleted += (sender, e) => Run(args.TargetProgram, args.Arguments, args.Repeat); watcher.Renamed += (sender, e) => Run(args.TargetProgram, args.Arguments, args.Repeat); // Begin watching. watcher.EnableRaisingEvents = true; Console.WriteLine("Press Key to End"); Console.ReadKey(); } } [ArgActionMethod, ArgDescription("Watch for changes in http response")] public void Http(HttpArgs args) { bool stopThread = false; var t = new Thread(new ThreadStart(() => { DateTime defaultDateTime = new DateTime(100, 1, 1); DateTime previouslastModified = defaultDateTime; string previousETag = ""; var sha1 = System.Security.Cryptography.SHA1.Create(); byte[] previousHash = null; while (!stopThread) { HttpWebRequest request = HttpWebRequest.CreateHttp(args.Uri); request.Method = "GET"; bool runTarget = false; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { var currentEtag = response.Headers.GetValues("ETag"); if (currentEtag != null && currentEtag.Count() > 0) { // set initial etag state if (string.IsNullOrWhiteSpace(previousETag)) { previousETag = currentEtag[0]; } if (!string.Equals(previousETag, currentEtag[0], StringComparison.InvariantCultureIgnoreCase)) { previousETag = currentEtag[0]; // run program runTarget = true; } } // check last modified var currentLastModifiedStr = response.Headers.GetValues("Last-Modified"); if (currentLastModifiedStr != null && currentLastModifiedStr.Count() > 0 ) { DateTime currentLastModified = DateTime.Parse(currentLastModifiedStr[0]); // set initial modified state if (previouslastModified == defaultDateTime) { previouslastModified = currentLastModified; } // check modified data is newer if (previouslastModified < currentLastModified) { previouslastModified = currentLastModified; // run program runTarget = true; } } // no etag or last modified so compare contents if (string.IsNullOrWhiteSpace(previousETag) && previouslastModified == defaultDateTime) { using (Stream s = response.GetResponseStream()) { var currentHash = sha1.ComputeHash(s); // set initial hash if(previousHash == null) { previousHash = currentHash; } // check hashes are not equal if(!Equals(previousHash, currentHash)) { previousHash = currentHash; // run program runTarget = true; } } } // run program if (runTarget) { Run(args.TargetProgram, args.Arguments, args.Repeat); } } Thread.Sleep(args.Interval); } })); t.SetApartmentState(ApartmentState.STA); t.Start(); Console.WriteLine("Press Key to End"); Console.ReadKey(); try { stopThread = true; t.Abort(); } catch (Exception e) {} } private bool Equals(byte[] h1, byte[] h2) { if (h1.Length != h2.Length) { return false; } for(int i = h1.Length; i < h1.Length; i++) { if (h1[i] != h2[i]) { return false; } } return true; } [ArgActionMethod, ArgDescription("Watch for changes in Ftp response")] public void FTP(FtpArgs args) { bool stopThread = false; var t = new Thread(new ThreadStart(() => { DateTime defaultDateTime = new DateTime(100, 1, 1); DateTime previouslastModified = defaultDateTime; while (!stopThread) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(args.Uri); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; request.Credentials = new NetworkCredential(args.UserName, args.Password); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // set initial modified state if (previouslastModified == defaultDateTime) { previouslastModified = response.LastModified; } // check datetime if(previouslastModified < response.LastModified) { previouslastModified = response.LastModified; // run program Run(args.TargetProgram, args.Arguments, args.Repeat); } } Thread.Sleep(args.Interval); } })); t.SetApartmentState(ApartmentState.STA); t.Start(); Console.WriteLine("Press Key to End"); Console.ReadKey(); try { stopThread = true; t.Abort(); } catch (Exception e) {} } private int CurrentRepetitions = 0; private void Run(string TargetProgram, string Arguments, int Repetitions) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = TargetProgram; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = Arguments; try { Console.WriteLine("{0} {1}", TargetProgram, Arguments); // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } CurrentRepetitions++; if (Repetitions != 0 && CurrentRepetitions >= Repetitions) { Environment.Exit(0); } } catch { // Log error. //Console.WriteLine("{0} {1}", TargetProgram, Arguments); } } } public class DefaultTriggerArgs { [ArgRequired, ArgDescription("The target program that is triggered"), ArgShortcut("t"), ArgPosition(1)] public string TargetProgram { get; set; } [ArgDescription("Arguments passed to program when Clipboard is updated."), ArgShortcut("a"), ArgPosition(2)] public string Arguments { get; set; } [ArgDescription("Number of times to repeat watch and trigger. 0 is indefinitely"), ArgShortcut("r"), DefaultValue(0), ArgRange(0, int.MaxValue)] public int Repeat { get; set; } } public class ClipboardArgs : DefaultTriggerArgs { [ArgDescription("Interval in which to poll clipboard in ms"), ArgShortcut("i"), DefaultValue(500), ArgRange(0, int.MaxValue)] public int Interval { get; set; } } public class FileSystemArgs : DefaultTriggerArgs { [ArgRequired, ArgDescription("Path to file or directory to be monitored"), ArgShortcut("p"), ArgPosition(3)] public string Path { get; set; } } public class HttpArgs : DefaultTriggerArgs { [ArgDescription("Interval in which to poll http resource in ms"), ArgShortcut("i"), DefaultValue(5000), ArgRange(0, int.MaxValue)] public int Interval { get; set; } [ArgRequired, ArgDescription("Uri to resource"), ArgShortcut("u"), ArgPosition(3)] public Uri Uri { get; set; } } public class FtpArgs : DefaultTriggerArgs { [ArgRequired, ArgDescription("account username"), ArgShortcut("un"), ArgPosition(3)] public string UserName { get; set; } [ArgRequired, ArgDescription("account password"), ArgShortcut("pw"), ArgPosition(4)] public string Password { get; set; } [ArgDescription("Interval in which to poll ftp resource in ms"), ArgShortcut("i"), DefaultValue(5000), ArgRange(0, int.MaxValue)] public int Interval { get; set; } [ArgRequired, ArgDescription("Uri to resource"), ArgShortcut("u"), ArgPosition(5)] public Uri Uri { get; set; } } }
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 Radio : IEquatable<Radio> { /// <summary> /// Specifies the page number on which the tab is located. /// </summary> /// <value>Specifies the page number on which the tab is located.</value> [DataMember(Name="pageNumber", EmitDefaultValue=false)] public string PageNumber { get; set; } /// <summary> /// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position. /// </summary> /// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value> [DataMember(Name="xPosition", EmitDefaultValue=false)] public string XPosition { get; set; } /// <summary> /// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position. /// </summary> /// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value> [DataMember(Name="yPosition", EmitDefaultValue=false)] public string YPosition { get; set; } /// <summary> /// Anchor text information for a radio button. /// </summary> /// <value>Anchor text information for a radio button.</value> [DataMember(Name="anchorString", EmitDefaultValue=false)] public string AnchorString { get; set; } /// <summary> /// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString. /// </summary> /// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value> [DataMember(Name="anchorXOffset", EmitDefaultValue=false)] public string AnchorXOffset { get; set; } /// <summary> /// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString. /// </summary> /// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value> [DataMember(Name="anchorYOffset", EmitDefaultValue=false)] public string AnchorYOffset { get; set; } /// <summary> /// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches. /// </summary> /// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value> [DataMember(Name="anchorUnits", EmitDefaultValue=false)] public string AnchorUnits { get; set; } /// <summary> /// When set to **true**, this tab is ignored if anchorString is not found in the document. /// </summary> /// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value> [DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)] public string AnchorIgnoreIfNotPresent { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)] public string AnchorCaseSensitive { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)] public string AnchorMatchWholeWord { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)] public string AnchorHorizontalAlignment { get; set; } /// <summary> /// Specifies the value of the tab. /// </summary> /// <value>Specifies the value of the tab.</value> [DataMember(Name="value", EmitDefaultValue=false)] public string Value { get; set; } /// <summary> /// When set to **true**, the radio button is selected. /// </summary> /// <value>When set to **true**, the radio button is selected.</value> [DataMember(Name="selected", EmitDefaultValue=false)] public string Selected { get; set; } /// <summary> /// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. /// </summary> /// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].</value> [DataMember(Name="tabId", EmitDefaultValue=false)] public string TabId { get; set; } /// <summary> /// When set to **true**, the signer is required to fill out this tab /// </summary> /// <value>When set to **true**, the signer is required to fill out this tab</value> [DataMember(Name="required", EmitDefaultValue=false)] public string Required { get; set; } /// <summary> /// When set to **true**, the signer cannot change the data of the custom tab. /// </summary> /// <value>When set to **true**, the signer cannot change the data of the custom tab.</value> [DataMember(Name="locked", EmitDefaultValue=false)] public string Locked { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { 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 Radio {\n"); sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); sb.Append(" XPosition: ").Append(XPosition).Append("\n"); sb.Append(" YPosition: ").Append(YPosition).Append("\n"); sb.Append(" AnchorString: ").Append(AnchorString).Append("\n"); sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n"); sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n"); sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n"); sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n"); sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n"); sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n"); sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" Selected: ").Append(Selected).Append("\n"); sb.Append(" TabId: ").Append(TabId).Append("\n"); sb.Append(" Required: ").Append(Required).Append("\n"); sb.Append(" Locked: ").Append(Locked).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).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 Radio); } /// <summary> /// Returns true if Radio instances are equal /// </summary> /// <param name="other">Instance of Radio to be compared</param> /// <returns>Boolean</returns> public bool Equals(Radio other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.PageNumber == other.PageNumber || this.PageNumber != null && this.PageNumber.Equals(other.PageNumber) ) && ( this.XPosition == other.XPosition || this.XPosition != null && this.XPosition.Equals(other.XPosition) ) && ( this.YPosition == other.YPosition || this.YPosition != null && this.YPosition.Equals(other.YPosition) ) && ( this.AnchorString == other.AnchorString || this.AnchorString != null && this.AnchorString.Equals(other.AnchorString) ) && ( this.AnchorXOffset == other.AnchorXOffset || this.AnchorXOffset != null && this.AnchorXOffset.Equals(other.AnchorXOffset) ) && ( this.AnchorYOffset == other.AnchorYOffset || this.AnchorYOffset != null && this.AnchorYOffset.Equals(other.AnchorYOffset) ) && ( this.AnchorUnits == other.AnchorUnits || this.AnchorUnits != null && this.AnchorUnits.Equals(other.AnchorUnits) ) && ( this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent || this.AnchorIgnoreIfNotPresent != null && this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent) ) && ( this.AnchorCaseSensitive == other.AnchorCaseSensitive || this.AnchorCaseSensitive != null && this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive) ) && ( this.AnchorMatchWholeWord == other.AnchorMatchWholeWord || this.AnchorMatchWholeWord != null && this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord) ) && ( this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment || this.AnchorHorizontalAlignment != null && this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ) && ( this.Selected == other.Selected || this.Selected != null && this.Selected.Equals(other.Selected) ) && ( this.TabId == other.TabId || this.TabId != null && this.TabId.Equals(other.TabId) ) && ( this.Required == other.Required || this.Required != null && this.Required.Equals(other.Required) ) && ( this.Locked == other.Locked || this.Locked != null && this.Locked.Equals(other.Locked) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ); } /// <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.PageNumber != null) hash = hash * 57 + this.PageNumber.GetHashCode(); if (this.XPosition != null) hash = hash * 57 + this.XPosition.GetHashCode(); if (this.YPosition != null) hash = hash * 57 + this.YPosition.GetHashCode(); if (this.AnchorString != null) hash = hash * 57 + this.AnchorString.GetHashCode(); if (this.AnchorXOffset != null) hash = hash * 57 + this.AnchorXOffset.GetHashCode(); if (this.AnchorYOffset != null) hash = hash * 57 + this.AnchorYOffset.GetHashCode(); if (this.AnchorUnits != null) hash = hash * 57 + this.AnchorUnits.GetHashCode(); if (this.AnchorIgnoreIfNotPresent != null) hash = hash * 57 + this.AnchorIgnoreIfNotPresent.GetHashCode(); if (this.AnchorCaseSensitive != null) hash = hash * 57 + this.AnchorCaseSensitive.GetHashCode(); if (this.AnchorMatchWholeWord != null) hash = hash * 57 + this.AnchorMatchWholeWord.GetHashCode(); if (this.AnchorHorizontalAlignment != null) hash = hash * 57 + this.AnchorHorizontalAlignment.GetHashCode(); if (this.Value != null) hash = hash * 57 + this.Value.GetHashCode(); if (this.Selected != null) hash = hash * 57 + this.Selected.GetHashCode(); if (this.TabId != null) hash = hash * 57 + this.TabId.GetHashCode(); if (this.Required != null) hash = hash * 57 + this.Required.GetHashCode(); if (this.Locked != null) hash = hash * 57 + this.Locked.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 57 + this.ErrorDetails.GetHashCode(); return hash; } } } }
/** * Copyright (c) 2015, GruntTheDivine 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 copyright holder 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.IO; using System.Net; using System.Threading; using System.Reflection; using System.Collections.Generic; using Iodine.Compiler; using Iodine.Runtime; using Iodine.Runtime.Debug; namespace Iodine { public class IodineEntry { private static IodineContext context; public static void Main (string[] args) { context = IodineContext.Create (); AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => { if (e.ExceptionObject is UnhandledIodineExceptionException) { HandleIodineException (e.ExceptionObject as UnhandledIodineExceptionException); } }; IodineOptions options = IodineOptions.Parse (args); context.ShouldCache = !options.SupressAutoCache; context.ShouldOptimize = !options.SupressOptimizer; ExecuteOptions (options); } private static void HandleIodineException (UnhandledIodineExceptionException ex) { Console.Error.WriteLine ( "An unhandled {0} has occured!", ex.OriginalException.TypeDef.Name ); Console.Error.WriteLine ( "\tMessage: {0}", ex.OriginalException.GetAttribute ("message").ToString () ); Console.WriteLine (); ex.PrintStack (); Console.Error.WriteLine (); Panic ("Program terminated."); } private static bool WaitForDebugger ( TraceType type, VirtualMachine vm, StackFrame frame, SourceLocation location) { Console.WriteLine ("Waiting for debugger..."); return true; } private static void ExecuteOptions (IodineOptions options) { if (options.DebugFlag) { RunDebugServer (); } if (options.WarningFlag) { context.WarningFilter = WarningType.SyntaxWarning; } if (options.SupressWarningFlag) { context.WarningFilter = WarningType.None; } switch (options.InterpreterAction) { case InterpreterAction.Check: CheckIfFileExists (options.FileName); CheckSourceUnit (options, SourceUnit.CreateFromFile (options.FileName)); break; case InterpreterAction.ShowVersion: DisplayInfo (); break; case InterpreterAction.ShowHelp: DisplayUsage (); break; case InterpreterAction.EvaluateFile: CheckIfFileExists (options.FileName); EvalSourceUnit (options, SourceUnit.CreateFromFile (options.FileName)); break; case InterpreterAction.EvaluateArgument: EvalSourceUnit (options, SourceUnit.CreateFromSource (options.FileName)); break; case InterpreterAction.Repl: LaunchRepl (options); break; } } private static void CheckIfFileExists (string file) { if (!File.Exists (file)) { Panic ("Could not find file '{0}'", file); } } private static void LaunchRepl (IodineOptions options, IodineModule module = null) { string interpreterDir = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ().Location ); if (module != null) { foreach (KeyValuePair<string, IodineObject> kv in module.Attributes) { context.Globals [kv.Key] = kv.Value; } } string iosh = Path.Combine (interpreterDir, "tools", "iosh.id"); if (File.Exists (iosh) && !options.FallBackFlag) { EvalSourceUnit (options, SourceUnit.CreateFromFile (iosh)); } else { ReplShell shell = new ReplShell (context); shell.Run (); } } private static void EvalSourceUnit (IodineOptions options, SourceUnit unit) { try { IodineModule module = unit.Compile (context); if (context.Debug) { context.VirtualMachine.SetTrace (WaitForDebugger); } do { context.Invoke (module, new IodineObject[] { }); if (module.HasAttribute ("main")) { context.Invoke (module.GetAttribute ("main"), new IodineObject[] { options.IodineArguments }); } } while (options.LoopFlag); if (options.ReplFlag) { LaunchRepl (options, module); } } catch (UnhandledIodineExceptionException ex) { HandleIodineException (ex); } catch (SyntaxException ex) { DisplayErrors (ex.ErrorLog); Panic ("Compilation failed with {0} errors!", ex.ErrorLog.ErrorCount); } catch (ModuleNotFoundException ex) { Console.Error.WriteLine (ex.ToString ()); Panic ("Program terminated."); } catch (Exception e) { Console.Error.WriteLine ("Fatal exception has occured!"); Console.Error.WriteLine (e.Message); Console.Error.WriteLine ("Stack trace: \n{0}", e.StackTrace); Console.Error.WriteLine ( "\nIodine stack trace \n{0}", context.VirtualMachine.GetStackTrace () ); Panic ("Program terminated."); } } private static void CheckSourceUnit (IodineOptions options, SourceUnit unit) { try { context.ShouldCache = false; unit.Compile (context); } catch (SyntaxException ex) { DisplayErrors (ex.ErrorLog); } } private static void RunDebugServer () { DebugServer server = new DebugServer (context.VirtualMachine); Thread debugThread = new Thread (() => { server.Start (new IPEndPoint (IPAddress.Loopback, 6569)); }); debugThread.Start (); Console.WriteLine ("Debug server listening on 127.0.0.1:6569"); } private static IodineConfiguration LoadConfiguration () { if (IsUnix ()) { if (File.Exists ("/etc/iodine.conf")) { return IodineConfiguration.Load ("/etc/iodine.conf"); } } string exePath = Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location); string commonAppData = Environment.GetFolderPath ( Environment.SpecialFolder.CommonApplicationData ); string appData = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); if (File.Exists (Path.Combine (exePath, "iodine.conf"))) { return IodineConfiguration.Load (Path.Combine (exePath, "iodine.conf")); } if (File.Exists (Path.Combine (commonAppData, "iodine.conf"))) { return IodineConfiguration.Load (Path.Combine (commonAppData, "iodine.conf")); } if (File.Exists (Path.Combine (appData, "iodine.conf"))) { return IodineConfiguration.Load (Path.Combine (appData, "iodine.conf")); } return new IodineConfiguration (); // If we can't find a configuration file, load the default } private static void DisplayInfo () { int major = Assembly.GetExecutingAssembly ().GetName ().Version.Major; int minor = Assembly.GetExecutingAssembly ().GetName ().Version.Minor; int patch = Assembly.GetExecutingAssembly ().GetName ().Version.Build; Console.WriteLine ("Iodine v{0}.{1}.{2}-alpha", major, minor, patch); Environment.Exit (0); } private static void DisplayErrors (ErrorSink errorLog) { Dictionary<string, string[]> lineDict = new Dictionary<string, string[]> (); foreach (Error err in errorLog) { SourceLocation loc = err.Location; if (!lineDict.ContainsKey (err.Location.File)) { lineDict [err.Location.File] = File.ReadAllLines (err.Location.File); } string[] lines = lineDict [err.Location.File]; Console.Error.WriteLine ("{0} ({1}:{2}) error ID{3:d4}: {4}", Path.GetFileName (loc.File), loc.Line, loc.Column, (int)err.ErrorID, err.Text ); string source = lines [loc.Line]; Console.Error.WriteLine (" {0}", source); Console.Error.WriteLine (" {0}", "^".PadLeft (loc.Column)); } } private static void DisplayUsage () { Console.WriteLine ("usage: iodine [option] ... [file] [arg] ..."); Console.WriteLine ("\n"); Console.WriteLine ("-c Check syntax only"); Console.WriteLine ("-d Run a debug server"); Console.WriteLine ("-e Evaluate a string of iodine code"); Console.WriteLine ("-f Use builtin fallback REPL shell instead of iosh"); Console.WriteLine ("-h Display this message"); Console.WriteLine ("-l Assume 'while (true) { ...}' loop around the program"); Console.WriteLine ("-r Launch an interactive REPL shell after the supplied program is ran"); Console.WriteLine ("-v Display the version of this interpreter"); Console.WriteLine ("-w Enable all warnings"); Console.WriteLine ("-x Disable all warnings"); Console.WriteLine ("--no-cache Do not cache compiled code"); Console.WriteLine ("--no-optimize Disable bytecode optimizations"); Environment.Exit (0); } private static void Panic (string format, params object[] args) { Console.Error.WriteLine (format, args); Environment.Exit (-1); } public static bool IsUnix () { int p = (int)Environment.OSVersion.Platform; return (p == 4) || (p == 6) || (p == 128); } } }
// 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.Globalization; using System.Linq; using Xunit; namespace System.Text.Tests { public partial class EncodingTest : IClassFixture<CultureSetup> { private const string AsciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static readonly char[] s_asciiPrintableCharArr = AsciiPrintable.ToCharArray(); public EncodingTest(CultureSetup setup) { // Setting up the culture happens externally, and only once, which is what we want. // xUnit will keep track of it, do nothing. } public static IEnumerable<object[]> CodePageInfo() { // The layout is code page, IANA(web) name, and query string. // Query strings may be undocumented, and IANA names will be returned from Encoding objects. // Entries are sorted by code page. yield return new object[] { 37, "ibm037", "ibm037" }; yield return new object[] { 37, "ibm037", "cp037" }; yield return new object[] { 37, "ibm037", "csibm037" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-us" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" }; yield return new object[] { 437, "ibm437", "ibm437" }; yield return new object[] { 437, "ibm437", "437" }; yield return new object[] { 437, "ibm437", "cp437" }; yield return new object[] { 437, "ibm437", "cspc8codepage437" }; yield return new object[] { 500, "ibm500", "ibm500" }; yield return new object[] { 500, "ibm500", "cp500" }; yield return new object[] { 500, "ibm500", "csibm500" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-be" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" }; yield return new object[] { 708, "asmo-708", "asmo-708" }; yield return new object[] { 720, "dos-720", "dos-720" }; yield return new object[] { 737, "ibm737", "ibm737" }; yield return new object[] { 775, "ibm775", "ibm775" }; yield return new object[] { 850, "ibm850", "ibm850" }; yield return new object[] { 850, "ibm850", "cp850" }; yield return new object[] { 852, "ibm852", "ibm852" }; yield return new object[] { 852, "ibm852", "cp852" }; yield return new object[] { 855, "ibm855", "ibm855" }; yield return new object[] { 855, "ibm855", "cp855" }; yield return new object[] { 857, "ibm857", "ibm857" }; yield return new object[] { 857, "ibm857", "cp857" }; yield return new object[] { 858, "ibm00858", "ibm00858" }; yield return new object[] { 858, "ibm00858", "ccsid00858" }; yield return new object[] { 858, "ibm00858", "cp00858" }; yield return new object[] { 858, "ibm00858", "cp858" }; yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" }; yield return new object[] { 860, "ibm860", "ibm860" }; yield return new object[] { 860, "ibm860", "cp860" }; yield return new object[] { 861, "ibm861", "ibm861" }; yield return new object[] { 861, "ibm861", "cp861" }; yield return new object[] { 862, "dos-862", "dos-862" }; yield return new object[] { 862, "dos-862", "cp862" }; yield return new object[] { 862, "dos-862", "ibm862" }; yield return new object[] { 863, "ibm863", "ibm863" }; yield return new object[] { 863, "ibm863", "cp863" }; yield return new object[] { 864, "ibm864", "ibm864" }; yield return new object[] { 864, "ibm864", "cp864" }; yield return new object[] { 865, "ibm865", "ibm865" }; yield return new object[] { 865, "ibm865", "cp865" }; yield return new object[] { 866, "cp866", "cp866" }; yield return new object[] { 866, "cp866", "ibm866" }; yield return new object[] { 869, "ibm869", "ibm869" }; yield return new object[] { 869, "ibm869", "cp869" }; yield return new object[] { 870, "ibm870", "ibm870" }; yield return new object[] { 870, "ibm870", "cp870" }; yield return new object[] { 870, "ibm870", "csibm870" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" }; yield return new object[] { 874, "windows-874", "windows-874" }; yield return new object[] { 874, "windows-874", "dos-874" }; yield return new object[] { 874, "windows-874", "iso-8859-11" }; yield return new object[] { 874, "windows-874", "tis-620" }; yield return new object[] { 875, "cp875", "cp875" }; yield return new object[] { 932, "shift_jis", "shift_jis" }; yield return new object[] { 932, "shift_jis", "csshiftjis" }; yield return new object[] { 932, "shift_jis", "cswindows31j" }; yield return new object[] { 932, "shift_jis", "ms_kanji" }; yield return new object[] { 932, "shift_jis", "shift-jis" }; yield return new object[] { 932, "shift_jis", "sjis" }; yield return new object[] { 932, "shift_jis", "x-ms-cp932" }; yield return new object[] { 932, "shift_jis", "x-sjis" }; yield return new object[] { 936, "gb2312", "gb2312" }; yield return new object[] { 936, "gb2312", "chinese" }; yield return new object[] { 936, "gb2312", "cn-gb" }; yield return new object[] { 936, "gb2312", "csgb2312" }; yield return new object[] { 936, "gb2312", "csgb231280" }; yield return new object[] { 936, "gb2312", "csiso58gb231280" }; yield return new object[] { 936, "gb2312", "gb_2312-80" }; yield return new object[] { 936, "gb2312", "gb231280" }; yield return new object[] { 936, "gb2312", "gb2312-80" }; yield return new object[] { 936, "gb2312", "gbk" }; yield return new object[] { 936, "gb2312", "iso-ir-58" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" }; yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" }; yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" }; yield return new object[] { 949, "ks_c_5601-1987", "korean" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" }; yield return new object[] { 950, "big5", "big5" }; yield return new object[] { 950, "big5", "big5-hkscs" }; yield return new object[] { 950, "big5", "cn-big5" }; yield return new object[] { 950, "big5", "csbig5" }; yield return new object[] { 950, "big5", "x-x-big5" }; yield return new object[] { 1026, "ibm1026", "ibm1026" }; yield return new object[] { 1026, "ibm1026", "cp1026" }; yield return new object[] { 1026, "ibm1026", "csibm1026" }; yield return new object[] { 1047, "ibm01047", "ibm01047" }; yield return new object[] { 1140, "ibm01140", "ibm01140" }; yield return new object[] { 1140, "ibm01140", "ccsid01140" }; yield return new object[] { 1140, "ibm01140", "cp01140" }; yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" }; yield return new object[] { 1141, "ibm01141", "ibm01141" }; yield return new object[] { 1141, "ibm01141", "ccsid01141" }; yield return new object[] { 1141, "ibm01141", "cp01141" }; yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" }; yield return new object[] { 1142, "ibm01142", "ibm01142" }; yield return new object[] { 1142, "ibm01142", "ccsid01142" }; yield return new object[] { 1142, "ibm01142", "cp01142" }; yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" }; yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" }; yield return new object[] { 1143, "ibm01143", "ibm01143" }; yield return new object[] { 1143, "ibm01143", "ccsid01143" }; yield return new object[] { 1143, "ibm01143", "cp01143" }; yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" }; yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" }; yield return new object[] { 1144, "ibm01144", "ibm01144" }; yield return new object[] { 1144, "ibm01144", "ccsid01144" }; yield return new object[] { 1144, "ibm01144", "cp01144" }; yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" }; yield return new object[] { 1145, "ibm01145", "ibm01145" }; yield return new object[] { 1145, "ibm01145", "ccsid01145" }; yield return new object[] { 1145, "ibm01145", "cp01145" }; yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" }; yield return new object[] { 1146, "ibm01146", "ibm01146" }; yield return new object[] { 1146, "ibm01146", "ccsid01146" }; yield return new object[] { 1146, "ibm01146", "cp01146" }; yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" }; yield return new object[] { 1147, "ibm01147", "ibm01147" }; yield return new object[] { 1147, "ibm01147", "ccsid01147" }; yield return new object[] { 1147, "ibm01147", "cp01147" }; yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" }; yield return new object[] { 1148, "ibm01148", "ibm01148" }; yield return new object[] { 1148, "ibm01148", "ccsid01148" }; yield return new object[] { 1148, "ibm01148", "cp01148" }; yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" }; yield return new object[] { 1149, "ibm01149", "ibm01149" }; yield return new object[] { 1149, "ibm01149", "ccsid01149" }; yield return new object[] { 1149, "ibm01149", "cp01149" }; yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" }; yield return new object[] { 1250, "windows-1250", "windows-1250" }; yield return new object[] { 1250, "windows-1250", "x-cp1250" }; yield return new object[] { 1251, "windows-1251", "windows-1251" }; yield return new object[] { 1251, "windows-1251", "x-cp1251" }; yield return new object[] { 1252, "windows-1252", "windows-1252" }; yield return new object[] { 1252, "windows-1252", "x-ansi" }; yield return new object[] { 1253, "windows-1253", "windows-1253" }; yield return new object[] { 1254, "windows-1254", "windows-1254" }; yield return new object[] { 1255, "windows-1255", "windows-1255" }; yield return new object[] { 1256, "windows-1256", "windows-1256" }; yield return new object[] { 1256, "windows-1256", "cp1256" }; yield return new object[] { 1257, "windows-1257", "windows-1257" }; yield return new object[] { 1258, "windows-1258", "windows-1258" }; yield return new object[] { 1361, "johab", "johab" }; yield return new object[] { 10000, "macintosh", "macintosh" }; yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" }; yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" }; yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" }; yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" }; yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" }; yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" }; yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" }; yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" }; yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" }; yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" }; yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" }; yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" }; yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" }; yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" }; yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" }; yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" }; yield return new object[] { 20001, "x-cp20001", "x-cp20001" }; yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" }; yield return new object[] { 20003, "x-cp20003", "x-cp20003" }; yield return new object[] { 20004, "x-cp20004", "x-cp20004" }; yield return new object[] { 20005, "x-cp20005", "x-cp20005" }; yield return new object[] { 20105, "x-ia5", "x-ia5" }; yield return new object[] { 20105, "x-ia5", "irv" }; yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" }; yield return new object[] { 20106, "x-ia5-german", "din_66003" }; yield return new object[] { 20106, "x-ia5-german", "german" }; yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" }; yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" }; yield return new object[] { 20107, "x-ia5-swedish", "swedish" }; yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" }; yield return new object[] { 20261, "x-cp20261", "x-cp20261" }; yield return new object[] { 20269, "x-cp20269", "x-cp20269" }; yield return new object[] { 20273, "ibm273", "ibm273" }; yield return new object[] { 20273, "ibm273", "cp273" }; yield return new object[] { 20273, "ibm273", "csibm273" }; yield return new object[] { 20277, "ibm277", "ibm277" }; yield return new object[] { 20277, "ibm277", "csibm277" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" }; yield return new object[] { 20278, "ibm278", "ibm278" }; yield return new object[] { 20278, "ibm278", "cp278" }; yield return new object[] { 20278, "ibm278", "csibm278" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" }; yield return new object[] { 20280, "ibm280", "ibm280" }; yield return new object[] { 20280, "ibm280", "cp280" }; yield return new object[] { 20280, "ibm280", "csibm280" }; yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" }; yield return new object[] { 20284, "ibm284", "ibm284" }; yield return new object[] { 20284, "ibm284", "cp284" }; yield return new object[] { 20284, "ibm284", "csibm284" }; yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" }; yield return new object[] { 20285, "ibm285", "ibm285" }; yield return new object[] { 20285, "ibm285", "cp285" }; yield return new object[] { 20285, "ibm285", "csibm285" }; yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" }; yield return new object[] { 20290, "ibm290", "ibm290" }; yield return new object[] { 20290, "ibm290", "cp290" }; yield return new object[] { 20290, "ibm290", "csibm290" }; yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" }; yield return new object[] { 20297, "ibm297", "ibm297" }; yield return new object[] { 20297, "ibm297", "cp297" }; yield return new object[] { 20297, "ibm297", "csibm297" }; yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" }; yield return new object[] { 20420, "ibm420", "ibm420" }; yield return new object[] { 20420, "ibm420", "cp420" }; yield return new object[] { 20420, "ibm420", "csibm420" }; yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" }; yield return new object[] { 20423, "ibm423", "ibm423" }; yield return new object[] { 20423, "ibm423", "cp423" }; yield return new object[] { 20423, "ibm423", "csibm423" }; yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" }; yield return new object[] { 20424, "ibm424", "ibm424" }; yield return new object[] { 20424, "ibm424", "cp424" }; yield return new object[] { 20424, "ibm424", "csibm424" }; yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" }; yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" }; yield return new object[] { 20838, "ibm-thai", "ibm-thai" }; yield return new object[] { 20838, "ibm-thai", "csibmthai" }; yield return new object[] { 20866, "koi8-r", "koi8-r" }; yield return new object[] { 20866, "koi8-r", "cskoi8r" }; yield return new object[] { 20866, "koi8-r", "koi" }; yield return new object[] { 20866, "koi8-r", "koi8" }; yield return new object[] { 20866, "koi8-r", "koi8r" }; yield return new object[] { 20871, "ibm871", "ibm871" }; yield return new object[] { 20871, "ibm871", "cp871" }; yield return new object[] { 20871, "ibm871", "csibm871" }; yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" }; yield return new object[] { 20880, "ibm880", "ibm880" }; yield return new object[] { 20880, "ibm880", "cp880" }; yield return new object[] { 20880, "ibm880", "csibm880" }; yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" }; yield return new object[] { 20905, "ibm905", "ibm905" }; yield return new object[] { 20905, "ibm905", "cp905" }; yield return new object[] { 20905, "ibm905", "csibm905" }; yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" }; yield return new object[] { 20924, "ibm00924", "ibm00924" }; yield return new object[] { 20924, "ibm00924", "ccsid00924" }; yield return new object[] { 20924, "ibm00924", "cp00924" }; yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" }; yield return new object[] { 20932, "euc-jp", "euc-jp" }; yield return new object[] { 20936, "x-cp20936", "x-cp20936" }; yield return new object[] { 20949, "x-cp20949", "x-cp20949" }; yield return new object[] { 21025, "cp1025", "cp1025" }; yield return new object[] { 21866, "koi8-u", "koi8-u" }; yield return new object[] { 21866, "koi8-u", "koi8-ru" }; yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" }; yield return new object[] { 28592, "iso-8859-2", "csisolatin2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" }; yield return new object[] { 28592, "iso-8859-2", "iso8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" }; yield return new object[] { 28592, "iso-8859-2", "l2" }; yield return new object[] { 28592, "iso-8859-2", "latin2" }; yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" }; yield return new object[] { 28593, "iso-8859-3", "csisolatin3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" }; yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" }; yield return new object[] { 28593, "iso-8859-3", "l3" }; yield return new object[] { 28593, "iso-8859-3", "latin3" }; yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" }; yield return new object[] { 28594, "iso-8859-4", "csisolatin4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" }; yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" }; yield return new object[] { 28594, "iso-8859-4", "l4" }; yield return new object[] { 28594, "iso-8859-4", "latin4" }; yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" }; yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" }; yield return new object[] { 28595, "iso-8859-5", "cyrillic" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" }; yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" }; yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" }; yield return new object[] { 28596, "iso-8859-6", "arabic" }; yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" }; yield return new object[] { 28596, "iso-8859-6", "ecma-114" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" }; yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" }; yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" }; yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" }; yield return new object[] { 28597, "iso-8859-7", "ecma-118" }; yield return new object[] { 28597, "iso-8859-7", "elot_928" }; yield return new object[] { 28597, "iso-8859-7", "greek" }; yield return new object[] { 28597, "iso-8859-7", "greek8" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" }; yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" }; yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" }; yield return new object[] { 28598, "iso-8859-8", "hebrew" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" }; yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" }; yield return new object[] { 28598, "iso-8859-8", "logical" }; yield return new object[] { 28598, "iso-8859-8", "visual" }; yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" }; yield return new object[] { 28599, "iso-8859-9", "csisolatin5" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" }; yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" }; yield return new object[] { 28599, "iso-8859-9", "l5" }; yield return new object[] { 28599, "iso-8859-9", "latin5" }; yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" }; yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" }; yield return new object[] { 28605, "iso-8859-15", "csisolatin9" }; yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" }; yield return new object[] { 28605, "iso-8859-15", "l9" }; yield return new object[] { 28605, "iso-8859-15", "latin9" }; yield return new object[] { 29001, "x-europa", "x-europa" }; yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" }; yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" }; yield return new object[] { 50222, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" }; yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" }; yield return new object[] { 50227, "x-cp50227", "x-cp50227" }; yield return new object[] { 50227, "x-cp50227", "cp50227" }; yield return new object[] { 51932, "euc-jp", "euc-jp" }; yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" }; yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" }; yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" }; yield return new object[] { 51932, "euc-jp", "x-euc" }; yield return new object[] { 51932, "euc-jp", "x-euc-jp" }; yield return new object[] { 51936, "euc-cn", "euc-cn" }; yield return new object[] { 51936, "euc-cn", "x-euc-cn" }; yield return new object[] { 51949, "euc-kr", "euc-kr" }; yield return new object[] { 51949, "euc-kr", "cseuckr" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" }; yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" }; yield return new object[] { 54936, "gb18030", "gb18030" }; yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" }; yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" }; yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" }; yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" }; yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" }; yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" }; yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" }; yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" }; yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" }; yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" }; } public static IEnumerable<object[]> SpecificCodepageEncodings() { // Layout is codepage encoding, bytes, and matching unicode string. yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" }; yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } , "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"}; yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" }; yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } , "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"}; } public static IEnumerable<object[]> MultibyteCharacterEncodings() { // Layout is the encoding, bytes, and expected result. yield return new object[] { "iso-2022-jp", new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }, new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43} }; yield return new object[] { "GB18030", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }, new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 } }; yield return new object[] { "shift_jis", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 }, new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 } }; yield return new object[] { "iso-2022-kr", new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }, new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E } }; yield return new object[] { "hz-gb-2312", new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }, new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, } }; } private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings() { yield return Map(1200, "utf-16"); yield return Map(12000, "utf-32"); yield return Map(20127, "us-ascii"); yield return Map(65000, "utf-7"); yield return Map(65001, "utf-8"); } private static KeyValuePair<int, string> Map(int codePage, string webName) { return new KeyValuePair<int, string>(codePage, webName); } [Fact] public static void TestDefaultEncodings() { ValidateDefaultEncodings(); // The default encoding should be something from the known list. Encoding defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); if (defaultEncoding.CodePage == Encoding.UTF8.CodePage) { // if the default encoding is not UTF8 that means either we are running on the full framework // or the encoding provider is registered throw the call Encoding.RegisterProvider. // at that time we shouldn't expect exceptions when creating the following encodings. foreach (object[] mapping in CodePageInfo()) { Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0])); AssertExtensions.Throws<ArgumentException>("name", () => Encoding.GetEncoding((string)mapping[2])); } // Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present. // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings()); } // Add the code page provider. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Make sure added code pages are identical between the provider and the Encoding class. foreach (object[] mapping in CodePageInfo()) { Encoding encoding = Encoding.GetEncoding((int)mapping[0]); Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]); Assert.Equal(encoding, codePageEncoding); Assert.Equal(encoding.CodePage, (int)mapping[0]); Assert.Equal(encoding.WebName, (string)mapping[1]); // Get encoding via query string. Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2])); } // Adding the code page provider should keep the originals, too. ValidateDefaultEncodings(); // Currently the class EncodingInfo isn't present in corefx, so this checks the complete list // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)), // Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // Default encoding may have changed, should still be something on the combined list. defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])))); TestRegister1252(); } private static void ValidateDefaultEncodings() { foreach (var mapping in CrossplatformDefaultEncodings()) { Encoding encoding = Encoding.GetEncoding(mapping.Key); Assert.NotNull(encoding); Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value)); Assert.Equal(mapping.Value, encoding.WebName); } } [Theory] [MemberData(nameof(SpecificCodepageEncodings))] public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName); string encoded = encoding.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, encoded); Assert.Equal(bytes, encoding.GetBytes(encoded)); byte[] resultBytes = encoding.GetBytes(encoded); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestCodepageEncoding(int codePage, string webName, string queryString) { Encoding encoding; // There are two names that have duplicate associated CodePages. For those two names, // we have to test with the expectation that querying the name will always return the // same codepage. if (codePage != 20932 && codePage != 50222) { encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage)); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } else { encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(queryString)); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } Assert.NotNull(encoding); Assert.Equal(codePage, encoding.CodePage); Assert.Equal(webName, encoding.WebName); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. char[] traveled = encoding.GetChars(encoding.GetBytes(AsciiPrintable)); Assert.Equal(s_asciiPrintableCharArr, traveled); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestEncoderNLSAndDecoderNLSValidateDataRoundTrips(int codePage, string webName, string queryString) { Encoding encoding; if (codePage != 20932 && codePage != 50222) { encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); } else { encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); } Encoder encoder = encoding.GetEncoder(); Decoder decoder = encoding.GetDecoder(); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. int asciiPrintableLength = s_asciiPrintableCharArr.Length; int encodedByteCount = encoding.GetByteCount(s_asciiPrintableCharArr); byte[] encodedBytes = new byte[encodedByteCount]; char[] decodedChars = new char[asciiPrintableLength]; int encodedLength = encoder.GetBytes(s_asciiPrintableCharArr, 0, asciiPrintableLength, encodedBytes, 0, false); Assert.Equal(encodedByteCount, encodedLength); int decodedLength = decoder.GetChars(encodedBytes, 0, encodedByteCount, decodedChars, 0); Assert.Equal(asciiPrintableLength, decodedLength); Assert.Equal(s_asciiPrintableCharArr, decodedChars); } [Theory] [MemberData(nameof(MultibyteCharacterEncodings))] public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected) { Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder(); char[] buffer = new char[expected.Length]; for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount) { charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex); } Assert.Equal(expected, buffer.Select(c => (int)c)); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestEncodingDisplayNames(int codePage, string webName, string queryString) { var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); string name = encoding.EncodingName; // Names can't be empty, and must be printable characters. Assert.False(string.IsNullOrWhiteSpace(name)); Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c)); } // This test is run as part of the default mappings test, since it modifies global state which that test // depends on. private static void TestRegister1252() { // This test case ensure we can map all 1252 codepage codepoints without any exception. string s1252Result = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f" + "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" + "\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027\u0028\u0029\u002a\u002b\u002c\u002d\u002e\u002f" + "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039\u003a\u003b\u003c\u003d\u003e\u003f" + "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f" + "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057\u0058\u0059\u005a\u005b\u005c\u005d\u005e\u005f" + "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f" + "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077\u0078\u0079\u007a\u007b\u007c\u007d\u007e\u007f" + "\u20ac\u0081\u201a\u0192\u201e\u2026\u2020\u2021\u02c6\u2030\u0160\u2039\u0152\u008d\u017d\u008f" + "\u0090\u2018\u2019\u201c\u201d\u2022\u2013\u2014\u02dc\u2122\u0161\u203a\u0153\u009d\u017e\u0178" + "\u00a0\u00a1\u00a2\u00a3\u00a4\u00a5\u00a6\u00a7\u00a8\u00a9\u00aa\u00ab\u00ac\u00ad\u00ae\u00af" + "\u00b0\u00b1\u00b2\u00b3\u00b4\u00b5\u00b6\u00b7\u00b8\u00b9\u00ba\u00bb\u00bc\u00bd\u00be\u00bf" + "\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf" + "\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d7\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de\u00df" + "\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef" + "\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f7\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff"; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding win1252 = Encoding.GetEncoding("windows-1252", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); byte[] enc = new byte[256]; for (int j = 0; j < 256; j++) { enc[j] = (byte)j; } Assert.Equal(s1252Result, win1252.GetString(enc)); } } public class CultureSetup : IDisposable { private readonly CultureInfo _originalUICulture; public CultureSetup() { _originalUICulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentUICulture = _originalUICulture; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Streams; namespace Orleans { /// <summary> /// Client runtime for connecting to Orleans system /// </summary> /// TODO: Make this class non-static and inject it where it is needed. public static class GrainClient { /// <summary> /// Whether the client runtime has already been initialized /// </summary> /// <returns><c>true</c> if client runtime is already initialized</returns> public static bool IsInitialized { get { return isFullyInitialized && RuntimeClient.Current != null; } } internal static ClientConfiguration CurrentConfig { get; private set; } internal static bool TestOnlyNoConnect { get; set; } private static bool isFullyInitialized = false; private static OutsideRuntimeClient outsideRuntimeClient; private static readonly object initLock = new Object(); // RuntimeClient.Current is set to something different than OutsideRuntimeClient - it can only be set to InsideRuntimeClient, since we only have 2. // That means we are running in side a silo. private static bool IsRunningInsideSilo { get { return RuntimeClient.Current != null && !(RuntimeClient.Current is OutsideRuntimeClient); } } //TODO: prevent client code from using this from inside a Grain or provider public static IGrainFactory GrainFactory { get { return GetGrainFactory(); } } private static IGrainFactory GetGrainFactory() { if (IsRunningInsideSilo) { // just in case, make sure we don't get NullRefExc when checking RuntimeContext. bool runningInsideGrain = RuntimeContext.Current != null && RuntimeContext.CurrentActivationContext != null && RuntimeContext.CurrentActivationContext.ContextType == SchedulingContextType.Activation; if (runningInsideGrain) { throw new OrleansException("You are running inside a grain. GrainClient.GrainFactory should only be used on the client side. " + "Inside a grain use GrainFactory property of the Grain base class (use this.GrainFactory)."); } else // running inside provider or else where { throw new OrleansException("You are running inside the provider code, on the silo. GrainClient.GrainFactory should only be used on the client side. " + "Inside the provider code use GrainFactory that is passed via IProviderRuntime (use providerRuntime.GrainFactory)."); } } if (!IsInitialized) { throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory"); } return outsideRuntimeClient.InternalGrainFactory; } internal static IInternalGrainFactory InternalGrainFactory { get { if (!IsInitialized) { throw new OrleansException("You must initialize the Grain Client before accessing the InternalGrainFactory"); } return outsideRuntimeClient.InternalGrainFactory; } } /// <summary> /// Initializes the client runtime from the standard client configuration file. /// </summary> public static void Initialize() { ClientConfiguration config = ClientConfiguration.StandardLoad(); if (config == null) { Console.WriteLine("Error loading standard client configuration file."); throw new ArgumentException("Error loading standard client configuration file"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the provided client configuration file. /// If an error occurs reading the specified configuration file, the initialization fails. /// </summary> /// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param> public static void Initialize(string configFilePath) { Initialize(new FileInfo(configFilePath)); } /// <summary> /// Initializes the client runtime from the provided client configuration file. /// If an error occurs reading the specified configuration file, the initialization fails. /// </summary> /// <param name="configFile">The client configuration file.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Initialize(FileInfo configFile) { ClientConfiguration config; try { config = ClientConfiguration.LoadFromFile(configFile.FullName); } catch (Exception ex) { Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex); throw; } if (config == null) { Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName); throw new ArgumentException(String.Format("Error loading client configuration file {0}:", configFile.FullName), "configFile"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the provided client configuration object. /// If the configuration object is null, the initialization fails. /// </summary> /// <param name="config">A ClientConfiguration object.</param> public static void Initialize(ClientConfiguration config) { if (config == null) { Console.WriteLine("Initialize was called with null ClientConfiguration object."); throw new ArgumentException("Initialize was called with null ClientConfiguration object.", "config"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the standard client configuration file using the provided gateway address. /// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead. /// </summary> /// <param name="gatewayAddress">IP address and port of the gateway silo</param> /// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param> public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true) { var config = ClientConfiguration.StandardLoad(); if (config == null) { Console.WriteLine("Error loading standard client configuration file."); throw new ArgumentException("Error loading standard client configuration file"); } if (overrideConfig) { config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress }); } else if (!config.Gateways.Contains(gatewayAddress)) { config.Gateways.Add(gatewayAddress); } config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress); InternalInitialize(config); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static void InternalInitialize(ClientConfiguration config) { // We deliberately want to run this initialization code on .NET thread pool thread to escape any // TPL execution environment and avoid any conflicts with client's synchronization context var tcs = new TaskCompletionSource<ClientConfiguration>(); WaitCallback doInit = state => { try { if (TestOnlyNoConnect) { Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster."); } else { // Finish initializing this client connection to the Orleans cluster DoInternalInitialize(config); } tcs.SetResult(config); // Resolve promise } catch (Exception exc) { tcs.SetException(exc); // Break promise } }; // Queue Init call to thread pool thread ThreadPool.QueueUserWorkItem(doInit, null); try { CurrentConfig = tcs.Task.Result; // Wait for Init to finish } catch (AggregateException ae) { // Flatten the aggregate exception, which can be deeply nested. ae = ae.Flatten(); // If there is just one exception in the aggregate exception, throw that, otherwise throw the entire // flattened aggregate exception. var innerExceptions = ae.InnerExceptions; var exceptionToThrow = innerExceptions.Count == 1 ? innerExceptions[0] : ae; ExceptionDispatchInfo.Capture(exceptionToThrow).Throw(); } } /// <summary> /// Initializes client runtime from client configuration object. /// </summary> private static void DoInternalInitialize(ClientConfiguration config) { if (IsInitialized) return; lock (initLock) { if (!IsInitialized) { try { // this is probably overkill, but this ensures isFullyInitialized false // before we make a call that makes RuntimeClient.Current not null isFullyInitialized = false; outsideRuntimeClient = new OutsideRuntimeClient(config); // Keep reference, to avoid GC problems outsideRuntimeClient.Start(); // this needs to be the last successful step inside the lock so // IsInitialized doesn't return true until we're fully initialized isFullyInitialized = true; } catch (Exception exc) { // just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize. Console.WriteLine("Initialization failed. {0}", exc); InternalUninitialize(); throw; } } } } /// <summary> /// Uninitializes client runtime. /// </summary> public static void Uninitialize() { lock (initLock) { InternalUninitialize(); } } /// <summary> /// Test hook to uninitialize client without cleanup /// </summary> public static void HardKill() { lock (initLock) { InternalUninitialize(false); } } /// <summary> /// This is the lock free version of uninitilize so we can share /// it between the public method and error paths inside initialize. /// This should only be called inside a lock(initLock) block. /// </summary> private static void InternalUninitialize(bool cleanup = true) { // Update this first so IsInitialized immediately begins returning // false. Since this method should be protected externally by // a lock(initLock) we should be able to reset everything else // before the next init attempt. isFullyInitialized = false; if (RuntimeClient.Current != null) { try { RuntimeClient.Current.Reset(cleanup); } catch (Exception) { } RuntimeClient.Current = null; } outsideRuntimeClient = null; ClientInvokeCallback = null; } /// <summary> /// Check that the runtime is intialized correctly, and throw InvalidOperationException if not /// </summary> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> private static void CheckInitialized() { if (!IsInitialized) throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime."); } /// <summary> /// Provides logging facility for applications. /// </summary> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static Logger Logger { get { CheckInitialized(); return RuntimeClient.Current.AppLogger; } } /// <summary> /// Set a timeout for responses on this Orleans client. /// </summary> /// <param name="timeout"></param> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static void SetResponseTimeout(TimeSpan timeout) { CheckInitialized(); RuntimeClient.Current.SetResponseTimeout(timeout); } /// <summary> /// Get a timeout of responses on this Orleans client. /// </summary> /// <returns>The response timeout.</returns> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static TimeSpan GetResponseTimeout() { CheckInitialized(); return RuntimeClient.Current.GetResponseTimeout(); } /// <summary> /// Global pre-call interceptor function /// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain. /// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings /// such as <c>Orleans.RequestContext</c> will be picked up. /// The action receives an <see cref="InvokeMethodRequest"/> with details of the method to be invoked, including InterfaceId and MethodId, /// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through /// </summary> /// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks> public static Action<InvokeMethodRequest, IGrain> ClientInvokeCallback { get; set; } public static IEnumerable<Streams.IStreamProvider> GetStreamProviders() { return RuntimeClient.Current.CurrentStreamProviderManager.GetStreamProviders(); } internal static IStreamProviderRuntime CurrentStreamProviderRuntime { get { return RuntimeClient.Current.CurrentStreamProviderRuntime; } } public static Streams.IStreamProvider GetStreamProvider(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(name) as Streams.IStreamProvider; } public delegate void ConnectionToClusterLostHandler(object sender, EventArgs e); public static event ConnectionToClusterLostHandler ClusterConnectionLost; internal static void NotifyClusterConnectionLost() { try { // TODO: first argument should be 'this' when this class will no longer be static ClusterConnectionLost?.Invoke(null, EventArgs.Empty); } catch (Exception ex) { Logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex); } } internal static IList<Uri> Gateways { get { CheckInitialized(); return outsideRuntimeClient.Gateways; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Orchard.Caching; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.WebSite; using Orchard.Localization; using Orchard.Logging; using Orchard.Utility.Extensions; using Orchard.Exceptions; namespace Orchard.Environment.Extensions.Folders { public class ExtensionHarvester : IExtensionHarvester { private const string NameSection = "name"; private const string PathSection = "path"; private const string DescriptionSection = "description"; private const string VersionSection = "version"; private const string OrchardVersionSection = "orchardversion"; private const string AuthorSection = "author"; private const string WebsiteSection = "website"; private const string TagsSection = "tags"; private const string AntiForgerySection = "antiforgery"; private const string ZonesSection = "zones"; private const string BaseThemeSection = "basetheme"; private const string DependenciesSection = "dependencies"; private const string CategorySection = "category"; private const string FeatureDescriptionSection = "featuredescription"; private const string FeatureNameSection = "featurename"; private const string PrioritySection = "priority"; private const string FeaturesSection = "features"; private const string SessionStateSection = "sessionstate"; private readonly ICacheManager _cacheManager; private readonly IWebSiteFolder _webSiteFolder; private readonly ICriticalErrorProvider _criticalErrorProvider; public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider) { _cacheManager = cacheManager; _webSiteFolder = webSiteFolder; _criticalErrorProvider = criticalErrorProvider; Logger = NullLogger.Instance; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public bool DisableMonitoring { get; set; } public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) { return paths .SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional)) .ToList(); } private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) { string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType); return _cacheManager.Get(key, true, ctx => { if (!DisableMonitoring) { Logger.Debug("Monitoring virtual path \"{0}\"", path); ctx.Monitor(_webSiteFolder.WhenPathChanges(path)); } return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection(); }); } private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) { Logger.Information("Start looking for extensions in '{0}'...", path); var subfolderPaths = _webSiteFolder.ListDirectories(path); var localList = new List<ExtensionDescriptor>(); foreach (var subfolderPath in subfolderPaths) { var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\')); var manifestPath = Path.Combine(subfolderPath, manifestName); try { var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional); if (descriptor == null) continue; if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) { Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path); _criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path)); continue; } if (descriptor.Path == null) { descriptor.Path = descriptor.Name.IsValidUrlSegment() ? descriptor.Name : descriptor.Id; } localList.Add(descriptor); } catch (Exception ex) { // Ignore invalid module manifests if (ex.IsFatal()) { throw; } Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId); _criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' manifest could not be loaded. It was ignored.", extensionId)); } } Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id))); return localList; } public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) { Dictionary<string, string> manifest = ParseManifest(manifestText); var extensionDescriptor = new ExtensionDescriptor { Location = locationPath, Id = extensionId, ExtensionType = extensionType, Name = GetValue(manifest, NameSection) ?? extensionId, Path = GetValue(manifest, PathSection), Description = GetValue(manifest, DescriptionSection), Version = GetValue(manifest, VersionSection), OrchardVersion = GetValue(manifest, OrchardVersionSection), Author = GetValue(manifest, AuthorSection), WebSite = GetValue(manifest, WebsiteSection), Tags = GetValue(manifest, TagsSection), AntiForgery = GetValue(manifest, AntiForgerySection), Zones = GetValue(manifest, ZonesSection), BaseTheme = GetValue(manifest, BaseThemeSection), SessionState = GetValue(manifest, SessionStateSection) }; extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor); return extensionDescriptor; } private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) { return _cacheManager.Get(manifestPath, true, context => { if (!DisableMonitoring) { Logger.Debug("Monitoring virtual path \"{0}\"", manifestPath); context.Monitor(_webSiteFolder.WhenPathChanges(manifestPath)); } var manifestText = _webSiteFolder.ReadFile(manifestPath); if (manifestText == null) { if (manifestIsOptional) { manifestText = string.Format("Id: {0}", extensionId); } else { return null; } } return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText); }); } private static Dictionary<string, string> ParseManifest(string manifestText) { var manifest = new Dictionary<string, string>(); using (StringReader reader = new StringReader(manifestText)) { string line; while ((line = reader.ReadLine()) != null) { string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int fieldLength = field.Length; if (fieldLength != 2) continue; for (int i = 0; i < fieldLength; i++) { field[i] = field[i].Trim(); } switch (field[0].ToLowerInvariant()) { case NameSection: manifest.Add(NameSection, field[1]); break; case PathSection: manifest.Add(PathSection, field[1]); break; case DescriptionSection: manifest.Add(DescriptionSection, field[1]); break; case VersionSection: manifest.Add(VersionSection, field[1]); break; case OrchardVersionSection: manifest.Add(OrchardVersionSection, field[1]); break; case AuthorSection: manifest.Add(AuthorSection, field[1]); break; case WebsiteSection: manifest.Add(WebsiteSection, field[1]); break; case TagsSection: manifest.Add(TagsSection, field[1]); break; case AntiForgerySection: manifest.Add(AntiForgerySection, field[1]); break; case ZonesSection: manifest.Add(ZonesSection, field[1]); break; case BaseThemeSection: manifest.Add(BaseThemeSection, field[1]); break; case DependenciesSection: manifest.Add(DependenciesSection, field[1]); break; case CategorySection: manifest.Add(CategorySection, field[1]); break; case FeatureDescriptionSection: manifest.Add(FeatureDescriptionSection, field[1]); break; case FeatureNameSection: manifest.Add(FeatureNameSection, field[1]); break; case PrioritySection: manifest.Add(PrioritySection, field[1]); break; case SessionStateSection: manifest.Add(SessionStateSection, field[1]); break; case FeaturesSection: manifest.Add(FeaturesSection, reader.ReadToEnd()); break; } } } return manifest; } private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) { var featureDescriptors = new List<FeatureDescriptor>(); // Default feature FeatureDescriptor defaultFeature = new FeatureDescriptor { Id = extensionDescriptor.Id, Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name, Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0, Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty, Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)), Extension = extensionDescriptor, Category = GetValue(manifest, CategorySection) }; featureDescriptors.Add(defaultFeature); // Remaining features string featuresText = GetValue(manifest, FeaturesSection); if (featuresText != null) { FeatureDescriptor featureDescriptor = null; using (StringReader reader = new StringReader(featuresText)) { string line; while ((line = reader.ReadLine()) != null) { if (IsFeatureDeclaration(line)) { if (featureDescriptor != null) { if (!featureDescriptor.Equals(defaultFeature)) { featureDescriptors.Add(featureDescriptor); } featureDescriptor = null; } string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); string featureDescriptorId = featureDeclaration[0].Trim(); if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) { featureDescriptor = defaultFeature; featureDescriptor.Name = extensionDescriptor.Name; } else { featureDescriptor = new FeatureDescriptor { Id = featureDescriptorId, Extension = extensionDescriptor }; } } else if (IsFeatureFieldDeclaration(line)) { if (featureDescriptor != null) { string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int featureFieldLength = featureField.Length; if (featureFieldLength != 2) continue; for (int i = 0; i < featureFieldLength; i++) { featureField[i] = featureField[i].Trim(); } switch (featureField[0].ToLowerInvariant()) { case NameSection: featureDescriptor.Name = featureField[1]; break; case DescriptionSection: featureDescriptor.Description = featureField[1]; break; case CategorySection: featureDescriptor.Category = featureField[1]; break; case PrioritySection: featureDescriptor.Priority = int.Parse(featureField[1]); break; case DependenciesSection: featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]); break; } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature)) featureDescriptors.Add(featureDescriptor); } } return featureDescriptors; } private static bool IsFeatureFieldDeclaration(string line) { if (line.StartsWith("\t\t") || line.StartsWith("\t ") || line.StartsWith(" ") || line.StartsWith(" \t")) return true; return false; } private static bool IsFeatureDeclaration(string line) { int lineLength = line.Length; if (line.StartsWith("\t") && lineLength >= 2) { return !Char.IsWhiteSpace(line[1]); } if (line.StartsWith(" ") && lineLength >= 5) return !Char.IsWhiteSpace(line[4]); return false; } private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) { if (string.IsNullOrEmpty(dependenciesEntry)) return Enumerable.Empty<string>(); var dependencies = new List<string>(); foreach (var s in dependenciesEntry.Split(',')) { dependencies.Add(s.Trim()); } return dependencies; } private static string GetValue(IDictionary<string, string> fields, string key) { string value; return fields.TryGetValue(key, out value) ? value : null; } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 Outercurve Foundation 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. // Material sourced from the bluePortal project (http://blueportal.codeplex.com). // Licensed under the Microsoft Public License (available at http://www.opensource.org/licenses/ms-pl.html). using System; using System.Data; using System.Collections; using System.Configuration; 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; namespace CSSFriendly { public class PasswordRecoveryAdapter : System.Web.UI.WebControls.Adapters.WebControlAdapter { private enum State { UserName, VerifyingUser, UserLookupError, Question, VerifyingAnswer, AnswerLookupError, SendMailError, Success } State _state = State.UserName; string _currentErrorText = ""; private WebControlAdapterExtender _extender = null; private WebControlAdapterExtender Extender { get { if (((_extender == null) && (Control != null)) || ((_extender != null) && (Control != _extender.AdaptedControl))) { _extender = new WebControlAdapterExtender(Control); } System.Diagnostics.Debug.Assert(_extender != null, "CSS Friendly adapters internal error", "Null extender instance"); return _extender; } } private MembershipProvider PasswordRecoveryMembershipProvider { get { MembershipProvider provider = Membership.Provider; PasswordRecovery passwordRecovery = Control as PasswordRecovery; if ((passwordRecovery != null) && (passwordRecovery.MembershipProvider != null) && (!String.IsNullOrEmpty(passwordRecovery.MembershipProvider)) && (Membership.Providers[passwordRecovery.MembershipProvider] != null)) { provider = Membership.Providers[passwordRecovery.MembershipProvider]; } return provider; } } public PasswordRecoveryAdapter() { _state = State.UserName; _currentErrorText = ""; } /// /////////////////////////////////////////////////////////////////////////////// /// PROTECTED protected override void OnInit(EventArgs e) { base.OnInit(e); PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (Extender.AdapterEnabled && (passwordRecovery != null)) { RegisterScripts(); passwordRecovery.AnswerLookupError += OnAnswerLookupError; passwordRecovery.SendMailError += OnSendMailError; passwordRecovery.UserLookupError += OnUserLookupError; passwordRecovery.VerifyingAnswer += OnVerifyingAnswer; passwordRecovery.VerifyingUser += OnVerifyingUser; _state = State.UserName; _currentErrorText = ""; } } protected override void CreateChildControls() { base.CreateChildControls(); PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (passwordRecovery != null) { if ((passwordRecovery.UserNameTemplate != null) && (passwordRecovery.UserNameTemplateContainer != null)) { passwordRecovery.UserNameTemplateContainer.Controls.Clear(); passwordRecovery.UserNameTemplate.InstantiateIn(passwordRecovery.UserNameTemplateContainer); passwordRecovery.UserNameTemplateContainer.DataBind(); } if ((passwordRecovery.QuestionTemplate != null) && (passwordRecovery.QuestionTemplateContainer != null)) { passwordRecovery.QuestionTemplateContainer.Controls.Clear(); passwordRecovery.QuestionTemplate.InstantiateIn(passwordRecovery.QuestionTemplateContainer); passwordRecovery.QuestionTemplateContainer.DataBind(); } if ((passwordRecovery.SuccessTemplate != null) && (passwordRecovery.SuccessTemplateContainer != null)) { passwordRecovery.SuccessTemplateContainer.Controls.Clear(); passwordRecovery.SuccessTemplate.InstantiateIn(passwordRecovery.SuccessTemplateContainer); passwordRecovery.SuccessTemplateContainer.DataBind(); } } } protected void OnAnswerLookupError(object sender, EventArgs e) { _state = State.AnswerLookupError; PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (passwordRecovery != null) { _currentErrorText = passwordRecovery.GeneralFailureText; if (!String.IsNullOrEmpty(passwordRecovery.QuestionFailureText)) { _currentErrorText = passwordRecovery.QuestionFailureText; } } } protected void OnSendMailError(object sender, SendMailErrorEventArgs e) { if (!e.Handled) { _state = State.SendMailError; _currentErrorText = e.Exception.Message; } } protected void OnUserLookupError(object sender, EventArgs e) { _state = State.UserLookupError; PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (passwordRecovery != null) { _currentErrorText = passwordRecovery.GeneralFailureText; if (!String.IsNullOrEmpty(passwordRecovery.UserNameFailureText)) { _currentErrorText = passwordRecovery.UserNameFailureText; } } } protected void OnVerifyingAnswer(object sender, LoginCancelEventArgs e) { _state = State.VerifyingAnswer; } protected void OnVerifyingUser(object sender, LoginCancelEventArgs e) { _state = State.VerifyingUser; } protected override void RenderBeginTag(HtmlTextWriter writer) { if (Extender.AdapterEnabled) { Extender.RenderBeginTag(writer, "AspNet-PasswordRecovery"); } else { base.RenderBeginTag(writer); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (passwordRecovery != null) { string provider = passwordRecovery.MembershipProvider; } // By this time we have finished doing our event processing. That means that if errors have // occurred, the event handlers (OnAnswerLookupError, OnSendMailError or // OnUserLookupError) will have been called. So, if we were, for example, verifying the // user and didn't cause an error then we know we can move on to the next step, getting // the answer to the security question... if the membership system demands it. switch (_state) { case State.AnswerLookupError: // Leave the state alone because we hit an error. break; case State.Question: // Leave the state alone. Render a form to get the answer to the security question. _currentErrorText = ""; break; case State.SendMailError: // Leave the state alone because we hit an error. break; case State.Success: // Leave the state alone. Render a concluding message. _currentErrorText = ""; break; case State.UserLookupError: // Leave the state alone because we hit an error. break; case State.UserName: // Leave the state alone. Render a form to get the user name. _currentErrorText = ""; break; case State.VerifyingAnswer: // Success! We did not encounter an error while verifying the answer to the security question. _state = State.Success; _currentErrorText = ""; break; case State.VerifyingUser: // We have a valid user. We did not encounter an error while verifying the user. if (PasswordRecoveryMembershipProvider.RequiresQuestionAndAnswer) { _state = State.Question; } else { _state = State.Success; } _currentErrorText = ""; break; } } protected override void RenderEndTag(HtmlTextWriter writer) { if (Extender.AdapterEnabled) { Extender.RenderEndTag(writer); } else { base.RenderEndTag(writer); } } protected override void RenderContents(HtmlTextWriter writer) { if (Extender.AdapterEnabled) { PasswordRecovery passwordRecovery = Control as PasswordRecovery; if (passwordRecovery != null) { if ((_state == State.UserName) || (_state == State.UserLookupError)) { if ((passwordRecovery.UserNameTemplate != null) && (passwordRecovery.UserNameTemplateContainer != null)) { foreach (Control c in passwordRecovery.UserNameTemplateContainer.Controls) { c.RenderControl(writer); } } else { WriteTitlePanel(writer, passwordRecovery); WriteInstructionPanel(writer, passwordRecovery); WriteHelpPanel(writer, passwordRecovery); WriteUserPanel(writer, passwordRecovery); if (_state == State.UserLookupError) { WriteFailurePanel(writer, passwordRecovery); } WriteSubmitPanel(writer, passwordRecovery); } } else if ((_state == State.Question) || (_state == State.AnswerLookupError)) { if ((passwordRecovery.QuestionTemplate != null) && (passwordRecovery.QuestionTemplateContainer != null)) { foreach (Control c in passwordRecovery.QuestionTemplateContainer.Controls) { c.RenderControl(writer); } } else { WriteTitlePanel(writer, passwordRecovery); WriteInstructionPanel(writer, passwordRecovery); WriteHelpPanel(writer, passwordRecovery); WriteUserPanel(writer, passwordRecovery); WriteQuestionPanel(writer, passwordRecovery); WriteAnswerPanel(writer, passwordRecovery); if (_state == State.AnswerLookupError) { WriteFailurePanel(writer, passwordRecovery); } WriteSubmitPanel(writer, passwordRecovery); } } else if (_state == State.SendMailError) { WriteFailurePanel(writer, passwordRecovery); } else if (_state == State.Success) { if ((passwordRecovery.SuccessTemplate != null) && (passwordRecovery.SuccessTemplateContainer != null)) { foreach (Control c in passwordRecovery.SuccessTemplateContainer.Controls) { c.RenderControl(writer); } } else { WriteSuccessTextPanel(writer, passwordRecovery); } } else { // We should never get here. System.Diagnostics.Debug.Fail("The PasswordRecovery control adapter was asked to render a state that it does not expect."); } } } else { base.RenderContents(writer); } } /// /////////////////////////////////////////////////////////////////////////////// /// PRIVATE private void RegisterScripts() { } ///////////////////////////////////////////////////////// // Step 1: user name ///////////////////////////////////////////////////////// private void WriteTitlePanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if ((_state == State.UserName) || (_state == State.UserLookupError)) { if (!String.IsNullOrEmpty(passwordRecovery.UserNameTitleText)) { string className = (passwordRecovery.TitleTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.TitleTextStyle.CssClass)) ? passwordRecovery.TitleTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-UserName-TitlePanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", passwordRecovery.UserNameTitleText); WebControlAdapterExtender.WriteEndDiv(writer); } } else if ((_state == State.Question) || (_state == State.AnswerLookupError)) { if (!String.IsNullOrEmpty(passwordRecovery.QuestionTitleText)) { string className = (passwordRecovery.TitleTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.TitleTextStyle.CssClass)) ? passwordRecovery.TitleTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-Question-TitlePanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", passwordRecovery.QuestionTitleText); WebControlAdapterExtender.WriteEndDiv(writer); } } } private void WriteInstructionPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if ((_state == State.UserName) || (_state == State.UserLookupError)) { if (!String.IsNullOrEmpty(passwordRecovery.UserNameInstructionText)) { string className = (passwordRecovery.InstructionTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.InstructionTextStyle.CssClass)) ? passwordRecovery.InstructionTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-UserName-InstructionPanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", passwordRecovery.UserNameInstructionText); WebControlAdapterExtender.WriteEndDiv(writer); } } else if ((_state == State.Question) || (_state == State.AnswerLookupError)) { if (!String.IsNullOrEmpty(passwordRecovery.QuestionInstructionText)) { string className = (passwordRecovery.InstructionTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.InstructionTextStyle.CssClass)) ? passwordRecovery.InstructionTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-Question-InstructionPanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", passwordRecovery.QuestionInstructionText); WebControlAdapterExtender.WriteEndDiv(writer); } } } private void WriteFailurePanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if (!String.IsNullOrEmpty(_currentErrorText)) { string className = (passwordRecovery.FailureTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.FailureTextStyle.CssClass)) ? passwordRecovery.FailureTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-FailurePanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", _currentErrorText); WebControlAdapterExtender.WriteEndDiv(writer); } } private void WriteHelpPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if ((!String.IsNullOrEmpty(passwordRecovery.HelpPageIconUrl)) || (!String.IsNullOrEmpty(passwordRecovery.HelpPageText))) { WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-HelpPanel"); WebControlAdapterExtender.WriteImage(writer, passwordRecovery.HelpPageIconUrl, "Help"); WebControlAdapterExtender.WriteLink(writer, passwordRecovery.HyperLinkStyle.CssClass, passwordRecovery.HelpPageUrl, "Help", passwordRecovery.HelpPageText); WebControlAdapterExtender.WriteEndDiv(writer); } } private void WriteUserPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if ((_state == State.UserName) || (_state == State.UserLookupError)) { Control container = passwordRecovery.UserNameTemplateContainer; TextBox textBox = (container != null) ? container.FindControl("UserName") as TextBox : null; RequiredFieldValidator rfv = (textBox != null) ? container.FindControl("UserNameRequired") as RequiredFieldValidator : null; string id = (rfv != null) ? container.ID + "_" + textBox.ID : ""; if (!String.IsNullOrEmpty(id)) { Page.ClientScript.RegisterForEventValidation(textBox.UniqueID); WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-UserName-UserPanel"); Extender.WriteTextBox(writer, false, passwordRecovery.LabelStyle.CssClass, passwordRecovery.UserNameLabelText, passwordRecovery.TextBoxStyle.CssClass, id, passwordRecovery.UserName); WebControlAdapterExtender.WriteRequiredFieldValidator(writer, rfv, passwordRecovery.ValidatorTextStyle.CssClass, "UserName", passwordRecovery.UserNameRequiredErrorMessage); WebControlAdapterExtender.WriteEndDiv(writer); } } else if ((_state == State.Question) || (_state == State.AnswerLookupError)) { WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-Question-UserPanel"); Extender.WriteReadOnlyTextBox(writer, passwordRecovery.LabelStyle.CssClass, passwordRecovery.UserNameLabelText, passwordRecovery.TextBoxStyle.CssClass, passwordRecovery.UserName); WebControlAdapterExtender.WriteEndDiv(writer); } } private void WriteSubmitPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if ((_state == State.UserName) || (_state == State.UserLookupError)) { Control container = passwordRecovery.UserNameTemplateContainer; string id = (container != null) ? container.ID + "_Submit" : "Submit"; string idWithType = WebControlAdapterExtender.MakeIdWithButtonType("Submit", passwordRecovery.SubmitButtonType); Control btn = (container != null) ? container.FindControl(idWithType) as Control : null; if (btn != null) { Page.ClientScript.RegisterForEventValidation(btn.UniqueID); PostBackOptions options = new PostBackOptions(btn, "", "", false, false, false, false, true, passwordRecovery.UniqueID); string javascript = "javascript:" + Page.ClientScript.GetPostBackEventReference(options); javascript = Page.Server.HtmlEncode(javascript); WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-UserName-SubmitPanel"); Extender.WriteSubmit(writer, passwordRecovery.SubmitButtonType, passwordRecovery.SubmitButtonStyle.CssClass, id, passwordRecovery.SubmitButtonImageUrl, javascript, passwordRecovery.SubmitButtonText); WebControlAdapterExtender.WriteEndDiv(writer); } } else if ((_state == State.Question) || (_state == State.AnswerLookupError)) { Control container = passwordRecovery.QuestionTemplateContainer; string id = (container != null) ? container.ID + "_Submit" : "Submit"; string idWithType = WebControlAdapterExtender.MakeIdWithButtonType("Submit", passwordRecovery.SubmitButtonType); Control btn = (container != null) ? container.FindControl(idWithType) as Control : null; if (btn != null) { Page.ClientScript.RegisterForEventValidation(btn.UniqueID); PostBackOptions options = new PostBackOptions(btn, "", "", false, false, false, false, true, passwordRecovery.UniqueID); string javascript = "javascript:" + Page.ClientScript.GetPostBackEventReference(options); javascript = Page.Server.HtmlEncode(javascript); WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-Question-SubmitPanel"); Extender.WriteSubmit(writer, passwordRecovery.SubmitButtonType, passwordRecovery.SubmitButtonStyle.CssClass, id, passwordRecovery.SubmitButtonImageUrl, javascript, passwordRecovery.SubmitButtonText); WebControlAdapterExtender.WriteEndDiv(writer); } } } ///////////////////////////////////////////////////////// // Step 2: question ///////////////////////////////////////////////////////// private void WriteQuestionPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-QuestionPanel"); Extender.WriteReadOnlyTextBox(writer, passwordRecovery.LabelStyle.CssClass, passwordRecovery.QuestionLabelText, passwordRecovery.TextBoxStyle.CssClass, passwordRecovery.Question); WebControlAdapterExtender.WriteEndDiv(writer); } private void WriteAnswerPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { Control container = passwordRecovery.QuestionTemplateContainer; TextBox textBox = (container != null) ? container.FindControl("Answer") as TextBox : null; RequiredFieldValidator rfv = (textBox != null) ? container.FindControl("AnswerRequired") as RequiredFieldValidator : null; string id = (rfv != null) ? container.ID + "_" + textBox.ID : ""; if (!String.IsNullOrEmpty(id)) { Page.ClientScript.RegisterForEventValidation(textBox.UniqueID); WebControlAdapterExtender.WriteBeginDiv(writer, "AspNet-PasswordRecovery-AnswerPanel"); Extender.WriteTextBox(writer, false, passwordRecovery.LabelStyle.CssClass, passwordRecovery.AnswerLabelText, passwordRecovery.TextBoxStyle.CssClass, id, ""); WebControlAdapterExtender.WriteRequiredFieldValidator(writer, rfv, passwordRecovery.ValidatorTextStyle.CssClass, "Answer", passwordRecovery.AnswerRequiredErrorMessage); WebControlAdapterExtender.WriteEndDiv(writer); } } ///////////////////////////////////////////////////////// // Step 3: success ///////////////////////////////////////////////////////// private void WriteSuccessTextPanel(HtmlTextWriter writer, PasswordRecovery passwordRecovery) { if (!String.IsNullOrEmpty(passwordRecovery.SuccessText)) { string className = (passwordRecovery.SuccessTextStyle != null) && (!String.IsNullOrEmpty(passwordRecovery.SuccessTextStyle.CssClass)) ? passwordRecovery.SuccessTextStyle.CssClass + " " : ""; className += "AspNet-PasswordRecovery-SuccessTextPanel"; WebControlAdapterExtender.WriteBeginDiv(writer, className); WebControlAdapterExtender.WriteSpan(writer, "", passwordRecovery.SuccessText); WebControlAdapterExtender.WriteEndDiv(writer); } } } }
// 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 CompareGreaterThanOrEqualDouble() { var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble testClass) { var result = Sse2.CompareGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareGreaterThanOrEqual( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareGreaterThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareGreaterThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareGreaterThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareGreaterThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble(); var result = Sse2.CompareGreaterThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.CompareGreaterThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.CompareGreaterThanOrEqual( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] >= right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] >= right[i]) ? -1 : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using FileHelpers.Events; namespace FileHelpers { /// <summary> /// Async engine, reads records from file in background, /// returns them record by record in foreground /// </summary> public sealed class FileHelperAsyncEngine : FileHelperAsyncEngine<object> { #region " Constructor " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> public FileHelperAsyncEngine(Type recordType) : base(recordType) {} /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> /// <param name="encoding">The encoding used by the Engine.</param> public FileHelperAsyncEngine(Type recordType, Encoding encoding) : base(recordType, encoding) {} #endregion } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngine/*'/> /// <include file='Examples.xml' path='doc/examples/FileHelperAsyncEngine/*'/> /// <typeparam name="T">The record type.</typeparam> [DebuggerDisplay( "FileHelperAsyncEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}" )] public class FileHelperAsyncEngine<T> : EventEngineBase<T>, IFileHelperAsyncEngine<T> where T : class { #region " Constructor " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> public FileHelperAsyncEngine() : base(typeof (T)) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> protected FileHelperAsyncEngine(Type recordType) : base(recordType) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> /// <param name="encoding">The encoding used by the Engine.</param> public FileHelperAsyncEngine(Encoding encoding) : base(typeof (T), encoding) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> /// <param name="encoding">The encoding used by the Engine.</param> /// <param name="recordType">Type of record to read</param> protected FileHelperAsyncEngine(Type recordType, Encoding encoding) : base(recordType, encoding) { } #endregion #region " Readers and Writters " [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ForwardReader mAsyncReader; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private TextWriter mAsyncWriter; #endregion #region " LastRecord " [DebuggerBrowsable(DebuggerBrowsableState.Never)] private T mLastRecord; /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/LastRecord/*'/> public T LastRecord { get { return mLastRecord; } } private object[] mLastRecordValues; /// <summary> /// An array with the values of each field of the current record /// </summary> public object[] LastRecordValues { get { return mLastRecordValues; } } /// <summary> /// Get a field value of the current records. /// </summary> /// <param name="fieldIndex" >The index of the field.</param> public object this[int fieldIndex] { get { if (mLastRecordValues == null) { throw new BadUsageException( "You must be reading something to access this property. Try calling BeginReadFile first."); } return mLastRecordValues[fieldIndex]; } set { if (mAsyncWriter == null) { throw new BadUsageException( "You must be writing something to set a record value. Try calling BeginWriteFile first."); } if (mLastRecordValues == null) mLastRecordValues = new object[RecordInfo.FieldCount]; if (value == null) { if (RecordInfo.Fields[fieldIndex].FieldType.IsValueType) throw new BadUsageException("You can't assign null to a value type."); mLastRecordValues[fieldIndex] = null; } else { if (!RecordInfo.Fields[fieldIndex].FieldType.IsInstanceOfType(value)) { throw new BadUsageException(string.Format("Invalid type: {0}. Expected: {1}", value.GetType().Name, RecordInfo.Fields[fieldIndex].FieldType.Name)); } mLastRecordValues[fieldIndex] = value; } } } /// <summary> /// Get a field value of the current records. /// </summary> /// <param name="fieldName" >The name of the field (case sensitive)</param> public object this[string fieldName] { get { if (mLastRecordValues == null) { throw new BadUsageException( "You must be reading something to access this property. Try calling BeginReadFile first."); } int index = RecordInfo.GetFieldIndex(fieldName); return mLastRecordValues[index]; } set { int index = RecordInfo.GetFieldIndex(fieldName); this[index] = value; } } #endregion #region " BeginReadStream" /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadStream/*'/> public IDisposable BeginReadStream(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader", "The TextReader can't be null."); if (mAsyncWriter != null) throw new BadUsageException("You can't start to read while you are writing."); var recordReader = new NewLineDelimitedRecordReader(reader); ResetFields(); mHeaderText = String.Empty; mFooterText = String.Empty; if (RecordInfo.IgnoreFirst > 0) { for (int i = 0; i < RecordInfo.IgnoreFirst; i++) { string temp = recordReader.ReadRecordString(); mLineNumber++; if (temp != null) mHeaderText += temp + StringHelper.NewLine; else break; } } mAsyncReader = new ForwardReader(recordReader, RecordInfo.IgnoreLast, mLineNumber) { DiscardForward = true }; State = EngineState.Reading; mStreamInfo = new StreamInfoProvider(reader); mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); return this; } #endregion #region " BeginReadFile " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/> public IDisposable BeginReadFile(string fileName) { BeginReadFile(fileName, DefaultReadBufferSize); return this; } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/> /// <param name="bufferSize">Buffer size to read</param> public IDisposable BeginReadFile(string fileName, int bufferSize) { BeginReadStream(new InternalStreamReader(fileName, mEncoding, true, bufferSize)); return this; } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadString/*'/> public IDisposable BeginReadString(string sourceData) { if (sourceData == null) sourceData = String.Empty; BeginReadStream(new InternalStringReader(sourceData)); return this; } #endregion #region " ReadNext " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNext/*'/> public T ReadNext() { if (mAsyncReader == null) throw new BadUsageException("Before call ReadNext you must call BeginReadFile or BeginReadStream."); ReadNextRecord(); return mLastRecord; } private int mCurrentRecord = 0; private void ReadNextRecord() { string currentLine = mAsyncReader.ReadNextLine(); mLineNumber++; bool byPass = false; mLastRecord = default(T); var line = new LineInfo(string.Empty) { mReader = mAsyncReader }; if (mLastRecordValues == null) mLastRecordValues = new object[RecordInfo.FieldCount]; while (true) { if (currentLine != null) { try { mTotalRecords++; mCurrentRecord++; line.ReLoad(currentLine); bool skip = false; mLastRecord = (T) RecordInfo.Operations.CreateRecordHandler(); if (MustNotifyProgress) // Avoid object creation { OnProgress(new ProgressEventArgs(mCurrentRecord, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); } BeforeReadEventArgs<T> e = null; if (MustNotifyRead) // Avoid object creation { e = new BeforeReadEventArgs<T>(this, mLastRecord, currentLine, LineNumber); skip = OnBeforeReadRecord(e); if (e.RecordLineChanged) line.ReLoad(e.RecordLine); } if (skip == false) { if (RecordInfo.Operations.StringToRecord(mLastRecord, line, mLastRecordValues)) { if (MustNotifyRead) // Avoid object creation skip = OnAfterReadRecord(currentLine, mLastRecord, e.RecordLineChanged, LineNumber); if (skip == false) { byPass = true; return; } } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: byPass = true; throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mAsyncReader.LineNumber, mExceptionInfo = ex, mRecordString = currentLine }; // err.mColumnNumber = mColumnNum; mErrorManager.AddError(err); break; } } finally { if (byPass == false) { currentLine = mAsyncReader.ReadNextLine(); mLineNumber = mAsyncReader.LineNumber; } } } else { mLastRecordValues = null; mLastRecord = default(T); if (RecordInfo.IgnoreLast > 0) mFooterText = mAsyncReader.RemainingText; try { mAsyncReader.Close(); //mAsyncReader = null; } catch {} return; } } } /// <summary> /// Return array of object for all data to end of the file /// </summary> /// <returns>Array of objects created from data on file</returns> public T[] ReadToEnd() { return ReadNexts(int.MaxValue); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNexts/*'/> public T[] ReadNexts(int numberOfRecords) { if (mAsyncReader == null) throw new BadUsageException("Before call ReadNext you must call BeginReadFile or BeginReadStream."); var arr = new List<T>(numberOfRecords); for (int i = 0; i < numberOfRecords; i++) { ReadNextRecord(); if (mLastRecord != null) arr.Add(mLastRecord); else break; } return arr.ToArray(); } #endregion #region " Close " /// <summary> /// Save all the buffered data for write to the disk. /// Useful to opened async engines that wants to save pending values to /// disk or for engines used for logging. /// </summary> public void Flush() { if (mAsyncWriter != null) mAsyncWriter.Flush(); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/Close/*'/> public void Close() { lock (this) { State = EngineState.Closed; try { mLastRecordValues = null; mLastRecord = default(T); var reader = mAsyncReader; if (reader != null) { reader.Close(); mAsyncReader = null; } } catch {} try { var writer = mAsyncWriter; if (writer != null) { if (!string.IsNullOrEmpty(mFooterText)) { if (mFooterText.EndsWith(StringHelper.NewLine)) writer.Write(mFooterText); else writer.WriteLine(mFooterText); } writer.Close(); mAsyncWriter = null; } } catch {} } } #endregion #region " BeginWriteStream" /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteStream/*'/> public IDisposable BeginWriteStream(TextWriter writer) { if (writer == null) throw new ArgumentException("writer", "The TextWriter can't be null."); if (mAsyncReader != null) throw new BadUsageException("You can't start to write while you are reading."); State = EngineState.Writing; ResetFields(); mAsyncWriter = writer; WriteHeader(); mStreamInfo = new StreamInfoProvider(mAsyncWriter); mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); return this; } private void WriteHeader() { if (!string.IsNullOrEmpty(mHeaderText)) { if (mHeaderText.EndsWith(StringHelper.NewLine)) mAsyncWriter.Write(mHeaderText); else mAsyncWriter.WriteLine(mHeaderText); } } #endregion #region " BeginWriteFile " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/> public IDisposable BeginWriteFile(string fileName) { return BeginWriteFile(fileName, DefaultWriteBufferSize); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/> /// <param name="bufferSize">Size of the write buffer</param> public IDisposable BeginWriteFile(string fileName, int bufferSize) { BeginWriteStream(new StreamWriter(fileName, false, mEncoding, bufferSize)); return this; } #endregion #region " BeginAppendToFile " /// <summary> /// Begin the append to an existing file /// </summary> /// <param name="fileName">Filename to append to</param> /// <returns>Object to append TODO: ???</returns> public IDisposable BeginAppendToFile(string fileName) { return BeginAppendToFile(fileName, DefaultWriteBufferSize); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginAppendToFile/*'/> /// <param name="bufferSize">Size of the buffer for writing</param> public IDisposable BeginAppendToFile(string fileName, int bufferSize) { if (mAsyncReader != null) throw new BadUsageException("You can't start to write while you are reading."); mAsyncWriter = StreamHelper.CreateFileAppender(fileName, mEncoding, false, true, bufferSize); mHeaderText = String.Empty; mFooterText = String.Empty; State = EngineState.Writing; mStreamInfo = new StreamInfoProvider(mAsyncWriter); mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); return this; } #endregion #region " WriteNext " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNext/*'/> public void WriteNext(T record) { if (mAsyncWriter == null) throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream."); if (record == null) throw new BadUsageException("The record to write can't be null."); if (RecordType.IsAssignableFrom(record.GetType()) == false) throw new BadUsageException("The record must be of type: " + RecordType.Name); WriteRecord(record); } private void WriteRecord(T record) { string currentLine = null; try { mLineNumber++; mTotalRecords++; mCurrentRecord++; bool skip = false; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(mCurrentRecord, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); if (MustNotifyWrite) skip = OnBeforeWriteRecord(record, LineNumber); if (skip == false) { currentLine = RecordInfo.Operations.RecordToString(record); if (MustNotifyWrite) currentLine = OnAfterWriteRecord(currentLine, record); mAsyncWriter.WriteLine(currentLine); } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mLineNumber, mExceptionInfo = ex, mRecordString = currentLine }; // err.mColumnNumber = mColumnNum; mErrorManager.AddError(err); break; } } } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNexts/*'/> public void WriteNexts(IEnumerable<T> records) { if (mAsyncWriter == null) throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream."); if (records == null) throw new ArgumentNullException("records", "The record to write can't be null."); bool first = true; foreach (var rec in records) { if (first) { if (RecordType.IsAssignableFrom(rec.GetType()) == false) throw new BadUsageException("The record must be of type: " + RecordType.Name); first = false; } WriteRecord(rec); } } #endregion #region " WriteNext for LastRecordValues " /// <summary> /// Write the current record values in the buffer. You can use /// engine[0] or engine["YourField"] to set the values. /// </summary> public void WriteNextValues() { if (mAsyncWriter == null) throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream."); if (mLastRecordValues == null) { throw new BadUsageException( "You must set some values of the record before call this method, or use the overload that has a record as argument."); } string currentLine = null; try { mLineNumber++; mTotalRecords++; currentLine = RecordInfo.Operations.RecordValuesToString(this.mLastRecordValues); mAsyncWriter.WriteLine(currentLine); } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mLineNumber, mExceptionInfo = ex, mRecordString = currentLine }; // err.mColumnNumber = mColumnNum; mErrorManager.AddError(err); break; } } finally { mLastRecordValues = null; } } #endregion #region " IEnumerable implementation " /// <summary>Allows to loop record by record in the engine</summary> /// <returns>The enumerator</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (mAsyncReader == null) throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop."); return new AsyncEnumerator(this); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection. ///</returns> ///<filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { if (mAsyncReader == null) throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop."); return new AsyncEnumerator(this); } private class AsyncEnumerator : IEnumerator<T> { T IEnumerator<T>.Current { get { return mEngine.mLastRecord; } } void IDisposable.Dispose() { mEngine.Close(); } private readonly FileHelperAsyncEngine<T> mEngine; public AsyncEnumerator(FileHelperAsyncEngine<T> engine) { mEngine = engine; } public bool MoveNext() { object res = mEngine.ReadNext(); if (res == null) { mEngine.Close(); return false; } return true; } public object Current { get { return mEngine.mLastRecord; } } public void Reset() { // No needed } } #endregion #region " IDisposable implementation " /// <summary>Release Resources</summary> void IDisposable.Dispose() { Close(); GC.SuppressFinalize(this); } /// <summary>Destructor</summary> ~FileHelperAsyncEngine() { Close(); } #endregion #region " State " private StreamInfoProvider mStreamInfo; /// <summary> /// Indicates the current state of the engine. /// </summary> private EngineState State { get; set; } /// <summary> /// Indicates the State of an engine /// </summary> private enum EngineState { /// <summary>The Engine is closed</summary> Closed = 0, /// <summary>The Engine is reading a file, string or stream</summary> Reading, /// <summary>The Engine is writing a file, string or stream</summary> Writing } #endregion } }
using System; using System.Collections; using Server; using Server.Gumps; using Server.Network; namespace Knives.TownHouses { public delegate void GumpStateCallback(object obj); public delegate void GumpCallback(); public abstract class GumpPlusLight : Gump { public static void RefreshGump(Mobile m, Type type) { if (m.NetState == null) return; foreach (Gump g in m.NetState.Gumps) if (g is GumpPlusLight && g.GetType() == type) { m.CloseGump(type); ((GumpPlusLight)g).NewGump(); return; } } private Mobile c_Owner; private Hashtable c_Buttons, c_Fields; public Mobile Owner{ get{ return c_Owner; } } public GumpPlusLight( Mobile m, int x, int y ) : base( x, y ) { c_Owner = m; c_Buttons = new Hashtable(); c_Fields = new Hashtable(); Timer.DelayCall(TimeSpan.FromSeconds(0), new TimerCallback(NewGump)); } public void Clear() { Entries.Clear(); c_Buttons.Clear(); c_Fields.Clear(); } public virtual void NewGump() { NewGump( true ); } public void NewGump( bool clear ) { if ( clear ) Clear(); BuildGump(); c_Owner.SendGump( this ); } public void SameGump() { c_Owner.SendGump( this ); } protected abstract void BuildGump(); private int UniqueButton() { int random = 0; do { random = Utility.Random( 20000 ); }while( c_Buttons[random] != null ); return random; } private int UniqueTextId() { int random = 0; do { random = Utility.Random(20000); } while (c_Buttons[random] != null); return random; } public void AddBackgroundZero(int x, int y, int width, int height, int back) { AddBackgroundZero(x, y, width, height, back, true); } public void AddBackgroundZero(int x, int y, int width, int height, int back, bool over) { BackgroundPlus plus = new BackgroundPlus(x, y, width, height, back, over); Entries.Insert(0, plus); } public new void AddBackground(int x, int y, int width, int height, int back) { AddBackground(x, y, width, height, back, true); } public void AddBackground(int x, int y, int width, int height, int back, bool over) { BackgroundPlus plus = new BackgroundPlus(x, y, width, height, back, over); Add(plus); } public void AddButton(int x, int y, int id, GumpCallback callback) { AddButton(x, y, id, id, "None", callback); } public void AddButton(int x, int y, int id, GumpStateCallback callback, object arg) { AddButton(x, y, id, id, "None", callback, arg); } public void AddButton(int x, int y, int id, string name, GumpCallback callback) { AddButton(x, y, id, id, name, callback); } public void AddButton(int x, int y, int id, string name, GumpStateCallback callback, object arg) { AddButton(x, y, id, id, name, callback, arg); } public void AddButton(int x, int y, int up, int down, GumpCallback callback) { AddButton(x, y, up, down, "None", callback); } public void AddButton(int x, int y, int up, int down, string name, GumpCallback callback) { int id = UniqueButton(); ButtonPlus button = new ButtonPlus( x, y, up, down, id, name, callback ); Add( button ); c_Buttons[id] = button; } public void AddButton( int x, int y, int up, int down, GumpStateCallback callback, object arg ) { AddButton( x, y, up, down, "None", callback, arg ); } public void AddButton( int x, int y, int up, int down, string name, GumpStateCallback callback, object arg ) { int id = UniqueButton(); ButtonPlus button = new ButtonPlus( x, y, up, down, id, name, callback, arg ); Add( button ); c_Buttons[id] = button; } public void AddHtml(int x, int y, int width, string text) { AddHtml(x, y, width, 21, HTML.White + text, false, false, true); } public void AddHtml(int x, int y, int width, string text, bool over) { AddHtml(x, y, width, 21, HTML.White + text, false, false, over); } public new void AddHtml(int x, int y, int width, int height, string text, bool back, bool scroll) { AddHtml(x, y, width, height, HTML.White + text, back, scroll, true); } public void AddHtml(int x, int y, int width, int height, string text, bool back, bool scroll, bool over) { HtmlPlus html = new HtmlPlus(x, y, width, height, HTML.White + text, back, scroll, over); Add(html); } public void AddTextField(int x, int y, int width, int height, int color, int back, string name, string text) { int id = UniqueTextId(); AddImageTiled(x, y, width, height, back); base.AddTextEntry(x, y, width, height, color, id, text); c_Fields[id] = name; c_Fields[name] = text; } public string GetTextField( string name ) { if ( c_Fields[name] == null ) return ""; return c_Fields[name].ToString(); } public int GetTextFieldInt(string name) { return Utility.ToInt32(GetTextField(name)); } protected virtual void OnClose() { } public override void OnResponse( NetState state, RelayInfo info ) { string name = ""; try { if (info.ButtonID == -5) { NewGump(); return; } foreach (TextRelay t in info.TextEntries) c_Fields[c_Fields[t.EntryID].ToString()] = t.Text; if (info.ButtonID == 0) OnClose(); if (c_Buttons[info.ButtonID] == null || !(c_Buttons[info.ButtonID] is ButtonPlus)) return; name = ((ButtonPlus)c_Buttons[info.ButtonID]).Name; ((ButtonPlus)c_Buttons[info.ButtonID]).Invoke(); } catch (Exception e) { Errors.Report("An error occured during a gump response. More information can be found on the console."); if (name != "") Console.WriteLine("{0} gump name triggered an error.", name); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } } } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Worker.TestResults; using Moq; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.TestResults { public class TrxReaderTests : IDisposable { private string _trxResultFile; private Mock<IExecutionContext> _ec; [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithoutTestNamesAreSkipped() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"\" outcome=\"Passed\" />" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod name=\"\" />" + "<TestMethod />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutTestNames.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(0, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PendingOutcomeTreatedAsNotExecuted() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Pending\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "NotExecuted"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ThereAreNoResultsWithInvalidGuid() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"asdf\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"asdf\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"asdf\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"asdf\" testId = \"asdf\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"asfd\" outcome = \"Failed\" testListId = \"asdf\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "</Results></TestRun>"; _trxResultFile = "ResultsWithInvalidGuid.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(1, runData.Results.Length); Assert.Equal(null, runData.Results[0].AutomatedTestId); Assert.Equal(null, runData.Results[0].AutomatedTestTypeId); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithoutMandatoryFieldsAreSkipped() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"\" outcome=\"Passed\" />" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod name=\"\" />" + "<TestMethod />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutMandatoryFields.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(0, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValues() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.Results[0].StartedDate, StartedDate); TimeSpan Duration; TimeSpan.TryParse("00:00:00.0834563", out Duration); Assert.Equal(runData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(runData.Results[0].CompletedDate, CompletedDate); Assert.Equal(runData.Name, "VSTest Test Run debug any cpu"); Assert.Equal(runData.State, "InProgress"); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "Failed"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(runData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(runData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(runData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(runData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(runData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(runData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(runData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(runData.Results[0].Priority.ToString(), "1"); Assert.Equal(runData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(runData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(runData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(runData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(runData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(runData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(runData.Results[2].ComputerName, "random-DT"); Assert.Equal(runData.Results[2].AutomatedTestType, "OrderedTest"); Assert.Equal(runData.BuildFlavor, "debug"); Assert.Equal(runData.BuildPlatform, "any cpu"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(runData.Attachments.Length, 7); int buildId; int.TryParse(runData.Build.Id, out buildId); Assert.Equal(buildId, 1); Assert.Equal(runData.ReleaseUri, "releaseUri"); Assert.Equal(runData.ReleaseEnvironmentUri, "releaseEnvironmentUri"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValuesForHierarchicalResults() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" />" + "</UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "<InnerResults>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"SubResult 1 (TestMethod2)\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "</InnerResults>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var testRunData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime StartedDate); Assert.Equal(testRunData.Results[0].StartedDate, StartedDate); TimeSpan.TryParse("00:00:00.0834563", out TimeSpan Duration); Assert.Equal(testRunData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(testRunData.Results[0].CompletedDate, CompletedDate); Assert.Equal(testRunData.Results.Length, 3); Assert.Equal(testRunData.Results[0].Outcome, "Failed"); Assert.Equal(testRunData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(testRunData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(testRunData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(testRunData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(testRunData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(testRunData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(testRunData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(testRunData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(testRunData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(testRunData.Results[0].Priority.ToString(), "1"); Assert.Equal(testRunData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(testRunData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(testRunData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); // Testing subResult properties Assert.Equal(testRunData.Results[0].TestCaseSubResultData.Count, 1); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].DisplayName, "SubResult 1 (TestMethod2)"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].Outcome, "Failed"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(testRunData.Results[1].Outcome, "Passed"); Assert.Equal(testRunData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(testRunData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(testRunData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(testRunData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(testRunData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(testRunData.Results[2].Outcome, "Passed"); Assert.Equal(testRunData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(testRunData.Results[2].ComputerName, "random-DT"); Assert.Equal(testRunData.Results[2].AutomatedTestType, "OrderedTest"); // Testing subResult properties Assert.Equal(testRunData.Results[2].TestCaseSubResultData.Count, 2); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[0].DisplayName, "01- CodedUITestMethod1 (OrderedTest1)"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[1].DisplayName, "02- CodedUITestMethod2 (OrderedTest1)"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[0].Outcome, "Passed"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[1].Outcome, "Passed"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(testRunData.Attachments.Length, 7); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValuesInDifferentCulture() { SetupMocks(); CultureInfo current = CultureInfo.CurrentCulture; try { //German is used, as in this culture decimal seperator is comma & thousand seperator is dot CultureInfo.CurrentCulture = new CultureInfo("de-DE"); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.Results[0].StartedDate, StartedDate); TimeSpan Duration; TimeSpan.TryParse("00:00:00.0834563", out Duration); Assert.Equal(runData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(runData.Results[0].CompletedDate, CompletedDate); Assert.Equal(runData.Name, "VSTest Test Run debug any cpu"); Assert.Equal(runData.State, "InProgress"); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "Failed"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(runData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(runData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(runData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(runData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(runData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(runData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(runData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(runData.Results[0].Priority.ToString(), "1"); Assert.Equal(runData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(runData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(runData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(runData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(runData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(runData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(runData.Results[2].ComputerName, "random-DT"); Assert.Equal(runData.Results[2].AutomatedTestType, "OrderedTest"); Assert.Equal(runData.BuildFlavor, "debug"); Assert.Equal(runData.BuildPlatform, "any cpu"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(runData.Attachments.Length, 7); int buildId; int.TryParse(runData.Build.Id, out buildId); Assert.Equal(buildId, 1); Assert.Equal(runData.ReleaseUri, "releaseUri"); Assert.Equal(runData.ReleaseEnvironmentUri, "releaseEnvironmentUri"); } finally { CultureInfo.CurrentCulture = current; } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void CustomRunTitleIsHonoured() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithCustomRunTitle.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.Equal(runData.Name, "My Run Title"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailForBareMinimumTrx() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Inconclusive\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "bareMinimum.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); Assert.Equal(runData.Results[0].Outcome, "Inconclusive"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithoutStartTime() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutStartTime.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithoutFinishTime() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutFinishTime"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithFinishTimeLessThanStartTime() { SetupMocks(); var runData = GetTestRunDataBasic(); Assert.Equal(1, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunLevelResultsFilePresentByDefault() { SetupMocks(); var runData = GetTestRunDataBasic(); Assert.Equal(_trxResultFile, runData.Attachments[0]); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunLevelResultsFileAbsentIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataBasic(myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyResultsFilesAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(2); Assert.Equal(4, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(1); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachmentsWithDeployment() { SetupMocks(); var runData = GetTestRunDataWithAttachments(13); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDataCollectorFilesAndPdbsAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(0); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoDataCollectorFilesAndPdbsAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(0, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoResultsFilesAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(2, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(1, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunTypeIsSet() { SetupMocks(); var runData = GetTestRunDataWithAttachments(0); Assert.Equal("unittest".ToLowerInvariant(), runData.Results[0].AutomatedTestType.ToLowerInvariant()); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyReadResultsReturnsCorrectTestStartAndEndDateTime() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3349628+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.StartDate, StartedDate.ToString("o")); DateTime CompletedDate; DateTime.TryParse("2015-03-20T16:53:32.9232329+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out CompletedDate); Assert.Equal(runData.CompleteDate, CompletedDate.ToString("o")); } public void Dispose() { try { File.Delete(_trxResultFile); } catch { } } private TestRunData GetTestRunDataBasic(TrxResultReader myReader = null) { string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2014-03-20T16:53:32.3349628+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; return GetTestRunData(trxContents, myReader); } private TestRunData GetTestRunDataWithAttachments(int val, TrxResultReader myReader = null, TestRunContext trContext = null) { var trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "{3}" + "</TestSettings>" + "{0}" + "{1}" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "{2}" + "</ResultSummary>" + "</TestRun>"; var part0 = "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\">" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>"; var part1 = "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>"; var part2 = "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />"; var part3 = "<Deployment runDeploymentRoot=\"results\"></Deployment>"; switch (val) { case 0: trxContents = string.Format(trxContents, part0, string.Empty, string.Empty, string.Empty); break; case 1: trxContents = string.Format(trxContents, string.Empty, part1, string.Empty, string.Empty); break; case 2: trxContents = string.Format(trxContents, string.Empty, string.Empty, part2, string.Empty); break; case 3: trxContents = string.Format(trxContents, string.Empty, string.Empty, string.Empty, string.Empty); break; case 13: trxContents = string.Format(trxContents, string.Empty, part1, string.Empty, part3); break; default: trxContents = string.Format(trxContents, part0, part1, part2); break; } return GetTestRunData(trxContents, myReader, trContext); } private void SetupMocks([CallerMemberName] string name = "") { TestHostContext hc = new TestHostContext(this, name); _ec = new Mock<IExecutionContext>(); List<string> warnings; var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings); _ec.Setup(x => x.Variables).Returns(variables); } private TestRunData GetTestRunData(string trxContents, TrxResultReader myReader = null, TestRunContext trContext = null) { _trxResultFile = "results.trx"; File.WriteAllText(_trxResultFile, trxContents); var reader = myReader ?? new TrxResultReader(); var runData = reader.ReadResults(_ec.Object, _trxResultFile, trContext ?? new TestRunContext(null, null, null, 1, null, null, null)); return runData; } } }
using System; using System.Diagnostics; using System.Runtime.Serialization; using Hammock.Model; using Newtonsoft.Json; namespace TweetSharp { #if !SILVERLIGHT /// <summary> /// Represents a private <see cref="TwitterStatus" /> between two users. /// </summary> [Serializable] #endif #if !Smartphone && !NET20 [DataContract] [DebuggerDisplay("{SenderScreenName} to {RecipientScreenName}:{Text}")] #endif [JsonObject(MemberSerialization.OptIn)] public class TwitterDirectMessage : PropertyChangedBase, IComparable<TwitterDirectMessage>, IEquatable<TwitterDirectMessage>, ITwitterModel, ITweetable { private long _id; private long _recipientId; private string _recipientScreenName; private TwitterUser _recipient; private long _senderId; private TwitterUser _sender; private string _senderScreenName; private string _text; private DateTime _createdDate; private TwitterEntities _entities; #if !Smartphone && !NET20 [DataMember] #endif public virtual long Id { get { return _id; } set { if (_id == value) { return; } _id = value; OnPropertyChanged("Id"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual long RecipientId { get { return _recipientId; } set { if (_recipientId == value) { return; } _recipientId = value; OnPropertyChanged("RecipientId"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RecipientScreenName { get { return _recipientScreenName; } set { if (_recipientScreenName == value) { return; } _recipientScreenName = value; OnPropertyChanged("RecipientScreenName"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterUser Recipient { get { return _recipient; } set { if (_recipient == value) { return; } _recipient = value; OnPropertyChanged("Recipient"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual long SenderId { get { return _senderId; } set { if (_senderId == value) { return; } _senderId = value; OnPropertyChanged("SenderId"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterUser Sender { get { return _sender; } set { if (_sender == value) { return; } _sender = value; OnPropertyChanged("Sender"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string SenderScreenName { get { return _senderScreenName; } set { if (_senderScreenName == value) { return; } _senderScreenName = value; OnPropertyChanged("SenderScreenName"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string Text { get { return _text; } set { if (_text == value) { return; } _text = value; _entities = null; OnPropertyChanged("Text"); } } private string _textAsHtml; public virtual string TextAsHtml { get { if (string.IsNullOrEmpty(Text)) { return Text; } return _textAsHtml ?? (_textAsHtml = Text.ParseTwitterageToHtml()); } set { _entities = null; _textAsHtml = value; } } public ITweeter Author { get { return Sender; } } #if !Smartphone && !NET20 [DataMember] #endif [JsonProperty("created_at")] public virtual DateTime CreatedDate { get { return _createdDate; } set { if (_createdDate == value) { return; } _createdDate = value; OnPropertyChanged("CreatedDate"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterEntities Entities { get { return _entities ?? (Entities = Text.ParseTwitterageToEntities()); } set { if (_entities != null) { return; } _entities = value; OnPropertyChanged("Entities"); } } #region IComparable<TwitterDirectMessage> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. /// </returns> /// <param name="other">An object to compare with this object.</param> public int CompareTo(TwitterDirectMessage other) { return other.Id == Id ? 0 : other.Id > Id ? -1 : 1; } #endregion #region IEquatable<TwitterDirectMessage> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="obj">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="obj"/> parameter; otherwise, false. /// </returns> public bool Equals(TwitterDirectMessage obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.Id == Id; } #endregion /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == typeof (TwitterDirectMessage) && Equals((TwitterDirectMessage) obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return Id.GetHashCode(); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(TwitterDirectMessage left, TwitterDirectMessage right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(TwitterDirectMessage left, TwitterDirectMessage right) { return !Equals(left, right); } #if !Smartphone && !NET20 /// <summary> /// The source content used to deserialize the model entity instance. /// Can be XML or JSON, depending on the endpoint used. /// </summary> [DataMember] #endif public virtual string RawSource { get; set; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Security; using System.Security.Permissions; using System.ComponentModel; using System.Collections; using System.Windows; using System.Windows.Input; using System.Windows.Markup; using MS.Internal.PresentationCore; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace System.Windows.Input { /// <summary> /// A command that causes handlers associated with it to be called. /// </summary> [TypeConverter("System.Windows.Input.CommandConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] [ValueSerializer("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] public class RoutedCommand : ICommand { #region Constructors /// <summary> /// Default Constructor - needed to allow markup creation /// </summary> public RoutedCommand() { _name = String.Empty; _ownerType = null; _inputGestureCollection = null; } /// <summary> /// RoutedCommand Constructor with Name and OwnerType /// </summary> /// <param name="name">Declared Name of the RoutedCommand for Serialization</param> /// <param name="ownerType">Type that is registering the property</param> public RoutedCommand(string name, Type ownerType) : this(name, ownerType, null) { } /// <summary> /// RoutedCommand Constructor with Name and OwnerType /// </summary> /// <param name="name">Declared Name of the RoutedCommand for Serialization</param> /// <param name="ownerType">Type that is registering the property</param> /// <param name="inputGestures">Default Input Gestures associated</param> public RoutedCommand(string name, Type ownerType, InputGestureCollection inputGestures) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Get(SRID.StringEmpty), "name"); } if (ownerType == null) { throw new ArgumentNullException("ownerType"); } _name = name; _ownerType = ownerType; _inputGestureCollection = inputGestures; } /// <summary> /// RoutedCommand Constructor with Name and OwnerType and command identifier. /// </summary> /// <param name="name">Declared Name of the RoutedCommand for Serialization</param> /// <param name="ownerType">Type that is registering the property</param> /// <param name="commandId">Byte identifier for the command assigned by the owning type</param> internal RoutedCommand(string name, Type ownerType, byte commandId) : this(name, ownerType, null) { _commandId = commandId; } #endregion #region ICommand /// <summary> /// Executes the command with the given parameter on the currently focused element. /// </summary> /// <param name="parameter">Parameter to pass to any command handlers.</param> void ICommand.Execute(object parameter) { Execute(parameter, FilterInputElement(Keyboard.FocusedElement)); } /// <summary> /// Whether the command can be executed with the given parameter on the currently focused element. /// </summary> /// <param name="parameter">Parameter to pass to any command handlers.</param> /// <returns>true if the command can be executed, false otherwise.</returns> /// <SecurityNote> /// Critical: This code takes in a trusted bit which can be used to cause elevations for paste /// PublicOK: This code passes the flag in as false /// </SecurityNote> [SecurityCritical] bool ICommand.CanExecute(object parameter) { bool unused; return CanExecuteImpl(parameter, FilterInputElement(Keyboard.FocusedElement), false, out unused); } /// <summary> /// Raised when CanExecute should be requeried on commands. /// Since commands are often global, it will only hold onto the handler as a weak reference. /// Users of this event should keep a strong reference to their event handler to avoid /// it being garbage collected. This can be accomplished by having a private field /// and assigning the handler as the value before or after attaching to this event. /// </summary> public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } #endregion #region Public Methods /// <summary> /// Executes the command with the given parameter on the given target. /// </summary> /// <param name="parameter">Parameter to be passed to any command handlers.</param> /// <param name="target">Element at which to begin looking for command handlers.</param> /// <SecurityNote> /// Critical - calls critical function (ExecuteImpl) /// PublicOk - always passes in false for userInitiated, which is safe /// </SecurityNote> [SecurityCritical] public void Execute(object parameter, IInputElement target) { // We only support UIElement, ContentElement and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } ExecuteImpl(parameter, target, false); } /// <summary> /// Whether the command can be executed with the given parameter on the given target. /// </summary> /// <param name="parameter">Parameter to be passed to any command handlers.</param> /// <param name="target">The target element on which to begin looking for command handlers.</param> /// <returns>true if the command can be executed, false otherwise.</returns> /// <SecurityNote> /// Critical: This can be used to spoof input and cause userinitiated permission to be asserted /// PublicOK: The call sets trusted bit to false which prevents user initiated permission from being asserted /// </SecurityNote> [SecurityCritical] public bool CanExecute(object parameter, IInputElement target) { bool unused; return CriticalCanExecute(parameter, target, false, out unused); } /// <summary> /// Whether the command can be executed with the given parameter on the given target. /// </summary> /// <param name="parameter">Parameter to be passed to any command handlers.</param> /// <param name="target">The target element on which to begin looking for command handlers.</param> /// <param name="trusted">Determines whether this call will elevate for userinitiated input or not.</param> /// <param name="continueRouting">Determines whether the input event (if any) that caused this command should continue its route.</param> /// <returns>true if the command can be executed, false otherwise.</returns> /// <SecurityNote> /// Critical: This code takes in a trusted bit which can be used to cause elevations for paste /// </SecurityNote> [SecurityCritical] internal bool CriticalCanExecute(object parameter, IInputElement target, bool trusted, out bool continueRouting) { // We only support UIElement, ContentElement, and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } return CanExecuteImpl(parameter, target, trusted, out continueRouting); } #endregion #region Public Properties /// <summary> /// Name - Declared time Name of the property/field where it is /// defined, for serialization/debug purposes only. /// Ex: public static RoutedCommand New { get { new RoutedCommand("New", .... ) } } /// public static RoutedCommand New = new RoutedCommand("New", ... ) ; /// </summary> public string Name { get { return _name; } } /// <summary> /// Owning type of the property /// </summary> public Type OwnerType { get { return _ownerType; } } /// <summary> /// Identifier assigned by the owning Type. Note that this is not a global command identifier. /// </summary> internal byte CommandId { get { return _commandId; } } /// <summary> /// Input Gestures associated with RoutedCommand /// </summary> public InputGestureCollection InputGestures { get { if(InputGesturesInternal == null) { _inputGestureCollection = new InputGestureCollection(); } return _inputGestureCollection; } } internal InputGestureCollection InputGesturesInternal { get { if(_inputGestureCollection == null && AreInputGesturesDelayLoaded) { _inputGestureCollection = GetInputGestures(); AreInputGesturesDelayLoaded = false; } return _inputGestureCollection; } } /// <summary> /// Fetches the default input gestures for the command by invoking the LoadDefaultGestureFromResource function on the owning type. /// </summary> /// <returns>collection of input gestures for the command</returns> private InputGestureCollection GetInputGestures() { if(OwnerType == typeof(ApplicationCommands)) { return ApplicationCommands.LoadDefaultGestureFromResource(_commandId); } else if(OwnerType == typeof(NavigationCommands)) { return NavigationCommands.LoadDefaultGestureFromResource(_commandId); } else if(OwnerType == typeof(MediaCommands)) { return MediaCommands.LoadDefaultGestureFromResource(_commandId); } else if(OwnerType == typeof(ComponentCommands)) { return ComponentCommands.LoadDefaultGestureFromResource(_commandId); } return new InputGestureCollection(); } /// <summary> /// Rights Management Enabledness /// Will be set by Rights Management code. /// internal bool IsBlockedByRM { [SecurityCritical] get { return ReadPrivateFlag(PrivateFlags.IsBlockedByRM); } [UIPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)] [SecurityCritical] set { WritePrivateFlag(PrivateFlags.IsBlockedByRM, value); } } /// <SecurityNote> /// Critical: Calls WritePrivateFlag /// TreatAsSafe: Setting IsBlockedByRM is a critical operation. Setting AreInputGesturesDelayLoaded isn't. /// </SecurityNote> internal bool AreInputGesturesDelayLoaded { get { return ReadPrivateFlag(PrivateFlags.AreInputGesturesDelayLoaded); } [SecurityCritical, SecurityTreatAsSafe] set { WritePrivateFlag(PrivateFlags.AreInputGesturesDelayLoaded, value); } } #endregion #region Implementation private static IInputElement FilterInputElement(IInputElement elem) { // We only support UIElement, ContentElement, and UIElement3D if ((elem != null) && InputElement.IsValid(elem)) { return elem; } return null; } /// <param name="parameter"></param> /// <param name="target"></param> /// <param name="trusted"></param> /// <param name="continueRouting"></param> /// <returns></returns> /// <SecurityNote> /// Critical: This code takes in a trusted bit which can be used to cause elevations for paste /// </SecurityNote> [SecurityCritical] private bool CanExecuteImpl(object parameter, IInputElement target, bool trusted, out bool continueRouting) { // If blocked by rights-management fall through and return false if ((target != null) && !IsBlockedByRM) { // Raise the Preview Event, check the Handled value, and raise the regular event. CanExecuteRoutedEventArgs args = new CanExecuteRoutedEventArgs(this, parameter); args.RoutedEvent = CommandManager.PreviewCanExecuteEvent; CriticalCanExecuteWrapper(parameter, target, trusted, args); if (!args.Handled) { args.RoutedEvent = CommandManager.CanExecuteEvent; CriticalCanExecuteWrapper(parameter, target, trusted, args); } continueRouting = args.ContinueRouting; return args.CanExecute; } else { continueRouting = false; return false; } } /// <SecurityNote> /// Critical: This code takes in a trusted bit which can be used to cause elevations for paste /// </SecurityNote> [SecurityCritical] private void CriticalCanExecuteWrapper(object parameter, IInputElement target, bool trusted, CanExecuteRoutedEventArgs args) { // This cast is ok since we are already testing for UIElement, ContentElement, or UIElement3D // both of which derive from DO DependencyObject targetAsDO = (DependencyObject)target; if (InputElement.IsUIElement(targetAsDO)) { ((UIElement)targetAsDO).RaiseEvent(args, trusted); } else if (InputElement.IsContentElement(targetAsDO)) { ((ContentElement)targetAsDO).RaiseEvent(args, trusted); } else if (InputElement.IsUIElement3D(targetAsDO)) { ((UIElement3D)targetAsDO).RaiseEvent(args, trusted); } } /// <SecurityNote> /// Critical - Calls ExecuteImpl, which sets the user initiated bit on a command, which is used /// for security purposes later. It is important to validate /// the callers of this, and the implementation to make sure /// that we only call MarkAsUserInitiated in the correct cases. /// </SecurityNote> [SecurityCritical] internal bool ExecuteCore(object parameter, IInputElement target, bool userInitiated) { if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } return ExecuteImpl(parameter, target, userInitiated); } /// <SecurityNote> /// Critical - sets the user initiated bit on a command, which is used /// for security purposes later. It is important to validate /// the callers of this, and the implementation to make sure /// that we only call MarkAsUserInitiated in the correct cases. /// </SecurityNote> [SecurityCritical] private bool ExecuteImpl(object parameter, IInputElement target, bool userInitiated) { // If blocked by rights-management fall through and return false if ((target != null) && !IsBlockedByRM) { UIElement targetUIElement = target as UIElement; ContentElement targetAsContentElement = null; UIElement3D targetAsUIElement3D = null; // Raise the Preview Event and check for Handled value, and // Raise the regular ExecuteEvent. ExecutedRoutedEventArgs args = new ExecutedRoutedEventArgs(this, parameter); args.RoutedEvent = CommandManager.PreviewExecutedEvent; if (targetUIElement != null) { targetUIElement.RaiseEvent(args, userInitiated); } else { targetAsContentElement = target as ContentElement; if (targetAsContentElement != null) { targetAsContentElement.RaiseEvent(args, userInitiated); } else { targetAsUIElement3D = target as UIElement3D; if (targetAsUIElement3D != null) { targetAsUIElement3D.RaiseEvent(args, userInitiated); } } } if (!args.Handled) { args.RoutedEvent = CommandManager.ExecutedEvent; if (targetUIElement != null) { targetUIElement.RaiseEvent(args, userInitiated); } else if (targetAsContentElement != null) { targetAsContentElement.RaiseEvent(args, userInitiated); } else if (targetAsUIElement3D != null) { targetAsUIElement3D.RaiseEvent(args, userInitiated); } } return args.Handled; } return false; } #endregion #region PrivateMethods /// <SecurityNote> /// Critical - Accesses _flags. Setting IsBlockedByRM is a critical operation. Setting other flags should be fine. /// </SecurityNote> [SecurityCritical] private void WritePrivateFlag(PrivateFlags bit, bool value) { if (value) { _flags.Value |= bit; } else { _flags.Value &= ~bit; } } private bool ReadPrivateFlag(PrivateFlags bit) { return (_flags.Value & bit) != 0; } #endregion PrivateMethods #region Data private string _name; /// <SecurityNote> /// Critical : Holds the value to IsBlockedByRM which should not be settable from PartialTrust. /// </SecurityNote> private MS.Internal.SecurityCriticalDataForSet<PrivateFlags> _flags; private enum PrivateFlags : byte { IsBlockedByRM = 0x01, AreInputGesturesDelayLoaded = 0x02 } private Type _ownerType; private InputGestureCollection _inputGestureCollection; private byte _commandId; //Note that this is NOT a global command identifier. It is specific to the owning type. //it represents one of the CommandID enums defined by each of the command types and will be cast to one of them when used. #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- $River::EditorOpen = false; $River::wireframe = true; $River::showSpline = true; $River::showRiver = true; $River::showWalls = true; function RiverEditorGui::onEditorActivated( %this ) { %count = EWorldEditor.getSelectionSize(); for ( %i = 0; %i < %count; %i++ ) { %obj = EWorldEditor.getSelectedObject(%i); if ( %obj.getClassName() !$= "River" ) EWorldEditor.unselectObject( %obj ); else %this.setSelectedRiver( %obj ); } %this.onRiverSelected( %this.getSelectedRiver() ); %this.onNodeSelected(-1); } function RiverEditorGui::onEditorDeactivated( %this ) { } function RiverEditorGui::createRiver( %this ) { %river = new River() { rippleDir[0] = "0.000000 1.000000"; rippleDir[1] = "0.707000 0.707000"; rippleDir[2] = "0.500000 0.860000"; rippleSpeed[0] = "-0.065"; rippleSpeed[1] = "0.09"; rippleSpeed[2] = "0.04"; rippleTexScale[0] = "7.140000 7.140000"; rippleTexScale[1] = "6.250000 12.500000"; rippleTexScale[2] = "50.000000 50.000000"; waveDir[0] = "0.000000 1.000000"; waveDir[1] = "0.707000 0.707000"; waveDir[2] = "0.500000 0.860000"; waveSpeed[0] = "1"; waveSpeed[1] = "1"; waveSpeed[2] = "1"; waveMagnitude[0] = "0.2"; waveMagnitude[1] = "0.2"; waveMagnitude[2] = "0.2"; baseColor = "45 108 171 255"; rippleTex = "art/textures/water/ripple.dds"; foamTex = "art/textures/water/foam"; depthGradientTex = "art/textures/water/depthcolor_ramp"; }; return %river; } function RiverEditorGui::paletteSync( %this, %mode ) { %evalShortcut = "LabPaletteArray-->" @ %mode @ ".setStateOn(1);"; eval(%evalShortcut); } function RiverEditorGui::onEscapePressed( %this ) { if( %this.getMode() $= "RiverEditorAddNodeMode" ) { %this.prepSelectionMode(); return true; } return false; } function RiverEditorGui::onRiverSelected( %this, %river ) { %this.river = %river; RiverInspector.inspect( %river ); RiverTreeView.buildVisibleTree(true); RiverManager.currentRiver = %river; if( RiverTreeView.getSelectedObject() != %river ) { RiverTreeView.clearSelection(); %treeId = RiverTreeView.findItemByObjectId( %river ); RiverTreeView.selectItem( %treeId ); } RiverManager.updateRiverData(); } function RiverEditorGui::onNodeSelected( %this, %nodeIdx ) { RiverEditorGui.selectedNode = %nodeIdx; if ( %nodeIdx == -1 ) { RiverEditorGui.selectedNode = %nodeIdx; RiverEditorOptionsWindow-->position.setActive( false ); RiverEditorOptionsWindow-->position.setValue( "" ); RiverEditorOptionsWindow-->rotation.setActive( false ); RiverEditorOptionsWindow-->rotation.setValue( "" ); RiverEditorOptionsWindow-->CurrentWidth.setActive( false ); RiverEditorOptionsWindow-->CurrentWidth.setValue( "" ); RiverEditorOptionsWindow-->CurrentWidthSlider.setActive( false ); RiverEditorOptionsWindow-->CurrentWidthSlider.setValue( "" ); RiverEditorOptionsWindow-->CurrentDepth.setActive( false ); RiverEditorOptionsWindow-->CurrentDepth.setValue( "" ); RiverEditorOptionsWindow-->CurrentDepthSlider.setActive( false ); RiverEditorOptionsWindow-->CurrentDepthSlider.setValue( "" ); } else { RiverEditorOptionsWindow-->position.setActive( true ); RiverEditorOptionsWindow-->position.setValue( %this.getNodePosition() ); RiverEditorOptionsWindow-->rotation.setActive( true ); RiverEditorOptionsWindow-->rotation.setValue( %this.getNodeNormal() ); RiverEditorOptionsWindow-->CurrentWidth.setActive( true ); RiverEditorOptionsWindow-->CurrentWidth.setValue( %this.getNodeWidth() ); RiverEditorOptionsWindow-->CurrentWidthSlider.setActive( true ); RiverEditorOptionsWindow-->CurrentWidthSlider.setValue( %this.getNodeWidth() ); RiverEditorOptionsWindow-->CurrentDepth.setActive( true ); RiverEditorOptionsWindow-->CurrentDepth.setValue( %this.getNodeDepth() ); RiverEditorOptionsWindow-->CurrentDepthSlider.setActive( true ); RiverEditorOptionsWindow-->CurrentDepthSlider.setValue( %this.getNodeDepth() ); } RiverManager.onNodeSelected(%nodeIdx,true); } function RiverEditorGui::onNodeModified( %this, %nodeIdx ) { devLog("RiverEditorGui::onNodeModified( %this, %nodeIdx )",%nodeIdx); RiverEditorOptionsWindow-->position.setValue( %this.getNodePosition() ); RiverEditorOptionsWindow-->rotation.setValue( %this.getNodeNormal() ); RiverEditorOptionsWindow-->width.setValue( %this.getNodeWidth() ); RiverEditorOptionsWindow-->depth.setValue( %this.getNodeDepth() ); RiverManager.onNodeModified(%nodeIdx); } function RiverEditorGui::editNodeDetails( %this ) { %this.setNodePosition( RiverEditorOptionsWindow-->position.getText() ); %this.setNodeNormal( RiverEditorOptionsWindow-->rotation.getText() ); %this.setNodeWidth( RiverEditorOptionsWindow-->width.getText() ); %this.setNodeDepth( RiverEditorOptionsWindow-->depth.getText() ); } function RiverTreeView::onSelect(%this, %obj) { RiverEditorGui.road = %obj; RiverInspector.inspect( %obj ); if(%obj != RiverEditorGui.getSelectedRiver()) { RiverEditorGui.setSelectedRiver( %obj ); } } function RiverEditorGui::prepSelectionMode( %this ) { %mode = %this.getMode(); if ( %mode $= "RiverEditorAddNodeMode" ) { if ( isObject( %this.getSelectedRiver() ) ) %this.deleteNode(); } %this.setMode( "RiverEditorSelectMode" ); LabPaletteArray-->RiverEditorSelectMode.setStateOn(1); } //------------------------------------------------------------------------------ function ERiverEditorSelectModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Select"; } function ERiverEditorAddModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Add"; } function ERiverEditorMoveModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Move"; } function ERiverEditorRotateModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Rotate"; } function ERiverEditorScaleModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Scale"; } function ERiverEditorInsertModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Insert"; } function ERiverEditorRemoveModeBtn::onClick(%this) { EditorGuiStatusBar.setInfo(%this.ToolTip); RiverManager.toolMode = "Remove"; } function RiverDefaultWidthSliderCtrlContainer::onWake(%this) { RiverDefaultWidthSliderCtrlContainer-->slider.setValue(RiverDefaultWidthTextEditContainer-->textEdit.getText()); } function RiverDefaultDepthSliderCtrlContainer::onWake(%this) { RiverDefaultDepthSliderCtrlContainer-->slider.setValue(RiverDefaultDepthTextEditContainer-->textEdit.getText()); }
using System; using System.ComponentModel; using System.Threading.Tasks; using Android.Graphics; using Android.Graphics.Drawables; using Android.Runtime; using Android.Views; using Android.Widget; using ImageButton.Abstractions; using ImageButton.Android; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Color = Android.Graphics.Color; using Object = Java.Lang.Object; using View = Android.Views.View; [assembly: ExportRenderer(typeof(ImageButton.Abstractions.ImageButton), typeof(ImageButtonRenderer))] namespace ImageButton.Android { [Preserve(AllMembers = true)] public class ImageButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ViewRenderer <Abstractions.ImageButton, global::Android.Widget.ImageButton> { private bool _isDisposed; public static void Init() { var temp = DateTime.Now; } protected override global::Android.Widget.ImageButton CreateNativeControl() { var imageButton = new global::Android.Widget.ImageButton(Context); return imageButton; } protected override void OnElementChanged(ElementChangedEventArgs<Abstractions.ImageButton> e) { base.OnElementChanged(e); if (e.OldElement != null) { } if (e.NewElement != null) { if (Control == null) { var imageButton = CreateNativeControl(); imageButton.SetScaleType(ImageView.ScaleType.FitCenter); imageButton.SetAdjustViewBounds(true); imageButton.SetPadding(0, 0, 0, 0); imageButton.SetBackgroundColor(Color.Transparent); imageButton.SetOnClickListener(ButtonClickListener.Instance.Value); imageButton.SetOnTouchListener(ButtonTouchListener.Instance.Value); imageButton.Tag = this; SetNativeControl(imageButton); } UpdateBitmap(); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Abstractions.ImageButton.SourceProperty.PropertyName || e.PropertyName == Abstractions.ImageButton.PressedSourceProperty.PropertyName || e.PropertyName == Abstractions.ImageButton.SelectedSourceProperty.PropertyName) { UpdateBitmap(); } } protected virtual StateListDrawable MakeSelector(Bitmap bitmap, Bitmap pressedBitmap, Bitmap selectedBitmap) { BitmapDrawable image = null; BitmapDrawable pressedImage = null; BitmapDrawable selectedImage = null; if (bitmap != null) { image = new BitmapDrawable(bitmap); } if (pressedBitmap != null) { pressedImage = new BitmapDrawable(pressedBitmap); } if (selectedBitmap != null) { selectedImage = new BitmapDrawable(selectedBitmap); } var res = new StateListDrawable(); if (selectedImage != null) { res.AddState(new[] { global::Android.Resource.Attribute.StateSelected }, selectedImage); } if (pressedImage != null) { res.AddState(new[] {global::Android.Resource.Attribute.StatePressed}, pressedImage); } if (image != null) { res.AddState(new int[] {}, image); } return res; } protected virtual async void UpdateBitmap() { var defaultImage = await GetDefaultBitmap(); var pressedImage = await GetPressedBitmap(); var selectedImage = await GetSelectedBitmap(); if (!_isDisposed) { if (defaultImage == null) { // Try to fetch the drawable another way var source = Element.Source as FileImageSource; if (source != null) { Control.SetImageResource(ResourceManager.GetDrawableByName(source.File)); } } else { Control.SetImageDrawable(MakeSelector(defaultImage, pressedImage, selectedImage)); } defaultImage?.Dispose(); pressedImage?.Dispose(); ((IVisualElementController) Element).NativeSizeChanged(); } } protected virtual Task<Bitmap> GetDefaultBitmap() { var elementImage = Element.Source; return GetBitmap(elementImage); } protected virtual Task<Bitmap> GetPressedBitmap() { var elementPressedImage = Element.PressedSource; return GetBitmap(elementPressedImage); } protected virtual Task<Bitmap> GetSelectedBitmap() { var elementSelectedImage = Element.SelectedSource; return GetBitmap(elementSelectedImage); } protected virtual async Task<Bitmap> GetBitmap(ImageSource imageSource) { if (imageSource == null) { return null; } Bitmap bitmap = null; try { var handler = new FileImageSourceHandler(); bitmap = await handler.LoadImageAsync(imageSource, Context); } catch { // ignored } if (Element == null) { bitmap?.Dispose(); return null; } return bitmap; } protected override void Dispose(bool disposing) { if (_isDisposed) { return; } _isDisposed = true; if (disposing) { if (Control != null) { Control.SetOnClickListener(null); Control.SetOnTouchListener(null); Control.Tag = null; } } base.Dispose(disposing); } private class ButtonClickListener : Object, IOnClickListener { #region Statics public static readonly Lazy<ButtonClickListener> Instance = new Lazy<ButtonClickListener>(() => new ButtonClickListener()); #endregion public void OnClick(View v) { var renderer = v.Tag as ImageButtonRenderer; ((IImageButtonController) renderer?.Element)?.SendClicked(); } } private class ButtonTouchListener : Object, IOnTouchListener { public static readonly Lazy<ButtonTouchListener> Instance = new Lazy<ButtonTouchListener>(() => new ButtonTouchListener()); public bool OnTouch(View v, MotionEvent e) { var renderer = v.Tag as ImageButtonRenderer; if (renderer != null) { var buttonController = renderer.Element as IImageButtonController; if (e.Action == MotionEventActions.Down) { buttonController?.SendPressed(); } else if (e.Action == MotionEventActions.Up) { v.Selected = !v.Selected; buttonController?.OnSelectedChanged(v.Selected); buttonController?.SendReleased(); } } return false; } } } }
using System; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Controllers; using NBitcoin; namespace BTCPayServer.Configuration { public class ExternalConnectionString { public ExternalConnectionString() { } public ExternalConnectionString(Uri server) { Server = server; } public Uri Server { get; set; } public byte[] Macaroon { get; set; } public Macaroons Macaroons { get; set; } public string MacaroonFilePath { get; set; } public string CertificateThumbprint { get; set; } public string MacaroonDirectoryPath { get; set; } public string APIToken { get; set; } public string CookieFilePath { get; set; } public string AccessKey { get; set; } /// <summary> /// Return a connectionString which does not depends on external resources or information like relative path or file path /// </summary> /// <returns></returns> public async Task<ExternalConnectionString> Expand(Uri absoluteUrlBase, ExternalServiceTypes serviceType, ChainName network) { var connectionString = this.Clone(); // Transform relative URI into absolute URI var serviceUri = connectionString.Server.IsAbsoluteUri ? connectionString.Server : ToRelative(absoluteUrlBase, connectionString.Server.ToString()); var isSecure = network != ChainName.Mainnet || serviceUri.Scheme == "https" || serviceUri.DnsSafeHost.EndsWith(".onion", StringComparison.OrdinalIgnoreCase) || Extensions.IsLocalNetwork(serviceUri.DnsSafeHost); if (!isSecure) { throw new System.Security.SecurityException($"Insecure transport protocol to access this service, please use HTTPS or TOR"); } connectionString.Server = serviceUri; if (serviceType == ExternalServiceTypes.LNDGRPC || serviceType == ExternalServiceTypes.LNDRest || serviceType == ExternalServiceTypes.CLightningRest) { // Read the MacaroonDirectory if (connectionString.MacaroonDirectoryPath != null) { try { connectionString.Macaroons = await Macaroons.GetFromDirectoryAsync(connectionString.MacaroonDirectoryPath); connectionString.MacaroonDirectoryPath = null; } catch (Exception ex) { throw new System.IO.DirectoryNotFoundException("Macaroon directory path not found", ex); } } // Read the MacaroonFilePath if (connectionString.MacaroonFilePath != null) { try { connectionString.Macaroon = await System.IO.File.ReadAllBytesAsync(connectionString.MacaroonFilePath); connectionString.MacaroonFilePath = null; } catch (Exception ex) { throw new System.IO.FileNotFoundException("Macaroon not found", ex); } } } if (new[] { ExternalServiceTypes.Charge, ExternalServiceTypes.RTL, ExternalServiceTypes.ThunderHub, ExternalServiceTypes.Spark, ExternalServiceTypes.Configurator }.Contains(serviceType)) { // Read access key from cookie file if (connectionString.CookieFilePath != null) { string cookieFileContent = null; bool isFake = false; try { cookieFileContent = await System.IO.File.ReadAllTextAsync(connectionString.CookieFilePath); isFake = connectionString.CookieFilePath == "fake"; connectionString.CookieFilePath = null; } catch (Exception ex) { throw new System.IO.FileNotFoundException("Cookie file path not found", ex); } if (serviceType == ExternalServiceTypes.RTL || serviceType == ExternalServiceTypes.Configurator || serviceType == ExternalServiceTypes.ThunderHub) { connectionString.AccessKey = cookieFileContent; } else if (serviceType == ExternalServiceTypes.Spark) { var cookie = (isFake ? "fake:fake:fake" // Hacks for testing : cookieFileContent).Split(':'); if (cookie.Length >= 3) { connectionString.AccessKey = cookie[2]; } else { throw new FormatException("Invalid cookiefile format"); } } else if (serviceType == ExternalServiceTypes.Charge) { connectionString.APIToken = isFake ? "fake" : cookieFileContent; } } } return connectionString; } private Uri ToRelative(Uri absoluteUrlBase, string path) { if (path.StartsWith('/')) path = path.Substring(1); return new Uri($"{absoluteUrlBase.AbsoluteUri.WithTrailingSlash()}{path}", UriKind.Absolute); } public ExternalConnectionString Clone() { return new ExternalConnectionString() { MacaroonFilePath = MacaroonFilePath, CertificateThumbprint = CertificateThumbprint, Macaroon = Macaroon, MacaroonDirectoryPath = MacaroonDirectoryPath, Server = Server, APIToken = APIToken, CookieFilePath = CookieFilePath, AccessKey = AccessKey, Macaroons = Macaroons?.Clone() }; } public bool? IsOnion() { return Server?.IsOnion(); } public static bool TryParse(string str, out ExternalConnectionString result, out string error) { ArgumentNullException.ThrowIfNull(str); error = null; result = null; var resultTemp = new ExternalConnectionString(); foreach (var kv in str.Split(';') .Select(part => part.Split('=')) .Where(kv => kv.Length == 2)) { switch (kv[0].ToLowerInvariant()) { case "server": if (resultTemp.Server != null) { error = "Duplicated server attribute"; return false; } if (!Uri.IsWellFormedUriString(kv[1], UriKind.RelativeOrAbsolute)) { error = "Invalid URI"; return false; } resultTemp.Server = new Uri(kv[1], UriKind.RelativeOrAbsolute); if (!resultTemp.Server.IsAbsoluteUri && (kv[1].Length == 0 || kv[1][0] != '/')) resultTemp.Server = new Uri($"/{kv[1]}", UriKind.RelativeOrAbsolute); break; case "cookiefile": case "cookiefilepath": if (resultTemp.CookieFilePath != null) { error = "Duplicated cookiefile attribute"; return false; } resultTemp.CookieFilePath = kv[1]; break; case "macaroondirectorypath": resultTemp.MacaroonDirectoryPath = kv[1]; break; case "certthumbprint": resultTemp.CertificateThumbprint = kv[1]; break; case "macaroonfilepath": resultTemp.MacaroonFilePath = kv[1]; break; case "api-token": resultTemp.APIToken = kv[1]; break; case "access-key": resultTemp.AccessKey = kv[1]; break; } } result = resultTemp; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Microsoft.AspNetCore.TestHost { internal class TestWebSocket : WebSocket { private readonly ReceiverSenderBuffer _receiveBuffer; private readonly ReceiverSenderBuffer _sendBuffer; private readonly string? _subProtocol; private WebSocketState _state; private WebSocketCloseStatus? _closeStatus; private string? _closeStatusDescription; private Message? _receiveMessage; public static Tuple<TestWebSocket, TestWebSocket> CreatePair(string? subProtocol) { var buffers = new[] { new ReceiverSenderBuffer(), new ReceiverSenderBuffer() }; return Tuple.Create( new TestWebSocket(subProtocol, buffers[0], buffers[1]), new TestWebSocket(subProtocol, buffers[1], buffers[0])); } public override WebSocketCloseStatus? CloseStatus { get { return _closeStatus; } } public override string? CloseStatusDescription { get { return _closeStatusDescription; } } public override WebSocketState State { get { return _state; } } public override string? SubProtocol { get { return _subProtocol; } } public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) { ThrowIfDisposed(); if (State == WebSocketState.Open || State == WebSocketState.CloseReceived) { // Send a close message. await CloseOutputAsync(closeStatus, statusDescription, cancellationToken); } if (State == WebSocketState.CloseSent) { // Do a receiving drain var data = new byte[1024]; WebSocketReceiveResult result; do { result = await ReceiveAsync(new ArraySegment<byte>(data), cancellationToken); } while (result.MessageType != WebSocketMessageType.Close); } } public override async Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) { ThrowIfDisposed(); ThrowIfOutputClosed(); var message = new Message(closeStatus, statusDescription); await _sendBuffer.SendAsync(message, cancellationToken); if (State == WebSocketState.Open) { _state = WebSocketState.CloseSent; } else if (State == WebSocketState.CloseReceived) { _state = WebSocketState.Closed; Close(); } } public override void Abort() { if (_state >= WebSocketState.Closed) // or Aborted { return; } _state = WebSocketState.Aborted; Close(); } public override void Dispose() { if (_state >= WebSocketState.Closed) // or Aborted { return; } _state = WebSocketState.Closed; Close(); } public override async Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { ThrowIfDisposed(); ThrowIfInputClosed(); ValidateSegment(buffer); // TODO: InvalidOperationException if any receives are currently in progress. Message? receiveMessage = _receiveMessage; _receiveMessage = null; if (receiveMessage == null) { receiveMessage = await _receiveBuffer.ReceiveAsync(cancellationToken); } if (receiveMessage.MessageType == WebSocketMessageType.Close) { _closeStatus = receiveMessage.CloseStatus; _closeStatusDescription = receiveMessage.CloseStatusDescription ?? string.Empty; var result = new WebSocketReceiveResult(0, WebSocketMessageType.Close, true, _closeStatus, _closeStatusDescription); if (_state == WebSocketState.Open) { _state = WebSocketState.CloseReceived; } else if (_state == WebSocketState.CloseSent) { _state = WebSocketState.Closed; Close(); } return result; } else { int count = Math.Min(buffer.Count, receiveMessage.Buffer.Count); bool endOfMessage = count == receiveMessage.Buffer.Count; Array.Copy(receiveMessage.Buffer.Array!, receiveMessage.Buffer.Offset, buffer.Array!, buffer.Offset, count); if (!endOfMessage) { receiveMessage.Buffer = new ArraySegment<byte>(receiveMessage.Buffer.Array!, receiveMessage.Buffer.Offset + count, receiveMessage.Buffer.Count - count); _receiveMessage = receiveMessage; } endOfMessage = endOfMessage && receiveMessage.EndOfMessage; return new WebSocketReceiveResult(count, receiveMessage.MessageType, endOfMessage); } } public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { ValidateSegment(buffer); if (messageType != WebSocketMessageType.Binary && messageType != WebSocketMessageType.Text) { // Block control frames throw new ArgumentOutOfRangeException(nameof(messageType), messageType, string.Empty); } var message = new Message(buffer, messageType, endOfMessage); return _sendBuffer.SendAsync(message, cancellationToken); } private void Close() { _receiveBuffer.SetReceiverClosed(); _sendBuffer.SetSenderClosed(); } private void ThrowIfDisposed() { if (_state >= WebSocketState.Closed) // or Aborted { throw new ObjectDisposedException(typeof(TestWebSocket).FullName); } } private void ThrowIfOutputClosed() { if (State == WebSocketState.CloseSent) { throw new InvalidOperationException("Close already sent."); } } private void ThrowIfInputClosed() { if (State == WebSocketState.CloseReceived) { throw new InvalidOperationException("Close already received."); } } private void ValidateSegment(ArraySegment<byte> buffer) { if (buffer.Array == null) { throw new ArgumentNullException(nameof(buffer)); } if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length) { throw new ArgumentOutOfRangeException(nameof(buffer), buffer.Offset, string.Empty); } if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset) { throw new ArgumentOutOfRangeException(nameof(buffer), buffer.Count, string.Empty); } } private TestWebSocket(string? subProtocol, ReceiverSenderBuffer readBuffer, ReceiverSenderBuffer writeBuffer) { _state = WebSocketState.Open; _subProtocol = subProtocol; _receiveBuffer = readBuffer; _sendBuffer = writeBuffer; } private class Message { public Message(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage) { Buffer = buffer; CloseStatus = null; CloseStatusDescription = null; EndOfMessage = endOfMessage; MessageType = messageType; } public Message(WebSocketCloseStatus? closeStatus, string? closeStatusDescription) { Buffer = new ArraySegment<byte>(Array.Empty<byte>()); CloseStatus = closeStatus; CloseStatusDescription = closeStatusDescription; MessageType = WebSocketMessageType.Close; EndOfMessage = true; } public WebSocketCloseStatus? CloseStatus { get; set; } public string? CloseStatusDescription { get; set; } public ArraySegment<byte> Buffer { get; set; } public bool EndOfMessage { get; set; } public WebSocketMessageType MessageType { get; set; } } private class ReceiverSenderBuffer { private bool _receiverClosed; private bool _senderClosed; private bool _disposed; private readonly SemaphoreSlim _sem; private readonly Queue<Message> _messageQueue; public ReceiverSenderBuffer() { _sem = new SemaphoreSlim(0); _messageQueue = new Queue<Message>(); } public virtual async Task<Message> ReceiveAsync(CancellationToken cancellationToken) { if (_disposed) { ThrowNoReceive(); } await _sem.WaitAsync(cancellationToken); lock (_messageQueue) { if (_messageQueue.Count == 0) { _disposed = true; _sem.Dispose(); ThrowNoReceive(); } return _messageQueue.Dequeue(); } } public virtual Task SendAsync(Message message, CancellationToken cancellationToken) { lock (_messageQueue) { if (_senderClosed) { throw new ObjectDisposedException(typeof(TestWebSocket).FullName); } if (_receiverClosed) { throw new IOException("The remote end closed the connection.", new ObjectDisposedException(typeof(TestWebSocket).FullName)); } // we return immediately so we need to copy the buffer since the sender can re-use it var array = new byte[message.Buffer.Count]; Array.Copy(message.Buffer.Array!, message.Buffer.Offset, array, 0, message.Buffer.Count); message.Buffer = new ArraySegment<byte>(array); _messageQueue.Enqueue(message); _sem.Release(); return Task.FromResult(true); } } public void SetReceiverClosed() { lock (_messageQueue) { if (!_receiverClosed) { _receiverClosed = true; if (!_disposed) { _sem.Release(); } } } } public void SetSenderClosed() { lock (_messageQueue) { if (!_senderClosed) { _senderClosed = true; if (!_disposed) { _sem.Release(); } } } } private void ThrowNoReceive() { if (_receiverClosed) { throw new ObjectDisposedException(typeof(TestWebSocket).FullName); } else // _senderClosed { throw new IOException("The remote end closed the connection.", new ObjectDisposedException(typeof(TestWebSocket).FullName)); } } } } }
#region Using directives using System; using System.Management.Automation; using System.Management.Automation.SecurityAccountsManager; using System.Management.Automation.SecurityAccountsManager.Extensions; using Microsoft.PowerShell.LocalAccounts; #endregion namespace Microsoft.PowerShell.Commands { /// <summary> /// The Set-LocalUser cmdlet changes the properties of a user account in the /// local Windows Security Accounts Manager. It can also reset the password of a /// local user account. /// </summary> [Cmdlet(VerbsCommon.Set, "LocalUser", SupportsShouldProcess = true, DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717984")] [Alias("slu")] public class SetLocalUserCommand : PSCmdlet { #region Static Data // Names of object- and boolean-type parameters. // Switch parameters don't need to be included. private static string[] parameterNames = new string[] { "AccountExpires", "Description", "FullName", "Password", "UserMayChangePassword", "PasswordNeverExpires" }; #endregion Static Data #region Instance Data private Sam sam = null; #endregion Instance Data #region Parameter Properties /// <summary> /// The following is the definition of the input parameter "AccountExpires". /// Specifies when the user account will expire. Set to null to indicate that /// the account will never expire. The default value is null (account never /// expires). /// </summary> [Parameter] public System.DateTime AccountExpires { get { return this.accountexpires;} set { this.accountexpires = value; } } private System.DateTime accountexpires; /// <summary> /// The following is the definition of the input parameter "AccountNeverExpires". /// Specifies that the account will not expire. /// </summary> [Parameter] public System.Management.Automation.SwitchParameter AccountNeverExpires { get { return this.accountneverexpires;} set { this.accountneverexpires = value; } } private System.Management.Automation.SwitchParameter accountneverexpires; /// <summary> /// The following is the definition of the input parameter "Description". /// A descriptive comment for this user account (48 characters). /// </summary> [Parameter] [ValidateNotNull] [ValidateLength(0, 48)] public string Description { get { return this.description;} set { this.description = value; } } private string description; /// <summary> /// The following is the definition of the input parameter "FullName". /// Specifies the full name of the user account. This is different from the /// username of the user account. /// </summary> [Parameter] [ValidateNotNull] public string FullName { get { return this.fullname;} set { this.fullname = value; } } private string fullname; /// <summary> /// The following is the definition of the input parameter "InputObject". /// Specifies the of the local user account to modify in the local Security /// Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "InputObject")] [ValidateNotNull] public Microsoft.PowerShell.Commands.LocalUser InputObject { get { return this.inputobject;} set { this.inputobject = value; } } private Microsoft.PowerShell.Commands.LocalUser inputobject; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies the local user account to change. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Name")] [ValidateNotNullOrEmpty] public string Name { get { return this.name;} set { this.name = value; } } private string name; /// <summary> /// The following is the definition of the input parameter "Password". /// Specifies the password for the local user account. /// </summary> [Parameter] [ValidateNotNull] public System.Security.SecureString Password { get { return this.password;} set { this.password = value; } } private System.Security.SecureString password; /// <summary> /// The following is the definition of the input parameter "PasswordNeverExpires". /// Specifies that the password will not expire. /// </summary> [Parameter] public System.Boolean PasswordNeverExpires { get { return this.passwordneverexpires; } set { this.passwordneverexpires = value; } } private System.Boolean passwordneverexpires; /// <summary> /// The following is the definition of the input parameter "SID". /// Specifies a user from the local Security Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "SecurityIdentifier")] [ValidateNotNull] public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} set { this.sid = value; } } private System.Security.Principal.SecurityIdentifier sid; /// <summary> /// The following is the definition of the input parameter "UserMayChangePassword". /// Specifies whether the user is allowed to change the password on this /// account. The default value is True. /// </summary> [Parameter] public System.Boolean UserMayChangePassword { get { return this.usermaychangepassword;} set { this.usermaychangepassword = value; } } private System.Boolean usermaychangepassword; #endregion Parameter Properties #region Cmdlet Overrides /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) { InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); ThrowTerminatingError(ex.MakeErrorRecord()); } sam = new Sam(); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { LocalUser user = null; if (InputObject != null) { if (CheckShouldProcess(InputObject.ToString())) user = InputObject; } else if (Name != null) { user = sam.GetLocalUser(Name); if (!CheckShouldProcess(Name)) user = null; } else if (SID != null) { user = sam.GetLocalUser(SID); if (!CheckShouldProcess(SID.ToString())) user = null; } if (user == null) return; // We start with what already exists var delta = user.Clone(); bool? passwordNeverExpires = null; foreach (var paramName in parameterNames) { if (this.HasParameter(paramName)) { switch (paramName) { case "AccountExpires": delta.AccountExpires = this.AccountExpires; break; case "Description": delta.Description = this.Description; break; case "FullName": delta.FullName = this.FullName; break; case "UserMayChangePassword": delta.UserMayChangePassword = this.UserMayChangePassword; break; case "PasswordNeverExpires": passwordNeverExpires = this.PasswordNeverExpires; break; } } } if (AccountNeverExpires.IsPresent) delta.AccountExpires = null; sam.UpdateLocalUser(user, delta, Password, passwordNeverExpires); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { if (sam != null) { sam.Dispose(); sam = null; } } #endregion Cmdlet Overrides #region Private Methods private bool CheckShouldProcess(string target) { return ShouldProcess(target, Strings.ActionSetUser); } #endregion Private Methods }//End Class }//End namespace
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Build.BuildEngine { /// <summary> /// Internal enum for distinguishing between cache content types /// </summary> internal enum CacheContentType { // Cached build results for targets - only accessible internally from the engine BuildResults = 0, // Items cached from tasks Items = 1, // Properties cached from tasks Properties = 2, LastContentTypeIndex = 2 } /// <summary> /// This class is responsible for maintaining the set of object /// cached during a build session. This class is not thread safe and /// is intended to be used from the Engine thread. /// </summary> internal class CacheManager { #region Constructors internal CacheManager(string defaultVersion) { cacheContents = new Hashtable[(int)CacheContentType.LastContentTypeIndex + 1]; for (int i = 0; i < (int)CacheContentType.LastContentTypeIndex + 1; i++) { cacheContents[i] = new Hashtable(StringComparer.OrdinalIgnoreCase); } this.defaultToolsVersion = defaultVersion; } #endregion #region Properties #endregion #region Methods private CacheScope GetCacheScopeIfExists(string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { CacheScope cacheScope = null; // Default the version to the default engine version if (scopeToolsVersion == null) { scopeToolsVersion = defaultToolsVersion; } // Retrieve list of scopes by this name if (cacheContents[(int)cacheContentType].ContainsKey(scopeName)) { List<CacheScope> scopesByName = (List<CacheScope>)cacheContents[(int)cacheContentType][scopeName]; // If the list exists search for matching scope properties otherwise create the list if (scopesByName != null) { lock (cacheManagerLock) { for (int i = 0; i < scopesByName.Count; i++) { if (scopesByName[i].ScopeProperties.IsEquivalent(scopeProperties) && (String.Equals(scopeToolsVersion, scopesByName[i].ScopeToolsVersion, StringComparison.OrdinalIgnoreCase))) { cacheScope = scopesByName[i]; break; } } } } } return cacheScope; } /// <summary> /// This method return a cache scope with particular name and properties. If the cache /// scope doesn't exist it will be created. This method is thread safe. /// </summary> internal CacheScope GetCacheScope(string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { // If the version is not specified default to the engine version if (scopeToolsVersion == null) { scopeToolsVersion = defaultToolsVersion; } // Retrieve the cache scope if it exists CacheScope cacheScope = GetCacheScopeIfExists(scopeName, scopeProperties, scopeToolsVersion, cacheContentType); // If the scope doesn't exist create it if (cacheScope == null) { lock (cacheManagerLock) { cacheScope = GetCacheScopeIfExists(scopeName, scopeProperties, scopeToolsVersion, cacheContentType); if (cacheScope == null) { // If the list of scopes doesn't exist create it if (!cacheContents[(int)cacheContentType].ContainsKey(scopeName)) { cacheContents[(int)cacheContentType].Add(scopeName, new List<CacheScope>()); } // Create the scope and add it to the list List<CacheScope> scopesByName = (List<CacheScope>)cacheContents[(int)cacheContentType][scopeName]; cacheScope = new CacheScope(scopeName, scopeProperties, scopeToolsVersion); scopesByName.Add(cacheScope); } } } return cacheScope; } /// <summary> /// Sets multiple cache entries for the given scope /// </summary> /// <param name="entries"></param> /// <param name="scopeName"></param> /// <param name="scopeProperties"></param> internal void SetCacheEntries(CacheEntry[] entries, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { // If the list exists search for matching scope properties otherwise create the list CacheScope cacheScope = GetCacheScope(scopeName, scopeProperties, scopeToolsVersion, cacheContentType); // Add the entry to the right scope cacheScope.AddCacheEntries(entries); } /// <summary> /// Gets multiple cache entries from the given scope. /// </summary> /// <param name="names"></param> /// <param name="scopeName"></param> /// <param name="scopeProperties"></param> /// <returns></returns> internal CacheEntry[] GetCacheEntries(string[] names, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { CacheScope cacheScope = GetCacheScopeIfExists(scopeName, scopeProperties, scopeToolsVersion, cacheContentType); if (cacheScope != null) { return cacheScope.GetCacheEntries(names); } return new CacheEntry[names.Length]; } /// <summary> /// This method get a result from the cache if every target is cached. /// If any of the target are not present in the cache null is returned. This method is not thread safe. /// </summary> internal BuildResult GetCachedBuildResult(BuildRequest buildRequest, out ArrayList actuallyBuiltTargets) { actuallyBuiltTargets = null; if (!buildRequest.UseResultsCache) { return null; } // Retrieve list of scopes by this name string projectName = buildRequest.ProjectToBuild == null ? buildRequest.ProjectFileName : buildRequest.ProjectToBuild.FullFileName; // If the list exists search for matching scope properties otherwise create the list CacheScope cacheScope = GetCacheScopeIfExists(projectName, buildRequest.GlobalProperties, buildRequest.ToolsetVersion, CacheContentType.BuildResults); // If there is no cache entry for this project return null if (cacheScope == null) { return null; } return cacheScope.GetCachedBuildResult(buildRequest, out actuallyBuiltTargets); } /// <summary> /// Clear a particular scope /// </summary> /// <param name="projectName"></param> /// <param name="buildPropertyGroup"></param> /// <param name="toolsVersion"></param> internal void ClearCacheScope(string projectName, BuildPropertyGroup buildPropertyGroup, string toolsVersion, CacheContentType cacheContentType) { // Retrieve list of scopes by this name if (cacheContents[(int)cacheContentType].ContainsKey(projectName)) { List<CacheScope> scopesByName = (List<CacheScope>)cacheContents[(int)cacheContentType][projectName]; // If the list exists search for matching scope properties otherwise create the list if (scopesByName != null) { // If the version is not specified default to the engine version if (toolsVersion == null) { toolsVersion = defaultToolsVersion; } lock (cacheManagerLock) { for (int i = 0; i < scopesByName.Count; i++) { if (scopesByName[i].ScopeProperties.IsEquivalent(buildPropertyGroup) && (String.Equals(toolsVersion, scopesByName[i].ScopeToolsVersion, StringComparison.OrdinalIgnoreCase))) { scopesByName.RemoveAt(i); break; } } } } } } /// <summary> /// Clears the whole contents of the cache. /// </summary> internal void ClearCache() { // Abandon the old cache contents for (int i = 0; i < (int)CacheContentType.LastContentTypeIndex + 1; i++) { cacheContents[i] = new Hashtable(StringComparer.OrdinalIgnoreCase); } } #endregion #region Data // Array of cache contents per namespace private Hashtable[] cacheContents; // Lock object for the cache manager private object cacheManagerLock = new object(); // The default toolset version private string defaultToolsVersion; #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace SharePointAppSampleWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Web; using System.Web.UI.WebControls; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Framework.Text; using Subtext.Framework.Tracking; using Subtext.Web.Admin.Pages; using Subtext.Web.Admin.WebUI; using Subtext.Web.Controls; using Subtext.Web.Properties; using Subtext.Web.UI.Controls; namespace Subtext.Web.Admin.UserControls { public partial class EntryEditor : BaseControl { private const string CategoryTypeViewStateKey = "CategoryType"; int? _postId; /// <summary> /// Gets or sets the type of the entry. /// </summary> /// <value>The type of the entry.</value> public PostType EntryType { get { if(ViewState["PostType"] != null) { return (PostType)ViewState["PostType"]; } return PostType.None; } set { ViewState["PostType"] = value; } } public int? PostId { get { if(_postId == null) { string postIdText = Request.QueryString["PostId"]; int postId; if(int.TryParse(postIdText, out postId)) { _postId = postId; } } return _postId; } } public CategoryType CategoryType { get { if(ViewState[CategoryTypeViewStateKey] != null) { return (CategoryType)ViewState[CategoryTypeViewStateKey]; } throw new InvalidOperationException(Resources.InvalidOperation_CategoryTypeNotSet); } set { ViewState[CategoryTypeViewStateKey] = value; } } //This is true if we came from a pencil edit link while viewing the post //from outside the admin tool. private bool ReturnToOriginalPost { get { return (Request.QueryString["return-to-post"] == "true"); } } protected override void OnLoad(EventArgs e) { if(!IsPostBack) { BindCategoryList(); SetEditorMode(); if(PostId != null) { BindPostEdit(); } else { BindPostCreate(); } } base.OnLoad(e); } private void BindCategoryList() { cklCategories.DataSource = Links.GetCategories(CategoryType, ActiveFilter.None); cklCategories.DataValueField = "Id"; cklCategories.DataTextField = "Title"; cklCategories.DataBind(); } private void SetConfirmation() { var confirmPage = (ConfirmationPage)Page; confirmPage.IsInEdit = true; confirmPage.Message = Resources.Message_YouWillLoseUnsavedContent; lkbPost.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); lkUpdateCategories.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); lkbCancel.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); } private void BindPostCreate() { txbTitle.Text = string.Empty; richTextEditor.Text = string.Empty; SetConfirmation(); SetDefaultPublishOptions(); PopulateMimeTypeDropDown(); } private void SetDefaultPublishOptions() { chkMainSyndication.Checked = true; ckbPublished.Checked = true; chkDisplayHomePage.Checked = true; chkComments.Checked = Config.CurrentBlog.CommentsEnabled; } private void BindPostEdit() { Debug.Assert(PostId != null, "PostId Should not be null when we call this"); SetConfirmation(); Entry entry = GetEntryForEditing(PostId.Value); if(entry == null) { ReturnToOrigin(null); return; } txbTitle.Text = entry.Title; if(!NullValue.IsNull(entry.DateSyndicated) && entry.DateSyndicated > Config.CurrentBlog.TimeZone.Now) { txtPostDate.Text = entry.DateSyndicated.ToString(CultureInfo.CurrentCulture); } VirtualPath entryUrl = Url.EntryUrl(entry); if (entryUrl != null) { hlEntryLink.NavigateUrl = entryUrl; hlEntryLink.Text = entryUrl.ToFullyQualifiedUrl(Config.CurrentBlog).ToString(); hlEntryLink.Attributes.Add("title", "view: " + entry.Title); } else hlEntryLink.Text = "This post has not been published yet, so it doesn't have an URL"; PopulateMimeTypeDropDown(); //Enclosures if(entry.Enclosure != null) { Enclosure.Collapsed = false; txbEnclosureTitle.Text = entry.Enclosure.Title; txbEnclosureUrl.Text = entry.Enclosure.Url; txbEnclosureSize.Text = entry.Enclosure.Size.ToString(); if(ddlMimeType.Items.FindByText(entry.Enclosure.MimeType) != null) { ddlMimeType.SelectedValue = entry.Enclosure.MimeType; } else { ddlMimeType.SelectedValue = "other"; txbEnclosureOtherMimetype.Text = entry.Enclosure.MimeType; } ddlAddToFeed.SelectedValue = entry.Enclosure.AddToFeed.ToString().ToLower(); ddlDisplayOnPost.SelectedValue = entry.Enclosure.ShowWithPost.ToString().ToLower(); } chkComments.Checked = entry.AllowComments; chkCommentsClosed.Checked = entry.CommentingClosed; SetCommentControls(); if(entry.CommentingClosedByAge) { chkCommentsClosed.Enabled = false; } chkDisplayHomePage.Checked = entry.DisplayOnHomePage; chkMainSyndication.Checked = entry.IncludeInMainSyndication; chkSyndicateDescriptionOnly.Checked = entry.SyndicateDescriptionOnly; chkIsAggregated.Checked = entry.IsAggregated; // Advanced Options txbEntryName.Text = entry.EntryName; txbExcerpt.Text = entry.Description; SetEditorText(entry.Body); ckbPublished.Checked = entry.IsActive; BindCategoryList(); for(int i = 0; i < cklCategories.Items.Count; i++) { cklCategories.Items[i].Selected = false; } ICollection<Link> postCategories = Repository.GetLinkCollectionByPostId(PostId.Value); if(postCategories.Count > 0) { foreach(Link postCategory in postCategories) { ListItem categoryItem = cklCategories.Items.FindByValue(postCategory.CategoryId.ToString(CultureInfo.InvariantCulture)); if(categoryItem == null) { throw new InvalidOperationException( string.Format(Resources.EntryEditor_CouldNotFindCategoryInList, postCategory.CategoryId, cklCategories.Items.Count)); } categoryItem.Selected = true; } } SetEditorMode(); Advanced.Collapsed = !Preferences.AlwaysExpandAdvanced; var adminMasterPage = Page.Master as AdminPageTemplate; if(adminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, Resources.EntryEditor_EditingTitle, CategoryType == CategoryType.StoryCollection ? Resources.Label_Article : Resources.Label_Post, entry.Title); adminMasterPage.Title = title; } if(entry.HasEntryName) { Advanced.Collapsed = false; txbEntryName.Text = entry.EntryName; } } private void PopulateMimeTypeDropDown() { ddlMimeType.Items.Add(new ListItem(Resources.Label_Choose, "none")); foreach(string key in MimeTypesMapper.Mappings.List) { ddlMimeType.Items.Add(new ListItem(MimeTypesMapper.Mappings.List[key], MimeTypesMapper.Mappings.List[key])); } ddlMimeType.Items.Add(new ListItem(Resources.Label_Other, "other")); } private void SetCommentControls() { if(!Blog.CommentsEnabled) { chkComments.Enabled = false; chkCommentsClosed.Enabled = false; } } public void EditNewEntry() { SetConfirmation(); } private void ReturnToOrigin(string message) { if(ReturnToOriginalPost && PostId != null) { // We came from outside the post, let's go there. Entry updatedEntry = Repository.GetEntry(PostId.Value, true /*activeOnly*/, false /*includeCategories*/); if(updatedEntry != null) { Response.Redirect(Url.EntryUrl(updatedEntry)); } } else { string url = "Default.aspx"; if(!String.IsNullOrEmpty(message)) { url += "?message=" + HttpUtility.UrlEncode(message); } Response.Redirect(url); } } private void UpdatePost() { DateTime postDate = NullValue.NullDateTime; vCustomPostDate.IsValid = string.IsNullOrEmpty(txtPostDate.Text) || DateTime.TryParse(txtPostDate.Text, out postDate); EnableEnclosureValidation(EnclosureEnabled()); if(Page.IsValid) { string successMessage = Constants.RES_SUCCESSNEW; try { Entry entry; if(PostId == null) { ValidateEntryTypeIsNotNone(EntryType); entry = new Entry(EntryType); } else { entry = GetEntryForEditing(PostId.Value); if(entry.PostType != EntryType) { EntryType = entry.PostType; } } entry.Title = txbTitle.Text; entry.Body = richTextEditor.Xhtml; entry.Author = Config.CurrentBlog.Author; entry.Email = Config.CurrentBlog.Email; entry.BlogId = Config.CurrentBlog.Id; //Enclosure int enclosureId = 0; if(entry.Enclosure != null) { enclosureId = entry.Enclosure.Id; } if(EnclosureEnabled()) { if(entry.Enclosure == null) { entry.Enclosure = new Enclosure(); } Enclosure enc = entry.Enclosure; enc.Title = txbEnclosureTitle.Text; enc.Url = txbEnclosureUrl.Text; enc.MimeType = ddlMimeType.SelectedValue.Equals("other") ? txbEnclosureOtherMimetype.Text : ddlMimeType.SelectedValue; long size; Int64.TryParse(txbEnclosureSize.Text, out size); enc.Size = size; enc.AddToFeed = Boolean.Parse(ddlAddToFeed.SelectedValue); enc.ShowWithPost = Boolean.Parse(ddlDisplayOnPost.SelectedValue); } else { entry.Enclosure = null; } // Advanced options entry.IsActive = ckbPublished.Checked; entry.AllowComments = chkComments.Checked; entry.CommentingClosed = chkCommentsClosed.Checked; entry.DisplayOnHomePage = chkDisplayHomePage.Checked; entry.IncludeInMainSyndication = chkMainSyndication.Checked; entry.SyndicateDescriptionOnly = chkSyndicateDescriptionOnly.Checked; entry.IsAggregated = chkIsAggregated.Checked; entry.EntryName = txbEntryName.Text.NullIfEmpty(); entry.Description = txbExcerpt.Text.NullIfEmpty(); entry.Categories.Clear(); ReplaceSelectedCategoryNames(entry.Categories); if(!NullValue.IsNull(postDate)) { entry.DateSyndicated = postDate; } if(PostId != null) { successMessage = Constants.RES_SUCCESSEDIT; entry.DateModified = Config.CurrentBlog.TimeZone.Now; entry.Id = PostId.Value; var entryPublisher = SubtextContext.ServiceLocator.GetService<IEntryPublisher>(); entryPublisher.Publish(entry); if(entry.Enclosure == null && enclosureId != 0) { Enclosures.Delete(enclosureId); } else if(entry.Enclosure != null && entry.Enclosure.Id != 0) { Enclosures.Update(entry.Enclosure); } else if(entry.Enclosure != null && entry.Enclosure.Id == 0) { entry.Enclosure.EntryId = entry.Id; Enclosures.Create(entry.Enclosure); } UpdateCategories(); } else { var entryPublisher = SubtextContext.ServiceLocator.GetService<IEntryPublisher>(); _postId = entryPublisher.Publish(entry); NotificationServices.Run(entry, Blog, Url); if(entry.Enclosure != null) { entry.Enclosure.EntryId = PostId.Value; Enclosures.Create(entry.Enclosure); } UpdateCategories(); AddCommunityCredits(entry); } } catch(Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); successMessage = string.Empty; } //Prepared success messages were reset in the catch block because of some error on posting the content if(!String.IsNullOrEmpty(successMessage)) { ReturnToOrigin(successMessage); } } } [CoverageExclude] private static void ValidateEntryTypeIsNotNone(PostType entryType) { Debug.Assert(entryType != PostType.None, "The entry type is none. This should be impossible!"); } private bool EnclosureEnabled() { if(!String.IsNullOrEmpty(txbEnclosureUrl.Text)) { return true; } if(!String.IsNullOrEmpty(txbEnclosureTitle.Text)) { return true; } if(!String.IsNullOrEmpty(txbEnclosureSize.Text)) { return true; } return ddlMimeType.SelectedIndex > 0; } private void EnableEnclosureValidation(bool enabled) { valEncSizeRequired.Enabled = enabled; valEncUrlRequired.Enabled = enabled; valEncMimeTypeRequired.Enabled = enabled; valEncOtherMimetypeRequired.Enabled = enabled && ddlMimeType.SelectedValue.Equals("other"); } private void ReplaceSelectedCategoryNames(ICollection<string> sc) { sc.Clear(); foreach(ListItem item in cklCategories.Items) { if(item.Selected) { sc.Add(item.Text); } } } private string UpdateCategories() { try { if(PostId != null) { string successMessage = Constants.RES_SUCCESSCATEGORYUPDATE; var al = new List<int>(); foreach(ListItem item in cklCategories.Items) { if(item.Selected) { al.Add(int.Parse(item.Value)); } } Repository.SetEntryCategoryList(PostId.Value, al); return successMessage; } Messages.ShowError(Constants.RES_FAILURECATEGORYUPDATE + Resources.EntryEditor_ProblemEditingPostCategories); } catch(Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); } return null; } private void SetEditorMode() { if(CategoryType == CategoryType.StoryCollection) { chkDisplayHomePage.Visible = false; chkIsAggregated.Visible = false; chkMainSyndication.Visible = false; chkSyndicateDescriptionOnly.Visible = false; } } private void SetEditorText(string bodyValue) { richTextEditor.Text = bodyValue; } override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { lkbPost.Click += OnUpdatePostClick; lkUpdateCategories.Click += OnUpdateCategoriesClick; lkbCancel.Click += OnCancelClick; } private void OnCancelClick(object sender, EventArgs e) { if(PostId != null && ReturnToOriginalPost) { // We came from outside the post, let's go there. Entry updatedEntry = Repository.GetEntry(PostId.Value, true /* activeOnly */, false /* includeCategories */); if(updatedEntry != null) { Response.Redirect(Url.EntryUrl(updatedEntry)); return; } } ReturnToOrigin(null); } private void OnUpdatePostClick(object sender, EventArgs e) { UpdatePost(); } private void OnUpdateCategoriesClick(object sender, EventArgs e) { string successMessage = UpdateCategories(); if(successMessage != null) { ReturnToOrigin(successMessage); } } protected void richTextEditor_Error(object sender, RichTextEditorErrorEventArgs e) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", e.Exception.Message)); } private void AddCommunityCredits(Entry entry) { try { CommunityCreditNotification.AddCommunityCredits(entry, Url, Blog); } catch(CommunityCreditNotificationException ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Resources.EntryEditor_ErrorSendingToCommunityCredits, ex.Message)); } catch(Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Resources.EntryEditor_ErrorSendingToCommunityCredits, ex.Message)); } } private Entry GetEntryForEditing(int id) { var entry = Repository.GetEntry(id, false /*activeOnly*/, false /*includeCategories*/); entry.Blog = Blog; return entry; } } }
using System; using System.CodeDom; using System.Collections.Generic; namespace IronAHK.Scripting { partial class Parser { #region Wrappers CodeExpressionStatement[] ParseMultiExpression(string code) { var tokens = SplitTokens(code); #region Date/time int n = tokens.Count - 2; if (tokens.Count > 1 && ((string)tokens[n]).Length > 0 && ((string)tokens[n])[0] == Multicast) { string arg = ((string)tokens[n + 1]).ToUpperInvariant().Trim(); arg = arg.Length == 1 ? arg : arg.TrimEnd('S'); switch (arg) { case "S": case "SECOND": case "M": case "MINUTE": case "H": case "HOUR": case "D": case "DAY": return new[] { new CodeExpressionStatement(ParseDateExpression(code)) }; } } #endregion var result = ParseMultiExpression(tokens.ToArray()); var statements = new CodeExpressionStatement[result.Length]; for (int i = 0; i < result.Length; i++) statements[i] = new CodeExpressionStatement(result[i]); return statements; } CodeExpression ParseSingleExpression(string code) { var tokens = SplitTokens(code); return ParseExpression(tokens); } CodeExpression[] ParseMultiExpression(object[] parts) { var expr = new List<CodeExpression>(); var sub = new List<object>(); for (int i = 0; i < parts.Length; i++) { if (!(parts[i] is string) || ((string)parts[i]).Length == 0) { sub.Add(parts[i]); continue; } int next = Set(parts, i); if (next > 0) { for (; i < next; i++) sub.Add(parts[i]); i--; continue; } var check = (string)parts[i]; if (check.Length == 1 && check[0] == Multicast && sub.Count != 0) { expr.Add(ParseExpression(sub)); sub.Clear(); continue; } else sub.Add(parts[i]); } if (sub.Count != 0) expr.Add(ParseExpression(sub)); return expr.ToArray(); } #endregion #region Parser CodeExpression ParseExpression(List<object> parts) { RemoveExcessParentheses(parts); #region Scanner start: bool rescan = false; for (int i = 0; i < parts.Count; i++) { if (parts[i] is string) { var part = (string)parts[i]; object result; #region Parentheses if (part[0] == ParenOpen) { int n = i + 1; var paren = Dissect(parts, n, Set(parts, i)); parts.RemoveAt(n); n -= 2; bool call = n > -1 && parts[n] is CodeExpression && !(parts[n] is CodePrimitiveExpression); if (call && parts[n] is CodeMethodInvokeExpression && ((CodeMethodInvokeExpression)parts[n]).Parameters[0] is CodeFieldReferenceExpression) call = false; if (call) { var invoke = (CodeMethodInvokeExpression)InternalMethods.Invoke; invoke.Parameters.Add((CodeExpression)parts[n]); if (paren.Count != 0) { var passed = ParseMultiExpression(paren.ToArray()); invoke.Parameters.AddRange(passed); } parts[i] = invoke; parts.RemoveAt(n); } else { if (paren.Count == 0) parts.RemoveAt(i); else parts[i] = ParseExpression(paren); } } else if (part[0] == ParenClose) rescan = true; #endregion #region Strings else if (part.Length > 1 && part[0] == StringBound && part[part.Length - 1] == StringBound) parts[i] = new CodePrimitiveExpression(EscapedString(part.Substring(1, part.Length - 2), false)); #endregion #region Numerics else if (IsPrimativeObject(part, out result)) parts[i] = new CodePrimitiveExpression(result); #endregion #region Variables else if (IsIdentifier(part, true) && !IsKeyword(part)) { var low = part.ToLowerInvariant(); if (libProperties.ContainsKey(low)) parts[i] = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(bcl), libProperties[low]); else parts[i] = VarIdOrConstant(part); } #endregion #region JSON else if (part.Length == 1 && part[0] == BlockOpen) { int n = i + 1; var paren = Dissect(parts, n, Set(parts, i)); var invoke = (CodeMethodInvokeExpression)InternalMethods.Dictionary; CodePrimitiveExpression[] keys; CodeExpression[] values; ParseObject(paren, out keys, out values); invoke.Parameters.Add(new CodeArrayCreateExpression(typeof(string), keys)); invoke.Parameters.Add(new CodeArrayCreateExpression(typeof(object), values)); parts[i] = invoke; parts.RemoveAt(n); i--; } else if (part.Length == 1 && part[0] == ArrayOpen) { int n = i + 1; var paren = Dissect(parts, n, Set(parts, i)); parts.RemoveAt(n); if (i > 0 && parts[i - 1] is CodeExpression) { var invoke = (CodeMethodInvokeExpression)InternalMethods.Index; n = i - 1; invoke.Parameters.Add((CodeExpression)parts[n]); var index = ParseMultiExpression(paren.ToArray()); if (index.Length > 1) throw new ParseException("Cannot have multipart expression in index."); else if (index.Length == 0) { var extend = (CodeMethodInvokeExpression)InternalMethods.ExtendArray; var sub = new List<object>(1); sub.Add(parts[n]); extend.Parameters.Add(ParseExpression(sub)); invoke = extend; } else invoke.Parameters.Add(index[0]); parts[i] = invoke; parts.RemoveAt(n); i--; } else { var array = new CodeArrayCreateExpression(typeof(object[]), ParseMultiExpression(paren.ToArray())); parts[i] = array; } } #endregion #region Invokes else if (part.Length > 1 && part[part.Length - 1] == ParenOpen) { string name = part.Substring(0, part.Length - 1); bool dynamic = false; if (!IsIdentifier(name)) { if (IsDynamicReference(name)) dynamic = true; else throw new ParseException("Invalid function name"); } else CheckPersistent(name); int n = i + 1; var paren = Dissect(parts, n, Set(parts, i)); parts.RemoveAt(n); CodeMethodInvokeExpression invoke; if (dynamic) { invoke = (CodeMethodInvokeExpression)InternalMethods.FunctionCall; invoke.Parameters.Add(VarIdExpand(name)); } else invoke = LocalMethodInvoke(name); if (paren.Count != 0) { var passed = ParseMultiExpression(paren.ToArray()); invoke.Parameters.AddRange(passed); } parts[i] = invoke; invokes.Add(invoke); } #endregion #region Assignments else if (IsAssignOp(part) || IsImplicitAssignment(parts, i)) { int n = i - 1; if (i > 0 && IsJsonObject(parts[n])) { } else if (n < 0 || !IsVarReference(parts[n])) { if (LaxExpressions) { if (parts[n] is CodePrimitiveExpression && ((CodePrimitiveExpression)parts[n]).Value is decimal) parts[n] = VarId(((decimal)((CodePrimitiveExpression)parts[n]).Value).ToString()); } else throw new ParseException("Can only assign to a variable"); } // (x += y) => (x = x + y) parts[i] = CodeBinaryOperatorType.Assign; if (part[0] != AssignPre && part.Length != 1) { parts.Insert(++i, ParenOpen.ToString()); parts.Insert(++i, parts[i - 3]); if (part.Length > 1) { parts.Insert(++i, OperatorFromString(part.Substring(0, part.Length - 1))); parts.Insert(++i, ParenOpen.ToString()); parts.Add(ParenClose.ToString()); } parts.Add(ParenClose.ToString()); } } #endregion #region Multiple statements else if (part.Length == 1 && part[0] == Multicast) { if (!LaxExpressions) throw new ParseException("Nested multipart expression not allowed."); // implement as: + Dummy(expr..) int z = i + 1, l = parts.Count - z; var sub = new List<object>(l); for (; z < parts.Count; z++) sub.Add(parts[z]); parts.RemoveRange(i, parts.Count - i); var invoke = (CodeMethodInvokeExpression)InternalMethods.OperateZero; invoke.Parameters.Add(ParseExpression(sub)); parts.Add(Script.Operator.Add); parts.Add(invoke); } #endregion #region Binary operators else { var ops = OperatorFromString(part); #region Increment/decrement if (ops == Script.Operator.Increment || ops == Script.Operator.Decrement) { int z = -1, x = i - 1, y = i + 1; int d = ops == Script.Operator.Increment ? 1 : -1; CodeMethodInvokeExpression shadow = null; // UNDONE: use generic approach to ++/-- for all types of operands? if (x > -1 && parts[x] is CodeMethodInvokeExpression) { var sub = new List<object>(5); sub.Add(parts[x]); sub.Add(CodeBinaryOperatorType.Assign); sub.Add(parts[x]); sub.Add(Script.Operator.Add); sub.Add(d); parts.RemoveAt(i); parts[x] = ParseExpression(sub); i = x; continue; } #region Compounding increment/decrement operators if (LaxExpressions) { while (y < parts.Count) { Script.Operator nextOps = Script.Operator.ValueEquality; if (parts[y] is Script.Operator) nextOps = (Script.Operator)parts[y]; else if (parts[y] is string) { try { nextOps = OperatorFromString((string)parts[y]); } catch { break; } } else break; if (nextOps == Script.Operator.Increment) d++; else if (nextOps == Script.Operator.Decrement) d--; else break; parts.RemoveAt(y); } } #endregion if (x > -1 && (IsVarReference(parts[x]) || parts[x] is CodePropertyReferenceExpression)) z = x; if (y < parts.Count && parts[y] is string && !IsOperator((string)parts[y])) { if (z != -1) { if (LaxExpressions) { parts.Insert(y, Script.Operator.Concat); z = x; } else throw new ParseException("Cannot use both prefix and postfix operators on the same variable"); } if (z == -1) z = y; if (LaxExpressions) { if (parts[z] is string && ((string)parts[z]).Length == 1 && ((string)parts[z])[0] == ParenOpen) { var zx = new[] { z + 1, z + 2 }; if (zx[1] < parts.Count && parts[zx[1]] is string && ((string)parts[zx[1]]).Length == 1 && ((string)parts[zx[1]])[0] == ParenClose && (parts[zx[0]] is string && IsDynamicReference((string)parts[zx[0]]) || IsVarReference(parts[zx[0]]))) { parts.RemoveAt(zx[1]); parts.RemoveAt(z); } else { parts.RemoveAt(i); i--; continue; } } } } if (z == -1) { if (LaxExpressions) { if ((x > 0 && (parts[x] is CodeBinaryOperatorExpression || parts[x] is CodeMethodInvokeExpression || parts[x] is CodePrimitiveExpression)) || (y < parts.Count && (parts[y] is string && !IsOperator(parts[y] as string) || parts[y] is Script.Operator))) { parts.RemoveAt(i); i--; continue; } } else throw new ParseException("Neither left or right hand side of operator is a variable"); } if (parts[z] is string && ((string)parts[z]).Length > 0 && ((string)parts[z])[0] == StringBound) { parts.RemoveAt(Math.Max(i, z)); parts.RemoveAt(Math.Min(i, z)); continue; } if (LaxExpressions) { int w = z + (z == x ? 2 : 1); if (w < parts.Count && (parts[w] is string && IsAssignOp((string)parts[w]) || IsVarAssignment(parts[w]))) { int l = parts.Count - w; var sub = new List<object>(l + 1); sub.Add(parts[z]); for (int wx = w; wx < parts.Count; wx++) sub.Add(parts[wx]); shadow = (CodeMethodInvokeExpression)InternalMethods.OperateZero; shadow.Parameters.Add(ParseExpression(sub)); parts.RemoveRange(w, l); } } var list = new List<object>(9); list.Add(parts[z]); list.Add(new string(new[] { Add, Equal })); list.Add(new CodePrimitiveExpression(d)); if (shadow != null) { list.Add(Script.Operator.Add); list.Add(shadow); } if (z < i) // postfix, so adjust { list.Insert(0, ParenOpen.ToString()); list.Add(ParenClose.ToString()); list.Add(d > 0 ? Script.Operator.Minus : Script.Operator.Add); list.Add(new CodePrimitiveExpression(d)); } x = Math.Min(i, z); y = Math.Max(i, z); parts[x] = ParseExpression(list); parts.RemoveAt(y); i = x; } #endregion else { #region Dereference if (part.Length == 1 && part[0] == Dereference) { bool deref = false; if (i == 0) deref = true; else { int x = i - 1; deref = parts[x] is Script.Operator || IsVarAssignment(parts[x]) || (parts[x] is string && ((string)parts[x]).Length == 1 && ((string)parts[x])[0] == '('); } if (deref) { int y = i + 1; if (y < parts.Count && (IsVarReference(parts[y]) || (parts[y] is string && IsIdentifier((string)parts[y]) && !IsKeyword((string)parts[y])))) ops = Script.Operator.Dereference; } } #endregion parts[i] = ops; } } #endregion } } if (rescan) goto start; #endregion #region Operators #region Unary (precedent) for (int i = 1; i < parts.Count; i++) { if (parts[i] is Script.Operator && (parts[i - 1] is Script.Operator || parts[i - 1] as CodeBinaryOperatorType? == CodeBinaryOperatorType.Assign || IsVarAssignment(parts[i - 1])) && IsUnaryOperator((Script.Operator)parts[i])) { int n = i + 1, m = n + 1; int u = n; while (u < parts.Count && parts[u] is Script.Operator && IsUnaryOperator((Script.Operator)parts[u])) u++; if (u == parts.Count) { if (LaxExpressions) { u--; while (parts[u] is Script.Operator && ((Script.Operator)parts[u] == Script.Operator.Add || (Script.Operator)parts[u] == Script.Operator.Subtract)) parts.RemoveAt(u--); if (u + 1 < n) { i = u; continue; } } throw new ParseException("Compounding unary operator with no operand"); } if (u > n) { var sub = new List<object>(++u - n); for (int x = n; x < u; x++) sub.Add(parts[x]); parts.RemoveRange(n, u - n); parts.Insert(n, ParseExpression(sub)); } if (m + 1 < parts.Count && IsVarReference(parts[n]) && IsVarAssignment(parts[m])) MergeAssignmentAt(parts, i + 2); if (m > parts.Count) throw new ParseException("Unary operator without operand"); var op = (Script.Operator)parts[i]; if (parts[n] is CodePrimitiveExpression && op == Script.Operator.Subtract) { var parent = ((CodePrimitiveExpression)parts[n]); if (parent.Value is int) parent.Value = -(int)parent.Value; else if (parent.Value is decimal) parent.Value = -(decimal)parent.Value; else if (parent.Value is double) parent.Value = -(double)parent.Value; else if (parent.Value is string) parent.Value = string.Concat(Minus.ToString(), (string)parent.Value); else throw new ArgumentOutOfRangeException(); parts.RemoveAt(i); } else if (op == Script.Operator.Add) { parts.RemoveAt(i); } else { var invoke = (CodeMethodInvokeExpression)InternalMethods.OperateUnary; invoke.Parameters.Add(OperatorAsFieldReference(op)); if (LaxExpressions) { if (!(IsVarReference(parts[n]) || IsVarAssignment(parts[n]))) { invoke.Parameters.Add(new CodePrimitiveExpression(null)); goto next; } } invoke.Parameters.Add(VarMixedExpr(parts[n])); next: parts[i] = invoke; parts.RemoveAt(n); } } } #endregion #region Generic bool scan = true; int level = -1; while (scan) { scan = false; for (int i = 0; i < parts.Count; i++) { if (parts[i] is Script.Operator && (Script.Operator)parts[i] != Script.Operator.Assign) { scan = true; var op = (Script.Operator)parts[i]; if (OperatorPrecedence(op) < level) continue; int x = i - 1, y = i + 1; var invoke = new CodeMethodInvokeExpression(); if (i + 3 < parts.Count && IsVarReference(parts[i + 1]) && parts[i + 2] as CodeBinaryOperatorType? == CodeBinaryOperatorType.Assign) MergeAssignmentAt(parts, i + 2); #region Ternary if (op == Script.Operator.TernaryA) { if (x < 0) { if (LaxExpressions) return new CodePrimitiveExpression(null); else throw new ParseException("Ternary with no condition."); } var eval = (CodeMethodInvokeExpression)InternalMethods.IfElse; eval.Parameters.Add(VarMixedExpr(parts[x])); var ternary = new CodeTernaryOperatorExpression { Condition = eval }; int depth = 1, max = parts.Count - i, start = i; var branch = new[] { new List<object>(max), new List<object>(max) }; for (i++; i < parts.Count; i++) { switch (parts[i] as Script.Operator?) { case Script.Operator.TernaryA: depth++; break; case Script.Operator.TernaryB: depth--; break; } if (depth == 0) { for (int n = i + 1; n < parts.Count; n++) branch[1].Add(parts[n]); break; } else branch[0].Add(parts[i]); } if (branch[0].Count == 0) throw new ParseException("Ternary operator must have at least one branch"); if (branch[1].Count == 0) branch[1].Add(new CodePrimitiveExpression(null)); ternary.TrueBranch = ParseExpression(branch[0]); ternary.FalseBranch = ParseExpression(branch[1]); parts[x] = ternary; parts.Remove(y); parts.RemoveRange(start, parts.Count - start); } else if (op == Script.Operator.NullAssign) { if (x < 0) throw new ParseException("Nullable assignment with no condition."); int n = i + 1; if (n >= parts.Count) throw new ParseException("Nullable assignment with no right-hand operator"); var result = InternalVariable; var left = new CodeBinaryOperatorExpression(result, CodeBinaryOperatorType.Assign, VarMixedExpr(parts[x])); var eval = (CodeMethodInvokeExpression)InternalMethods.IfElse; eval.Parameters.Add(left); var ternary = new CodeTernaryOperatorExpression { Condition = eval, TrueBranch = result }; var right = new List<object>(); while (n < parts.Count) right.Add(parts[n++]); ternary.FalseBranch = ParseExpression(right); parts[x] = ternary; parts.RemoveRange(i, parts.Count - i); } #endregion #region Unary else if (x == -1) { int z = y + 1; if (op == Script.Operator.LogicalNotEx && IsVarReference(parts[y]) && z < parts.Count) MergeAssignmentAt(parts, z); if (LaxExpressions) { if (y > parts.Count - 1) return new CodePrimitiveExpression(null); } invoke.Method = (CodeMethodReferenceExpression)InternalMethods.OperateUnary; invoke.Parameters.Add(OperatorAsFieldReference(op)); invoke.Parameters.Add(VarMixedExpr(parts[y])); parts[i] = invoke; parts.RemoveAt(y); } #endregion #region Binary else { if (op == Script.Operator.BooleanAnd || op == Script.Operator.BooleanOr) { var boolean = new CodeBinaryOperatorExpression(); boolean.Operator = op == Script.Operator.BooleanAnd ? CodeBinaryOperatorType.BooleanAnd : CodeBinaryOperatorType.BooleanOr; var iftest = (CodeMethodInvokeExpression)InternalMethods.IfElse; iftest.Parameters.Add(VarMixedExpr(parts[x])); boolean.Left = iftest; iftest = (CodeMethodInvokeExpression)InternalMethods.IfElse; var next = parts[y] as Script.Operator?; if (next == Script.Operator.BooleanAnd || next == Script.Operator.BooleanOr) { if (LaxExpressions) iftest.Parameters.Add(new CodePrimitiveExpression(false)); else throw new ParseException(ExInvalidExpression); } else { iftest.Parameters.Add(VarMixedExpr(parts[y])); parts.RemoveAt(y); } boolean.Right = iftest; parts[x] = boolean; } else { if (LaxExpressions) { if (parts[x] is Script.Operator && (Script.Operator)parts[x] == Script.Operator.TernaryA) { parts[x] = new CodePrimitiveExpression(null); goto next; } if (y > parts.Count - 1) return new CodePrimitiveExpression(null); } else throw new ParseException(ExInvalidExpression); invoke.Method = (CodeMethodReferenceExpression)InternalMethods.Operate; invoke.Parameters.Add(OperatorAsFieldReference(op)); if (LaxExpressions && parts[i] is Script.Operator && (Script.Operator)parts[i] == Script.Operator.Concat && parts[x] as CodeBinaryOperatorType? == CodeBinaryOperatorType.Assign) invoke.Parameters.Add(new CodePrimitiveExpression(string.Empty)); else invoke.Parameters.Add(VarMixedExpr(parts[x])); invoke.Parameters.Add(VarMixedExpr(parts[y])); parts[x] = invoke; next: parts.RemoveAt(y); } parts.RemoveAt(i); } #endregion i--; } else if (parts[i] as CodeBinaryOperatorType? != CodeBinaryOperatorType.Assign) { var x = i - 1; if (x > 0 && !(parts[x] is Script.Operator || parts[x] is CodeBinaryOperatorType)) { parts.Insert(i, Script.Operator.Concat); i--; continue; } } } level--; } #endregion #endregion #region Assignments for (int i = parts.Count - 1; i > 0; i--) MergeAssignmentAt(parts, i); #endregion #region Result if (parts.Count > 1) { for (int i = 0; i < parts.Count; i++) { bool typed = false; if (LaxExpressions) typed = IsVarAssignment(parts[i]) || IsVarReference(parts[i]); if (!(typed || parts[i] is CodeMethodInvokeExpression || parts[i] is CodePrimitiveExpression || parts[i] is CodeTernaryOperatorExpression || parts[i] is CodeBinaryOperatorExpression || parts[i] is CodePropertyReferenceExpression)) throw new ArgumentOutOfRangeException(); if (i % 2 == 1) parts.Insert(i, Script.Operator.Concat); } var concat = ParseExpression(parts); parts.Clear(); parts.Add(concat); } if (parts.Count != 1) throw new ArgumentOutOfRangeException(); if (IsVarAssignment(parts[0])) return (CodeBinaryOperatorExpression)parts[0]; else return (CodeExpression)parts[0]; #endregion } #endregion } }
/* * Copyright 2014 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace Splunk.Client.AcceptanceTests { using Splunk.Client; using Splunk.Client.Helpers; using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; /// <summary> /// Tests the Index class /// </summary> public class IndexTest { /// <summary> /// Tests the basic getters and setters of index /// </summary> [Trait("acceptance-test", "Splunk.Client.Index")] [MockContext] [Fact] public async Task IndexCollection() { string indexName = string.Format("delete-me-{0}", Guid.NewGuid()); using (var service = await SdkHelper.CreateService()) { IndexCollection indexes = service.Indexes; Index testIndex = await indexes.CreateAsync(indexName); //// TODO: Verify testIndex await testIndex.GetAsync(); //// TODO: Reverify testIndex await indexes.GetAllAsync(); Assert.NotNull(indexes.SingleOrDefault(x => x.Title == testIndex.Title)); foreach (Index index in indexes) { int dummyInt; string dummyString; bool dummyBool; DateTime dummyTime; dummyBool = index.AssureUTF8; dummyInt = index.BloomFilterTotalSizeKB; dummyString = index.ColdPath; dummyString = index.ColdPathExpanded; dummyString = index.ColdToFrozenDir; dummyString = index.ColdToFrozenScript; dummyBool = index.CompressRawData; long size = index.CurrentDBSizeMB; dummyString = index.DefaultDatabase; dummyBool = index.EnableRealTimeSearch; dummyInt = index.FrozenTimePeriodInSecs; dummyString = index.HomePath; dummyString = index.HomePathExpanded; dummyString = index.IndexThreads; long time = index.LastInitTime; dummyString = index.MaxBloomBackfillBucketAge; dummyInt = index.MaxConcurrentOptimizes; dummyString = index.MaxDataSize; dummyInt = index.MaxHotBuckets; dummyInt = index.MaxHotIdleSecs; dummyInt = index.MaxHotSpanSecs; dummyInt = index.MaxMemMB; dummyInt = index.MaxMetaEntries; dummyInt = index.MaxRunningProcessGroups; dummyTime = index.MaxTime; dummyInt = index.MaxTotalDataSizeMB; dummyInt = index.MaxWarmDBCount; dummyString = index.MemPoolMB; dummyString = index.MinRawFileSyncSecs; dummyTime = index.MinTime; dummyInt = index.NumBloomFilters; dummyInt = index.NumHotBuckets; dummyInt = index.NumWarmBuckets; dummyInt = index.PartialServiceMetaPeriod; dummyInt = index.QuarantineFutureSecs; dummyInt = index.QuarantinePastSecs; dummyInt = index.RawChunkSizeBytes; dummyInt = index.RotatePeriodInSecs; dummyInt = index.ServiceMetaPeriod; dummyString = index.SuppressBannerList; bool sync = index.Sync; dummyBool = index.SyncMeta; dummyString = index.ThawedPath; dummyString = index.ThawedPathExpanded; dummyInt = index.ThrottleCheckPeriod; long eventCount = index.TotalEventCount; dummyBool = index.Disabled; dummyBool = index.IsInternal; } for (int i = 0; i < indexes.Count; i++) { Index index = indexes[i]; int dummyInt; string dummyString; bool dummyBool; DateTime dummyTime; dummyBool = index.AssureUTF8; dummyInt = index.BloomFilterTotalSizeKB; dummyString = index.ColdPath; dummyString = index.ColdPathExpanded; dummyString = index.ColdToFrozenDir; dummyString = index.ColdToFrozenScript; dummyBool = index.CompressRawData; long size = index.CurrentDBSizeMB; dummyString = index.DefaultDatabase; dummyBool = index.EnableRealTimeSearch; dummyInt = index.FrozenTimePeriodInSecs; dummyString = index.HomePath; dummyString = index.HomePathExpanded; dummyString = index.IndexThreads; long time = index.LastInitTime; dummyString = index.MaxBloomBackfillBucketAge; dummyInt = index.MaxConcurrentOptimizes; dummyString = index.MaxDataSize; dummyInt = index.MaxHotBuckets; dummyInt = index.MaxHotIdleSecs; dummyInt = index.MaxHotSpanSecs; dummyInt = index.MaxMemMB; dummyInt = index.MaxMetaEntries; dummyInt = index.MaxRunningProcessGroups; dummyTime = index.MaxTime; dummyInt = index.MaxTotalDataSizeMB; dummyInt = index.MaxWarmDBCount; dummyString = index.MemPoolMB; dummyString = index.MinRawFileSyncSecs; dummyTime = index.MinTime; dummyInt = index.NumBloomFilters; dummyInt = index.NumHotBuckets; dummyInt = index.NumWarmBuckets; dummyInt = index.PartialServiceMetaPeriod; dummyInt = index.QuarantineFutureSecs; dummyInt = index.QuarantinePastSecs; dummyInt = index.RawChunkSizeBytes; dummyInt = index.RotatePeriodInSecs; dummyInt = index.ServiceMetaPeriod; dummyString = index.SuppressBannerList; bool sync = index.Sync; dummyBool = index.SyncMeta; dummyString = index.ThawedPath; dummyString = index.ThawedPathExpanded; dummyInt = index.ThrottleCheckPeriod; long eventCount = index.TotalEventCount; dummyBool = index.Disabled; dummyBool = index.IsInternal; } var attributes = GetIndexAttributes(testIndex); attributes.EnableOnlineBucketRepair = !testIndex.EnableOnlineBucketRepair; attributes.MaxBloomBackfillBucketAge = "20d"; attributes.FrozenTimePeriodInSecs = testIndex.FrozenTimePeriodInSecs + 1; attributes.MaxConcurrentOptimizes = testIndex.MaxConcurrentOptimizes + 1; attributes.MaxDataSize = "auto"; attributes.MaxHotBuckets = testIndex.MaxHotBuckets + 1; attributes.MaxHotIdleSecs = testIndex.MaxHotIdleSecs + 1; attributes.MaxMemMB = testIndex.MaxMemMB + 1; attributes.MaxMetaEntries = testIndex.MaxMetaEntries + 1; attributes.MaxTotalDataSizeMB = testIndex.MaxTotalDataSizeMB + 1; attributes.MaxWarmDBCount = testIndex.MaxWarmDBCount + 1; attributes.MinRawFileSyncSecs = "disable"; attributes.PartialServiceMetaPeriod = testIndex.PartialServiceMetaPeriod + 1; attributes.QuarantineFutureSecs = testIndex.QuarantineFutureSecs + 1; attributes.QuarantinePastSecs = testIndex.QuarantinePastSecs + 1; attributes.RawChunkSizeBytes = testIndex.RawChunkSizeBytes + 1; attributes.RotatePeriodInSecs = testIndex.RotatePeriodInSecs + 1; attributes.ServiceMetaPeriod = testIndex.ServiceMetaPeriod + 1; attributes.SyncMeta = !testIndex.SyncMeta; attributes.ThrottleCheckPeriod = testIndex.ThrottleCheckPeriod + 1; bool updatedSnapshot = await testIndex.UpdateAsync(attributes); Assert.True(updatedSnapshot); await testIndex.DisableAsync(); Assert.True(testIndex.Disabled); // Because the disable endpoint returns an updated snapshot await service.Server.RestartAsync(2 * 60 * 1000); // Because you can't re-enable an index without a restart await service.LogOnAsync(); testIndex = await service.Indexes.GetAsync(indexName); await testIndex.EnableAsync(); // Because the enable endpoint returns an updated snapshot Assert.False(testIndex.Disabled); await service.Server.RestartAsync(2 * 60 * 1000); await service.LogOnAsync(); await testIndex.RemoveAsync(); await Task.Delay(5000); await SdkHelper.ThrowsAsync<ResourceNotFoundException>(async () => { await testIndex.GetAsync(); }); testIndex = await indexes.GetOrNullAsync(indexName); Assert.Null(testIndex); } } /// <summary> /// Tests submitting and streaming events to an index given the indexAttributes argument /// and also removing all events from the index /// </summary> [Trait("acceptance-test", "Splunk.Client.Transmitter")] [MockContext] [Fact] public async Task Transmitter1() { string indexName = string.Format("delete-me-{0}", Guid.NewGuid()); using (var service = await SdkHelper.CreateService()) { Index index = await service.Indexes.RecreateAsync(indexName); Assert.False(index.Disabled); await Task.Delay(2000); // Submit event using TransmitterArgs const string Source = "splunk-sdk-tests"; const string SourceType = "splunk-sdk-test-event"; const string Host = "test-host"; var transmitterArgs = new TransmitterArgs { Host = Host, Source = Source, SourceType = SourceType, }; ITransmitter transmitter = service.Transmitter; SearchResult result; //// TODO: Check contentss result = await transmitter.SendAsync( MockContext.GetOrElse(string.Format("1, {0}, {1}, simple event", DateTime.Now, indexName)), indexName, transmitterArgs); Assert.NotNull(result); result = await transmitter.SendAsync( MockContext.GetOrElse(string.Format("2, {0}, {1}, simple event", DateTime.Now, indexName)), indexName, transmitterArgs); Assert.NotNull(result); using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 4096, leaveOpen: true)) { writer.WriteLine( MockContext.GetOrElse(string.Format("1, {0}, {1}, stream event", DateTime.Now, indexName))); writer.WriteLine( MockContext.GetOrElse(string.Format("2, {0}, {1}, stream event", DateTime.Now, indexName))); } stream.Seek(0, SeekOrigin.Begin); await transmitter.SendAsync(stream, indexName, transmitterArgs); } await index.PollForUpdatedEventCount(4); var search = string.Format( "search index={0} host={1} source={2} sourcetype={3}", indexName, Host, Source, SourceType); using (SearchResultStream stream = await service.SearchOneShotAsync(search)) { Assert.Equal(0, stream.FieldNames.Count); Assert.False(stream.IsFinal); Assert.Equal(0, stream.ReadCount); foreach (SearchResult record in stream) { var fieldNames = stream.FieldNames; Assert.Equal(14, fieldNames.Count); Assert.Equal(14, record.FieldNames.Count); Assert.Equal(fieldNames.AsEnumerable(), record.FieldNames.AsEnumerable()); var memberNames = record.GetDynamicMemberNames(); var intersection = fieldNames.Intersect(memberNames); Assert.Equal(memberNames, intersection); } Assert.Equal(14, stream.FieldNames.Count); Assert.Equal(4, stream.ReadCount); } } } /// <summary> /// Test submitting and streaming to a default index given the indexAttributes argument /// and also removing all events from the index /// </summary> [Trait("acceptance-test", "Splunk.Client.Transmitter")] [MockContext] [Fact] public async Task Transmitter2() { string indexName = "main"; using (var service = await SdkHelper.CreateService()) { Index index = await service.Indexes.GetAsync(indexName); long currentEventCount = index.TotalEventCount; Assert.NotNull(index); Transmitter transmitter = (Transmitter)service.Transmitter; IndexAttributes indexAttributes = GetIndexAttributes(index); Assert.NotNull(indexAttributes); // Submit event to default index using variable arguments await transmitter.SendAsync( MockContext.GetOrElse(string.Format("{0}, DefaultIndexArgs string event Hello World 1", DateTime.Now)), indexName); await transmitter.SendAsync( MockContext.GetOrElse(string.Format("{0}, DefaultIndexArgs string event Hello World 2", DateTime.Now)), indexName); await index.PollForUpdatedEventCount(currentEventCount + 2); currentEventCount += 2; using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 4096, leaveOpen: true)) { writer.WriteLine( MockContext.GetOrElse(string.Format("{0}, DefaultIndexArgs stream events 1", DateTime.Now))); writer.WriteLine( MockContext.GetOrElse(string.Format("{0}, DefaultIndexArgs stream events 2", DateTime.Now))); } stream.Seek(0, SeekOrigin.Begin); await transmitter.SendAsync(stream, indexName); } await index.PollForUpdatedEventCount(currentEventCount + 2); currentEventCount += 2; } } /// <summary> /// Gets old values from given index, skip saving paths and things we cannot write /// </summary> /// <param name="index">The Index</param> /// <returns>The argument getIndexProperties</returns> IndexAttributes GetIndexAttributes(Index index) { IndexAttributes indexAttributes = new IndexAttributes(); indexAttributes.FrozenTimePeriodInSecs = index.FrozenTimePeriodInSecs; indexAttributes.MaxConcurrentOptimizes = index.MaxConcurrentOptimizes; indexAttributes.MaxDataSize = index.MaxDataSize; indexAttributes.MaxHotBuckets = index.MaxHotBuckets; indexAttributes.MaxHotIdleSecs = index.MaxHotIdleSecs; indexAttributes.MaxHotSpanSecs = index.MaxHotSpanSecs; indexAttributes.MaxMemMB = index.MaxMemMB; indexAttributes.MaxMetaEntries = index.MaxMetaEntries; indexAttributes.MaxTotalDataSizeMB = index.MaxTotalDataSizeMB; indexAttributes.MaxWarmDBCount = index.MaxWarmDBCount; indexAttributes.MinRawFileSyncSecs = index.MinRawFileSyncSecs; indexAttributes.PartialServiceMetaPeriod = index.PartialServiceMetaPeriod; indexAttributes.QuarantineFutureSecs = index.QuarantineFutureSecs; indexAttributes.QuarantinePastSecs = index.QuarantinePastSecs; indexAttributes.RawChunkSizeBytes = index.RawChunkSizeBytes; indexAttributes.RotatePeriodInSecs = index.RotatePeriodInSecs; indexAttributes.ServiceMetaPeriod = index.ServiceMetaPeriod; indexAttributes.SyncMeta = index.SyncMeta; indexAttributes.ThrottleCheckPeriod = index.ThrottleCheckPeriod; return indexAttributes; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading; using NUnit.Framework; namespace System.Reactive.Linq.Tests { [TestFixture] public class ObservableSchedulerArgumentTest { [Test] [ExpectedException (typeof (MyException))] public void BufferScheduler () { var o = Observable.Range (1, 3).Buffer (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void BufferSchedulerEmpty () { var o = Observable.Range (0, 0).Buffer (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void DelayScheduler () { var o = Observable.Range (1, 3).Delay (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void DelaySchedulerEmpty () { var o = Observable.Empty<int> ().Delay (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void EmptyScheduler () { var o = Observable.Empty<int> (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void GenerateScheduler () { var o = Observable.Generate<int,int> (0, i => i < 5, i => i + 1, i => i, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void GenerateSchedulerEmpty () { var o = Observable.Generate<int,int> (0, i => i < 0, i => i + 1, i => i, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void IntervalScheduler () { var o = Observable.Interval (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void MergeScheduler () { var o = Observable.Range (0, 3).Merge (Observable.Range (4, 3), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void MergeSchedulerEmpty () { var o = Observable.Empty<int> ().Merge (Observable.Empty<int> (), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ObserveOnScheduler () { var o = Observable.Range (0, 3).ObserveOn (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ObserveOnSchedulerEmpty () { // empty, still schedules. var o = Observable.Empty<int> ().ObserveOn (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void RangeScheduler () { var o = Observable.Range (0, 3, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void RangeSchedulerEmpty () { var o = Observable.Range (0, 0, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void RepeatScheduler () { var o = Observable.Repeat (0, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } /* [Test] [ExpectedException (typeof (MyException))] public void ReplayScheduler () { var o = Observable.Range (0, 3).Replay (2, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } */ [Test] [ExpectedException (typeof (MyException))] public void ReturnScheduler () { var o = Observable.Return (0, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void SampleScheduler () { var o = Observable.Range (0, 3).Sample (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void SampleSchedulerEmpty () { var o = Observable.Empty<int> ().Sample (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void StartScheduler () { var o = Observable.Start (() => {}, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void StartWithScheduler () { var o = Observable.Range (0, 3).StartWith (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void SubscribeOnScheduler () { var o = Observable.Range (0, 3).StartWith (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ThrottleScheduler () { var o = Observable.Range (0, 3).Throttle (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] public void ThrottleSchedulerEmpty () { // empty causes no subscription. var o = Observable.Empty<int> ().Throttle (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ThrowScheduler () { var o = Observable.Throw<int> (new Exception (), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] // does not schedule public void TimeIntervalScheduler () { var o = Observable.Range (0, 3).TimeInterval (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void TimeoutScheduler () { var o = Observable.Range (0, 3).Timeout (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void TimeoutSchedulerEmpty () { var o = Observable.Range (0, 0).Timeout (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void TimeoutSchedulerTimeout () { // timeout with no value, still raises an error. var o = Observable.Interval (TimeSpan.FromMilliseconds (100)).Take (5).Timeout (TimeSpan.FromMilliseconds (10), new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void TimerScheduler () { var o = Observable.Timer (DateTimeOffset.Now, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] // does not schedule public void TimestampScheduler () { var o = Observable.Range (1, 3).Timestamp (new ErrorScheduler ()); // This ensures that Timestamp() does *not* use IScheduler to *schedule* tasks. var a = from t in o.ToEnumerable () select t.Value; Assert.AreEqual (new int [] {1, 2, 3}, a.ToArray (), "#1"); } [Test] [ExpectedException (typeof (MyException))] public void ToAsyncScheduler () { var o = Observable.ToAsync (() => {}, new ErrorScheduler ()); foreach (var i in o ().ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ToObservableScheduler () { var o = Enumerable.Range (0, 3).ToObservable (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void ToObservableSchedulerEmpty () { var o = Enumerable.Range (0, 0).ToObservable (new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void WindowScheduler () { var o = Observable.Range (0, 3).Window (TimeSpan.FromMilliseconds (10), 2, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } [Test] [ExpectedException (typeof (MyException))] public void WindowSchedulerEmpty () { var o = Observable.Range (0, 0).Window (TimeSpan.FromMilliseconds (10), 2, new ErrorScheduler ()); foreach (var i in o.ToEnumerable ()) ; } } }
#region License /* Illusory Studios C# Crypto Library (CryptSharp) Copyright (c) 2010 James F. Bellinger <jfb@zer7.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion using System; using System.Text; namespace BitPool.Cryptography.KDF.CryptSharp { public partial class BlowfishCipher { // Change this if you want a special but incompatible version of BCrypt. public static string BCryptMagic { get { return "OrpheanBeholderScryDoubt"; } } const int N = 16; static uint[][] S0 = new uint[][] { new uint[] { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a }, new uint[] { 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 }, new uint[] { 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 }, new uint[] { 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 } }; static uint[] P0 = new uint[] { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b }; } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System; using System.Diagnostics; using System.IO; namespace Mosa.Compiler.Pdb { /// <summary> /// Wraps PDB streams as a .NET stream. /// </summary> public class PdbStream : Stream { #region Data Members /// <summary> /// Holds the data of the current page. /// </summary> private byte[] page; /// <summary> /// Holds the length of the stream in bytes. /// </summary> private long length; /// <summary> /// Holds the page size. /// </summary> private int pageSize; /// <summary> /// Holds the pages. /// </summary> private int[] pages; /// <summary> /// The position within the stream. /// </summary> private long position; /// <summary> /// Holds the stream. /// </summary> private Stream stream; #endregion Data Members #region Construction /// <summary> /// Initializes a new instance of the <see cref="PdbStream"/> class. /// </summary> /// <param name="stream">The stream.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="pages">The pages.</param> /// <param name="length">The length.</param> public PdbStream(Stream stream, int pageSize, int[] pages, long length) { this.length = length; page = new byte[pageSize]; this.pageSize = pageSize; this.pages = pages; position = 0; this.stream = stream; SwitchPage(); } #endregion Construction #region Stream Overrides /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. /// </summary> /// <value></value> /// <returns>true if the stream supports reading; otherwise, false.</returns> public override bool CanRead { get { return true; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. /// </summary> /// <value></value> /// <returns>true if the stream supports seeking; otherwise, false.</returns> public override bool CanSeek { get { return true; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. /// </summary> /// <value></value> /// <returns>true if the stream supports writing; otherwise, false.</returns> public override bool CanWrite { get { return false; } } /// <summary> /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> public override void Flush() { stream.Flush(); } /// <summary> /// When overridden in a derived class, gets the length in bytes of the stream. /// </summary> /// <value></value> /// <returns>A long value representing the length of the stream in bytes.</returns> /// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Length { get { return length; } } /// <summary> /// When overridden in a derived class, gets or sets the position within the current stream. /// </summary> /// <value></value> /// <returns>The current position within the stream.</returns> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Position { get { return position; } set { Seek(value, SeekOrigin.Begin); } } /// <summary> /// When overridden in a derived class, 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">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// </returns> /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer"/> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="offset"/> or <paramref name="count"/> is negative. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override int Read(byte[] buffer, int offset, int count) { int pageOffset, pageRemaining, pageRead, totalRead = 0; // Split the read into page sized chunks while (0 != count) { pageOffset = (int)(position % pageSize); pageRemaining = pageSize - pageOffset; Debug.Assert(pageRemaining != 0, @"pageRemaining should never be zero."); pageRead = Math.Min(count, pageRemaining); Array.Copy(page, pageOffset, buffer, offset, pageRead); offset += pageRead; totalRead += pageRead; count -= pageRead; Position += pageRead; } return totalRead; } /// <summary> /// When overridden in a derived class, sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns> /// The new position within the current stream. /// </returns> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: position = offset; break; case SeekOrigin.Current: position += offset; break; case SeekOrigin.End: position = length - offset; break; } SwitchPage(); return position; } /// <summary> /// When overridden in a derived class, sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer"/> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="offset"/> or <paramref name="count"/> is negative. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception> /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } #endregion Stream Overrides #region Internals /// <summary> /// Switches the page. /// </summary> private void SwitchPage() { // Calculate the page index int pageIdx = (int)(position / pageSize); int pageOffset = (int)(position - (pageIdx * pageSize)); // Find the real offset lock (stream) { // Read the full page into the buffer stream.Position = (pages[pageIdx] * pageSize); stream.Read(page, 0, pageSize); } } #endregion Internals } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C06Level111 (editable child object).<br/> /// This is a generated base class of <see cref="C06Level111"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="C07Level1111Objects"/> of type <see cref="C07Level1111Coll"/> (1:M relation to <see cref="C08Level1111"/>)<br/> /// This class is an item of <see cref="C05Level111Coll"/> collection. /// </remarks> [Serializable] public partial class C06Level111 : BusinessBase<C06Level111> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Level_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_ID, "Level_1_1_1 ID"); /// <summary> /// Gets the Level_1_1_1 ID. /// </summary> /// <value>The Level_1_1_1 ID.</value> public int Level_1_1_1_ID { get { return GetProperty(Level_1_1_1_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Name, "Level_1_1_1 Name"); /// <summary> /// Gets or sets the Level_1_1_1 Name. /// </summary> /// <value>The Level_1_1_1 Name.</value> public string Level_1_1_1_Name { get { return GetProperty(Level_1_1_1_NameProperty); } set { SetProperty(Level_1_1_1_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="MarentID1"/> property. /// </summary> public static readonly PropertyInfo<int> MarentID1Property = RegisterProperty<int>(p => p.MarentID1, "Marent ID1"); /// <summary> /// Gets or sets the Marent ID1. /// </summary> /// <value>The Marent ID1.</value> public int MarentID1 { get { return GetProperty(MarentID1Property); } set { SetProperty(MarentID1Property, value); } } /// <summary> /// Maintains metadata about child <see cref="C07Level1111SingleObject"/> property. /// </summary> public static readonly PropertyInfo<C07Level1111Child> C07Level1111SingleObjectProperty = RegisterProperty<C07Level1111Child>(p => p.C07Level1111SingleObject, "A7 Level1111 Single Object", RelationshipTypes.Child); /// <summary> /// Gets the C07 Level1111 Single Object ("self load" child property). /// </summary> /// <value>The C07 Level1111 Single Object.</value> public C07Level1111Child C07Level1111SingleObject { get { return GetProperty(C07Level1111SingleObjectProperty); } private set { LoadProperty(C07Level1111SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C07Level1111ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<C07Level1111ReChild> C07Level1111ASingleObjectProperty = RegisterProperty<C07Level1111ReChild>(p => p.C07Level1111ASingleObject, "A7 Level1111 ASimple Object", RelationshipTypes.Child); /// <summary> /// Gets the C07 Level1111 ASingle Object ("self load" child property). /// </summary> /// <value>The C07 Level1111 ASingle Object.</value> public C07Level1111ReChild C07Level1111ASingleObject { get { return GetProperty(C07Level1111ASingleObjectProperty); } private set { LoadProperty(C07Level1111ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C07Level1111Objects"/> property. /// </summary> public static readonly PropertyInfo<C07Level1111Coll> C07Level1111ObjectsProperty = RegisterProperty<C07Level1111Coll>(p => p.C07Level1111Objects, "A7 Level1111 Objects", RelationshipTypes.Child); /// <summary> /// Gets the C07 Level1111 Objects ("self load" child property). /// </summary> /// <value>The C07 Level1111 Objects.</value> public C07Level1111Coll C07Level1111Objects { get { return GetProperty(C07Level1111ObjectsProperty); } private set { LoadProperty(C07Level1111ObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C06Level111"/> object. /// </summary> /// <returns>A reference to the created <see cref="C06Level111"/> object.</returns> internal static C06Level111 NewC06Level111() { return DataPortal.CreateChild<C06Level111>(); } /// <summary> /// Factory method. Loads a <see cref="C06Level111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="C06Level111"/> object.</returns> internal static C06Level111 GetC06Level111(SafeDataReader dr) { C06Level111 obj = new C06Level111(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C06Level111"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private C06Level111() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C06Level111"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Level_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(C07Level1111SingleObjectProperty, DataPortal.CreateChild<C07Level1111Child>()); LoadProperty(C07Level1111ASingleObjectProperty, DataPortal.CreateChild<C07Level1111ReChild>()); LoadProperty(C07Level1111ObjectsProperty, DataPortal.CreateChild<C07Level1111Coll>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C06Level111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_ID")); LoadProperty(Level_1_1_1_NameProperty, dr.GetString("Level_1_1_1_Name")); LoadProperty(MarentID1Property, dr.GetInt32("MarentID1")); _rowVersion = (dr.GetValue("RowVersion")) as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(C07Level1111SingleObjectProperty, C07Level1111Child.GetC07Level1111Child(Level_1_1_1_ID)); LoadProperty(C07Level1111ASingleObjectProperty, C07Level1111ReChild.GetC07Level1111ReChild(Level_1_1_1_ID)); LoadProperty(C07Level1111ObjectsProperty, C07Level1111Coll.GetC07Level1111Coll(Level_1_1_1_ID)); } /// <summary> /// Inserts a new <see cref="C06Level111"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Level_1_1_1_Name", ReadProperty(Level_1_1_1_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; LoadProperty(Level_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_ID"].Value); } FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="C06Level111"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Name", ReadProperty(Level_1_1_1_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@MarentID1", ReadProperty(MarentID1Property)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="C06Level111"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteC06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(C07Level1111SingleObjectProperty, DataPortal.CreateChild<C07Level1111Child>()); LoadProperty(C07Level1111ASingleObjectProperty, DataPortal.CreateChild<C07Level1111ReChild>()); LoadProperty(C07Level1111ObjectsProperty, DataPortal.CreateChild<C07Level1111Coll>()); } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }