context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* 23rd April 2017 Notes: Does not support duplicate value Only rely on recursive functions Completed on: 23rd April 2017 */ using System; namespace adt { interface IAvlTree { // add void insert(int key, object data); // delete by key void delete(int key); // display (inorder display) void display(); } class Avltree : IAvlTree { protected Node root = null; protected Node getRoot() { return root; } public void insert(int key, object data) { root = insert(getRoot(), key, data); } private Node insert(Node node, int key, object data) { if(node == null) { node = new Node(key, data); return node; } Node temp = null; if(key < node.key) { temp = insert(node.left, key, data); node.left = temp; } else if(key > node.key) { temp = insert(node.right, key, data); node.right = temp; } else { // avoiding duplicates Console.WriteLine("[ERROR] {0} key already exists", key); Console.WriteLine("[ERROR] call update(key, new_data) if you want to update data"); return node; } // updating height node.height = 1 + max(getHeight(node.left), getHeight(node.right)); // get balance factor int bal = getBalance(node); // if node is not balance // check 4 cases // left left case if(bal > 1 && key < node.left.key) return rightRotate(node); // right right case if(bal < -1 && key > node.right.key) return leftRotate(node); // left right case if(bal > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // right left case if(bal < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } public void delete(int key) { root = delete(getRoot(), key); } private Node delete(Node node, int key) { if(node == null) return node; // delete node in bst way if(key < node.key) node.left = delete(node.left, key); else if(key > node.key) node.right = delete(node.right, key); else { if(node.key != key) { Console.WriteLine("[ERROR] ABORT! KEY NOT FOUND"); return node; } // delete Node // no children and one child if(node.left == null) return node.right; if(node.right == null) return node.left; // have 2 children node.key = getMinValueNode(node.right).key; node.right = delete(node.right, node.key); } // after deletion balancing tree if(node == null) return node; node.height = 1 + max(getHeight(node.left), getHeight(node.right)); int bal = getBalance(node); // left left if(bal > 1 && getBalance(node.left) >= 0) return rightRotate(node); // left right if(bal > 1 && getBalance(node.left) < 0) { node.left = leftRotate(node.left); return rightRotate(node); } // right right if(bal < -1 && getBalance(node.right) <= 0) return leftRotate(node); // right left if(bal < -1 && getBalance(node.right) > 0) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } public void display() { //inorder(getRoot()); LevelOrderInLinesI(); Console.WriteLine(); } private void inorder(Node node) { if (node == null) return; inorder(node.left); Console.Write("{0} ", node.key); inorder(node.right); } private int getBalance(Node node) { if(node == null) return 0; return getHeight(node.left) - getHeight(node.right); } private int getHeight(Node node){ return node == null ? 0 : node.height; } private int max(int a, int b) { return a > b ? a : b; } // rotations private Node rightRotate(Node node) { Node x = node.left; Node temp = x.right; x.right = node; node.left = temp; node.height = max(getHeight(node.left), getHeight(node.right)) + 1; x.height = max(getHeight(x.left), getHeight(x.right)) + 1; return x; } private Node leftRotate(Node node) { Node x = node.right; Node temp = x.left; x.left = node; node.right = temp; node.height = max(getHeight(node.left), getHeight(node.right)) + 1; x.height = max(getHeight(x.left), getHeight(x.right)) + 1; return x; } protected void LevelOrderInLinesI() { Console.WriteLine("in level order"); Node curr = getRoot(); if(curr == null) return; int nCount = 0; cQueue q = new cQueue(); q.enqueue(curr); while(1==1) { nCount = q.getSize(); if(nCount == 0) break; while(nCount > 0) { curr = (Node)q.dequeue(); Console.Write("{0} ", curr.key); if(curr.left != null) q.enqueue(curr.left); if(curr.right != null) q.enqueue(curr.right); nCount--; } Console.WriteLine(); } } private Node getMinValueNode(Node node) { Node curr = node; if(curr == null) return curr; while(curr.left != null) curr = curr.left; return curr; } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetPoolFailuresSpectraS3Request : Ds3Request { private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { WithErrorMessage(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private string _poolId; public string PoolId { get { return _poolId; } set { WithPoolId(value); } } private PoolFailureType? _type; public PoolFailureType? Type { get { return _type; } set { WithType(value); } } public GetPoolFailuresSpectraS3Request WithErrorMessage(string errorMessage) { this._errorMessage = errorMessage; if (errorMessage != null) { this.QueryParams.Add("error_message", errorMessage); } else { this.QueryParams.Remove("error_message"); } return this; } public GetPoolFailuresSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetPoolFailuresSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetPoolFailuresSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetPoolFailuresSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetPoolFailuresSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetPoolFailuresSpectraS3Request WithPoolId(Guid? poolId) { this._poolId = poolId.ToString(); if (poolId != null) { this.QueryParams.Add("pool_id", poolId.ToString()); } else { this.QueryParams.Remove("pool_id"); } return this; } public GetPoolFailuresSpectraS3Request WithPoolId(string poolId) { this._poolId = poolId; if (poolId != null) { this.QueryParams.Add("pool_id", poolId); } else { this.QueryParams.Remove("pool_id"); } return this; } public GetPoolFailuresSpectraS3Request WithType(PoolFailureType? type) { this._type = type; if (type != null) { this.QueryParams.Add("type", type.ToString()); } else { this.QueryParams.Remove("type"); } return this; } public GetPoolFailuresSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/pool_failure"; } } } }
using System; using System.Net; using Craft.Net.Anvil; using System.Net.Sockets; using System.Security.Cryptography; using System.Threading; using Craft.Net.Common; using System.Collections.Generic; using Craft.Net.Networking; using ClassicStream = Craft.Net.Classic.Common.MinecraftStream; using ClassicPacket = Craft.Net.Classic.Networking.IPacket; using ClassicReader = Craft.Net.Classic.Networking.PacketReader; namespace RetroCraft { public class Proxy { public delegate void PacketHandler(RemoteClient client, Proxy proxy, IPacket packet); public delegate void ClassicHandler(RemoteClient client, Proxy proxy, ClassicPacket packet); public IPEndPoint LocalEndpoint { get; set; } public IPEndPoint RemoteEndpoint { get; set; } public List<RemoteClient> Clients { get; set; } public TcpListener Listener { get; set; } protected internal RSACryptoServiceProvider CryptoServiceProvider { get; set; } protected internal RSAParameters ServerKey { get; set; } protected internal object NetworkLock { get; set; } protected Thread NetworkThread { get; set; } protected PacketHandler[] PacketHandlers { get; set; } protected ClassicHandler[] ClassicPacketHandlers { get; set; } private DateTime LastPing { get; set; } public Proxy(IPEndPoint localEndpoint, IPEndPoint remoteEndpoint) { LocalEndpoint = localEndpoint; RemoteEndpoint = remoteEndpoint; NetworkLock = new object(); Clients = new List<RemoteClient>(); PacketHandlers = new PacketHandler[256]; ClassicPacketHandlers = new ClassicHandler[256]; ModernHandlers.PacketHandlers.Register(this); ClassicHandlers.PacketHandlers.Register(this); LastPing = DateTime.MinValue; } public void Start() { CryptoServiceProvider = new RSACryptoServiceProvider(1024); ServerKey = CryptoServiceProvider.ExportParameters(true); Listener = new TcpListener(LocalEndpoint); Listener.Start(); Listener.BeginAcceptTcpClient(AcceptClientAsync, null); NetworkThread = new Thread(NetworkWorker); NetworkThread.Start(); } public void Connect(RemoteClient client) { client.ClassicClient = new TcpClient(); client.ClassicClient.Connect(RemoteEndpoint); client.ClassicStream = new ClassicStream(new BufferedStream(client.ClassicClient.GetStream())); client.SendClassicPacket(new Craft.Net.Classic.Networking.HandshakePacket(ClassicReader.ProtocolVersion, client.Username, "", false)); client.ClassicLoggedIn = true; } public void RegisterPacketHandler(byte packetId, PacketHandler handler) { PacketHandlers[packetId] = handler; } public void RegisterClassicPacketHandler(byte packetId, ClassicHandler handler) { ClassicPacketHandlers[packetId] = handler; } public void HandleCommand(string command, RemoteClient client) { if (command.StartsWith("//save ")) { client.Level.SaveTo(command.Substring(7)); client.SendChat(ChatColors.Blue + "[RetroCraft] Level saved."); } } protected void AcceptClientAsync(IAsyncResult result) { lock (NetworkLock) { if (Listener == null) return; // Server shutting down var client = new RemoteClient(Listener.EndAcceptTcpClient(result)); client.NetworkStream = new MinecraftStream(new BufferedStream(client.NetworkClient.GetStream())); Clients.Add(client); Listener.BeginAcceptTcpClient(AcceptClientAsync, null); } } private void NetworkWorker() { while (true) { lock (NetworkLock) { for (int i = 0; i < Clients.Count; i++) { var client = Clients[i]; if (ModernWorker(ref i, client)) { if (client.ClassicLoggedIn) ClassicWorker(ref i, client); } } } } } internal void FlushClient(RemoteClient client) { while (client.PacketQueue.Count != 0) { IPacket nextPacket; if (client.PacketQueue.TryDequeue(out nextPacket)) { nextPacket.WritePacket(client.NetworkStream); client.NetworkStream.Flush(); } } } internal bool ModernWorker(ref int i, RemoteClient client) { bool disconnect = false; if (LastPing.AddSeconds(30) < DateTime.Now && client.ClassicLoggedIn) { client.SendPacket(new KeepAlivePacket(0)); LastPing = DateTime.Now; } while (client.PacketQueue.Count != 0) { IPacket nextPacket; if (client.PacketQueue.TryDequeue(out nextPacket)) { nextPacket.WritePacket(client.NetworkStream); Console.WriteLine("> {0}", nextPacket.GetType().Name); client.NetworkStream.Flush(); if (nextPacket is DisconnectPacket) disconnect = true; if (nextPacket is EncryptionKeyResponsePacket) { client.NetworkStream = new MinecraftStream(new BufferedStream(new AesStream(client.NetworkClient.GetStream(), client.SharedKey))); client.EncryptionEnabled = true; } } } if (disconnect) { Clients.RemoveAt(i--); return false; } // Read packets var timeout = DateTime.Now.AddMilliseconds(10); while (client.NetworkClient.Available != 0 && DateTime.Now < timeout) { try { var packet = PacketReader.ReadPacket(client.NetworkStream); if (packet is DisconnectPacket) { Disconnect(client); Clients.RemoveAt(i--); return false; } HandlePacket(client, packet); } catch (SocketException) { Disconnect(client); Clients.RemoveAt(i--); return false; } catch (InvalidOperationException e) { new DisconnectPacket(e.Message).WritePacket(client.NetworkStream); client.NetworkStream.Flush(); Disconnect(client); Clients.RemoveAt(i--); return false; } catch (Exception e) { new DisconnectPacket(e.Message).WritePacket(client.NetworkStream); client.NetworkStream.Flush(); Disconnect(client); Clients.RemoveAt(i--); return false; } } return true; } private void ClassicWorker(ref int i, RemoteClient client) { bool disconnect = false; while (client.ClassicQueue.Count != 0) { ClassicPacket nextPacket; if (client.ClassicQueue.TryDequeue(out nextPacket)) { nextPacket.WritePacket(client.ClassicStream); client.ClassicStream.Flush(); if (nextPacket is Craft.Net.Classic.Networking.DisconnectPlayerPacket) disconnect = true; } } if (disconnect) { Clients.RemoveAt(i--); return; } // Read packets var timeout = DateTime.Now.AddMilliseconds(10); while (client.ClassicClient.Available != 0 && DateTime.Now < timeout) { try { var packet = ClassicReader.ReadPacket(client.ClassicStream); Console.WriteLine("< {0}", packet.GetType().Name); if (packet is Craft.Net.Classic.Networking.DisconnectPlayerPacket) { new DisconnectPacket(((Craft.Net.Classic.Networking.DisconnectPlayerPacket)packet).Reason) .WritePacket(client.NetworkStream); client.NetworkStream.Flush(); Disconnect(client); Clients.RemoveAt(i--); return; } HandleClassicPacket(client, packet); } catch (SocketException) { Disconnect(client); Clients.RemoveAt(i--); return; } catch (InvalidOperationException e) { new DisconnectPacket(e.Message).WritePacket(client.NetworkStream); client.NetworkStream.Flush(); Clients.RemoveAt(i--); return; } catch (Exception e) { new DisconnectPacket(e.Message).WritePacket(client.NetworkStream); client.NetworkStream.Flush(); Disconnect(client); Clients.RemoveAt(i--); return; } } } private void HandlePacket(RemoteClient client, IPacket packet) { if (PacketHandlers[packet.Id] == null) return; //throw new InvalidOperationException("No packet handler registered for 0x" + packet.Id.ToString("X2")); PacketHandlers[packet.Id](client, this, packet); } private void HandleClassicPacket(RemoteClient client, ClassicPacket packet) { if (ClassicPacketHandlers[packet.Id] == null) return; //throw new InvalidOperationException("No packet handler registered for 0x" + packet.Id.ToString("X2")); ClassicPacketHandlers[packet.Id](client, this, packet); } private void Disconnect(RemoteClient client) { try { if (client.ClassicClient.Connected) client.ClassicClient.Close(); if (client.NetworkClient.Connected) client.NetworkClient.Close(); } catch { } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; namespace System.IO { public sealed class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path; FullPath = PathHelpers.GetFullPathInternal(path); DisplayPath = GetDisplayName(OriginalPath, FullPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject) { Debug.Assert(PathHelpers.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { // DisplayPath is dir name for coreclr Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == "."); return DisplayPath; } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { string s = FullPath; // FullPath might end in either "parent\child" or "parent\child", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. if (!PathHelpers.IsRoot(s)) { s = PathHelpers.TrimEndingDirectorySeparator(s); } string parentName = Path.GetDirectoryName(s); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path) { Contract.Requires(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); String newDirs = Path.Combine(FullPath, path); String fullPath = Path.GetFullPath(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison())) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), "path"); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); return EnumerableHelpers.ToArray(enumerable); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(String destDirName) { if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName); if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar) fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString; String fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; StringComparison pathComparison = PathInternal.GetComparison(); if (String.Equals(fullSourcePath, fullDestDirName, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(FullPath, fullDestDirName); FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Debug.Assert(originalPath != null); Debug.Assert(fullPath != null); return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : GetDirName(fullPath); } private static String GetDirName(String fullPath) { Debug.Assert(fullPath != null); return PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath)); } } }
// ZipFile.Read.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-August-05 11:38:59> // // ------------------------------------------------------------------ // // This module defines the methods for Reading zip files. // // ------------------------------------------------------------------ // using System; using System.IO; using System.Collections.Generic; namespace Ionic.Zip { /// <summary> /// A class for collecting the various options that can be used when /// Reading zip files for extraction or update. /// </summary> /// /// <remarks> /// <para> /// When reading a zip file, there are several options an /// application can set, to modify how the file is read, or what /// the library does while reading. This class collects those /// options into one container. /// </para> /// /// <para> /// Pass an instance of the <c>ReadOptions</c> class into the /// <c>ZipFile.Read()</c> method. /// </para> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/>. /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/>. /// </remarks> public class ReadOptions { /// <summary> /// An event handler for Read operations. When opening large zip /// archives, you may want to display a progress bar or other /// indicator of status progress while reading. This parameter /// allows you to specify a ReadProgress Event Handler directly. /// When you call <c>Read()</c>, the progress event is invoked as /// necessary. /// </summary> public EventHandler<ReadProgressEventArgs> ReadProgress { get; set; } /// <summary> /// The <c>System.IO.TextWriter</c> to use for writing verbose status messages /// during operations on the zip archive. A console application may wish to /// pass <c>System.Console.Out</c> to get messages on the Console. A graphical /// or headless application may wish to capture the messages in a different /// <c>TextWriter</c>, such as a <c>System.IO.StringWriter</c>. /// </summary> public TextWriter StatusMessageWriter { get; set; } /// <summary> /// The <c>System.Text.Encoding</c> to use when reading in the zip archive. Be /// careful specifying the encoding. If the value you use here is not the same /// as the Encoding used when the zip archive was created (possibly by a /// different archiver) you will get unexpected results and possibly exceptions. /// </summary> /// /// <seealso cref="ZipFile.ProvisionalAlternateEncoding"/> /// public System.Text.Encoding @Encoding { get; set; } } public partial class ZipFile { /// <summary> /// Reads a zip file archive and returns the instance. /// </summary> /// /// <remarks> /// <para> /// The stream is read using the default <c>System.Text.Encoding</c>, which is the /// <c>IBM437</c> codepage. /// </para> /// </remarks> /// /// <exception cref="System.Exception"> /// Thrown if the <c>ZipFile</c> cannot be read. The implementation of this method /// relies on <c>System.IO.File.OpenRead</c>, which can throw a variety of exceptions, /// including specific exceptions if a file is not found, an unauthorized access /// exception, exceptions for poorly formatted filenames, and so on. /// </exception> /// /// <param name="fileName"> /// The name of the zip archive to open. This can be a fully-qualified or relative /// pathname. /// </param> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/>. /// /// <returns>The instance read from the zip archive.</returns> /// public static ZipFile Read(string fileName) { return ZipFile.Read(fileName, null, null, null); } /// <summary> /// Reads a zip file archive from the named filesystem file using the /// specified options. /// </summary> /// /// <remarks> /// <para> /// This version of the <c>Read()</c> method allows the caller to pass /// in a <c>TextWriter</c> an <c>Encoding</c>, via an instance of the /// <c>ReadOptions</c> class. The <c>ZipFile</c> is read in using the /// specified encoding for entries where UTF-8 encoding is not /// explicitly specified. /// </para> /// </remarks> /// /// <example> /// /// <para> /// This example shows how to read a zip file using the Big-5 Chinese /// code page (950), and extract each entry in the zip file, while /// sending status messages out to the Console. /// </para> /// /// <para> /// For this code to work as intended, the zipfile must have been /// created using the big5 code page (CP950). This is typical, for /// example, when using WinRar on a machine with CP950 set as the /// default code page. In that case, the names of entries within the /// Zip archive will be stored in that code page, and reading the zip /// archive must be done using that code page. If the application did /// not use the correct code page in ZipFile.Read(), then names of /// entries within the zip archive would not be correctly retrieved. /// </para> /// /// <code lang="C#"> /// string zipToExtract = "MyArchive.zip"; /// string extractDirectory = "extract"; /// var options = new ReadOptions /// { /// StatusMessageWriter = System.Console.Out, /// Encoding = System.Text.Encoding.GetEncoding(950) /// }; /// using (ZipFile zip = ZipFile.Read(zipToExtract, options)) /// { /// foreach (ZipEntry e in zip) /// { /// e.Extract(extractDirectory); /// } /// } /// </code> /// /// /// <code lang="VB"> /// Dim zipToExtract as String = "MyArchive.zip" /// Dim extractDirectory as String = "extract" /// Dim options as New ReadOptions /// options.Encoding = System.Text.Encoding.GetEncoding(950) /// options.StatusMessageWriter = System.Console.Out /// Using zip As ZipFile = ZipFile.Read(zipToExtract, options) /// Dim e As ZipEntry /// For Each e In zip /// e.Extract(extractDirectory) /// Next /// End Using /// </code> /// </example> /// /// /// <example> /// /// <para> /// This example shows how to read a zip file using the default /// code page, to remove entries that have a modified date before a given threshold, /// sending status messages out to a <c>StringWriter</c>. /// </para> /// /// <code lang="C#"> /// var options = new ReadOptions /// { /// StatusMessageWriter = new System.IO.StringWriter() /// }; /// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options)) /// { /// var Threshold = new DateTime(2007,7,4); /// // We cannot remove the entry from the list, within the context of /// // an enumeration of said list. /// // So we add the doomed entry to a list to be removed later. /// // pass 1: mark the entries for removal /// var MarkedEntries = new System.Collections.Generic.List&lt;ZipEntry&gt;(); /// foreach (ZipEntry e in zip) /// { /// if (e.LastModified &lt; Threshold) /// MarkedEntries.Add(e); /// } /// // pass 2: actually remove the entry. /// foreach (ZipEntry zombie in MarkedEntries) /// zip.RemoveEntry(zombie); /// zip.Comment = "This archive has been updated."; /// zip.Save(); /// } /// // can now use contents of sw, eg store in an audit log /// </code> /// /// <code lang="VB"> /// Dim options as New ReadOptions /// options.StatusMessageWriter = New System.IO.StringWriter /// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options) /// Dim Threshold As New DateTime(2007, 7, 4) /// ' We cannot remove the entry from the list, within the context of /// ' an enumeration of said list. /// ' So we add the doomed entry to a list to be removed later. /// ' pass 1: mark the entries for removal /// Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry) /// Dim e As ZipEntry /// For Each e In zip /// If (e.LastModified &lt; Threshold) Then /// MarkedEntries.Add(e) /// End If /// Next /// ' pass 2: actually remove the entry. /// Dim zombie As ZipEntry /// For Each zombie In MarkedEntries /// zip.RemoveEntry(zombie) /// Next /// zip.Comment = "This archive has been updated." /// zip.Save /// End Using /// ' can now use contents of sw, eg store in an audit log /// </code> /// </example> /// /// <exception cref="System.Exception"> /// Thrown if the zipfile cannot be read. The implementation of /// this method relies on <c>System.IO.File.OpenRead</c>, which /// can throw a variety of exceptions, including specific /// exceptions if a file is not found, an unauthorized access /// exception, exceptions for poorly formatted filenames, and so /// on. /// </exception> /// /// <param name="fileName"> /// The name of the zip archive to open. /// This can be a fully-qualified or relative pathname. /// </param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <returns>The ZipFile instance read from the zip archive.</returns> /// /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/> /// public static ZipFile Read(string fileName, ReadOptions options) { if (options == null) throw new ArgumentNullException("options"); return Read(fileName, options.StatusMessageWriter, options.Encoding, options.ReadProgress); } /// <summary> /// Reads a zip file archive using the specified text encoding, the specified /// TextWriter for status messages, and the specified ReadProgress event handler, /// and returns the instance. /// </summary> /// /// <param name="fileName"> /// The name of the zip archive to open. /// This can be a fully-qualified or relative pathname. /// </param> /// /// <param name="readProgress"> /// An event handler for Read operations. /// </param> /// /// <param name="statusMessageWriter"> /// The <c>System.IO.TextWriter</c> to use for writing verbose status messages /// during operations on the zip archive. A console application may wish to /// pass <c>System.Console.Out</c> to get messages on the Console. A graphical /// or headless application may wish to capture the messages in a different /// <c>TextWriter</c>, such as a <c>System.IO.StringWriter</c>. /// </param> /// /// <param name="encoding"> /// The <c>System.Text.Encoding</c> to use when reading in the zip archive. Be /// careful specifying the encoding. If the value you use here is not the same /// as the Encoding used when the zip archive was created (possibly by a /// different archiver) you will get unexpected results and possibly exceptions. /// </param> /// /// <returns>The instance read from the zip archive.</returns> /// private static ZipFile Read(string fileName, TextWriter statusMessageWriter, System.Text.Encoding encoding, EventHandler<ReadProgressEventArgs> readProgress) { ZipFile zf = new ZipFile(); zf.AlternateEncoding = encoding ?? DefaultEncoding; zf.AlternateEncodingUsage = ZipOption.Always; zf._StatusMessageTextWriter = statusMessageWriter; zf._name = fileName; if (readProgress != null) zf.ReadProgress = readProgress; if (zf.Verbose) zf._StatusMessageTextWriter.WriteLine("reading from {0}...", fileName); ReadIntoInstance(zf); zf._fileAlreadyExists = true; return zf; } /// <summary> /// Reads a zip archive from a stream. /// </summary> /// /// <remarks> /// /// <para> /// When reading from a file, it's probably easier to just use /// <see cref="ZipFile.Read(String, /// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This /// overload is useful when when the zip archive content is /// available from an already-open stream. The stream must be /// open and readable and seekable when calling this method. The /// stream is left open when the reading is completed. /// </para> /// /// <para> /// Using this overload, the stream is read using the default /// <c>System.Text.Encoding</c>, which is the <c>IBM437</c> /// codepage. If you want to specify the encoding to use when /// reading the zipfile content, see /// <see cref="ZipFile.Read(Stream, /// ReadOptions)">ZipFile.Read(Stream, ReadOptions)</see>. This /// </para> /// /// <para> /// Reading of zip content begins at the current position in the /// stream. This means if you have a stream that concatenates /// regular data and zip data, if you position the open, readable /// stream at the start of the zip data, you will be able to read /// the zip archive using this constructor, or any of the ZipFile /// constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip /// content is concatenated at the end of a regular EXE file, as /// some self-extracting archives do. (Note: SFX files produced /// by DotNetZip do not work this way; they can be read as normal /// ZIP files). Another example might be a stream being read from /// a database, where the zip content is embedded within an /// aggregate stream of data. /// </para> /// /// </remarks> /// /// <example> /// <para> /// This example shows how to Read zip content from a stream, and /// extract one entry into a different stream. In this example, /// the filename "NameOfEntryInArchive.doc", refers only to the /// name of the entry within the zip archive. A file by that /// name is not created in the filesystem. The I/O is done /// strictly with the given streams. /// </para> /// /// <code> /// using (ZipFile zip = ZipFile.Read(InputStream)) /// { /// zip.Extract("NameOfEntryInArchive.doc", OutputStream); /// } /// </code> /// /// <code lang="VB"> /// Using zip as ZipFile = ZipFile.Read(InputStream) /// zip.Extract("NameOfEntryInArchive.doc", OutputStream) /// End Using /// </code> /// </example> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <returns>The ZipFile instance read from the stream</returns> /// public static ZipFile Read(Stream zipStream) { return Read(zipStream, null, null, null); } /// <summary> /// Reads a zip file archive from the given stream using the /// specified options. /// </summary> /// /// <remarks> /// /// <para> /// When reading from a file, it's probably easier to just use /// <see cref="ZipFile.Read(String, /// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This /// overload is useful when when the zip archive content is /// available from an already-open stream. The stream must be /// open and readable and seekable when calling this method. The /// stream is left open when the reading is completed. /// </para> /// /// <para> /// Reading of zip content begins at the current position in the /// stream. This means if you have a stream that concatenates /// regular data and zip data, if you position the open, readable /// stream at the start of the zip data, you will be able to read /// the zip archive using this constructor, or any of the ZipFile /// constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip /// content is concatenated at the end of a regular EXE file, as /// some self-extracting archives do. (Note: SFX files produced /// by DotNetZip do not work this way; they can be read as normal /// ZIP files). Another example might be a stream being read from /// a database, where the zip content is embedded within an /// aggregate stream of data. /// </para> /// </remarks> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <exception cref="System.Exception"> /// Thrown if the zip archive cannot be read. /// </exception> /// /// <returns>The ZipFile instance read from the stream.</returns> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/> /// public static ZipFile Read(Stream zipStream, ReadOptions options) { if (options == null) throw new ArgumentNullException("options"); return Read(zipStream, options.StatusMessageWriter, options.Encoding, options.ReadProgress); } /// <summary> /// Reads a zip archive from a stream, using the specified text Encoding, the /// specified TextWriter for status messages, /// and the specified ReadProgress event handler. /// </summary> /// /// <remarks> /// <para> /// Reading of zip content begins at the current position in the stream. This /// means if you have a stream that concatenates regular data and zip data, if /// you position the open, readable stream at the start of the zip data, you /// will be able to read the zip archive using this constructor, or any of the /// ZipFile constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip content is /// concatenated at the end of a regular EXE file, as some self-extracting /// archives do. (Note: SFX files produced by DotNetZip do not work this /// way). Another example might be a stream being read from a database, where /// the zip content is embedded within an aggregate stream of data. /// </para> /// </remarks> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <param name="statusMessageWriter"> /// The <c>System.IO.TextWriter</c> to which verbose status messages are written /// during operations on the <c>ZipFile</c>. For example, in a console /// application, System.Console.Out works, and will get a message for each entry /// added to the ZipFile. If the TextWriter is <c>null</c>, no verbose messages /// are written. /// </param> /// /// <param name="encoding"> /// The text encoding to use when reading entries that do not have the UTF-8 /// encoding bit set. Be careful specifying the encoding. If the value you use /// here is not the same as the Encoding used when the zip archive was created /// (possibly by a different archiver) you will get unexpected results and /// possibly exceptions. See the <see cref="ProvisionalAlternateEncoding"/> /// property for more information. /// </param> /// /// <param name="readProgress"> /// An event handler for Read operations. /// </param> /// /// <returns>an instance of ZipFile</returns> private static ZipFile Read(Stream zipStream, TextWriter statusMessageWriter, System.Text.Encoding encoding, EventHandler<ReadProgressEventArgs> readProgress) { if (zipStream == null) throw new ArgumentNullException("zipStream"); ZipFile zf = new ZipFile(); zf._StatusMessageTextWriter = statusMessageWriter; zf._alternateEncoding = encoding ?? ZipFile.DefaultEncoding; zf._alternateEncodingUsage = ZipOption.Always; if (readProgress != null) zf.ReadProgress += readProgress; zf._readstream = (zipStream.Position == 0L) ? zipStream : new OffsetStream(zipStream); zf._ReadStreamIsOurs = false; if (zf.Verbose) zf._StatusMessageTextWriter.WriteLine("reading from stream..."); ReadIntoInstance(zf); return zf; } private static void ReadIntoInstance(ZipFile zf) { Stream s = zf.ReadStream; try { zf._readName = zf._name; // workitem 13915 if (!s.CanSeek) { ReadIntoInstance_Orig(zf); return; } zf.OnReadStarted(); // change for workitem 8098 //zf._originPosition = s.Position; // Try reading the central directory, rather than scanning the file. uint datum = ReadFirstFourBytes(s); if (datum == ZipConstants.EndOfCentralDirectorySignature) return; // start at the end of the file... // seek backwards a bit, then look for the EoCD signature. int nTries = 0; bool success = false; // The size of the end-of-central-directory-footer plus 2 bytes is 18. // This implies an archive comment length of 0. We'll add a margin of // safety and start "in front" of that, when looking for the // EndOfCentralDirectorySignature long posn = s.Length - 64; long maxSeekback = Math.Max(s.Length - 0x4000, 10); do { if (posn < 0) posn = 0; // BOF s.Seek(posn, SeekOrigin.Begin); long bytesRead = SharedUtilities.FindSignature(s, (int)ZipConstants.EndOfCentralDirectorySignature); if (bytesRead != -1) success = true; else { if (posn==0) break; // started at the BOF and found nothing nTries++; // Weird: with NETCF, negative offsets from SeekOrigin.End DO // NOT WORK. So rather than seek a negative offset, we seek // from SeekOrigin.Begin using a smaller number. posn -= (32 * (nTries + 1) * nTries); } } while (!success && posn > maxSeekback); if (success) { // workitem 8299 zf._locEndOfCDS = s.Position - 4; byte[] block = new byte[16]; s.Read(block, 0, block.Length); zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2); if (zf._diskNumberWithCd == 0xFFFF) throw new ZipException("Spanned archives with more than 65534 segments are not supported at this time."); zf._diskNumberWithCd++; // I think the number in the file differs from reality by 1 int i = 12; uint offset32 = (uint) BitConverter.ToUInt32(block, i); if (offset32 == 0xFFFFFFFF) { Zip64SeekToCentralDirectory(zf); } else { zf._OffsetOfCentralDirectory = offset32; // change for workitem 8098 s.Seek(offset32, SeekOrigin.Begin); } ReadCentralDirectory(zf); } else { // Could not find the central directory. // Fallback to the old method. // workitem 8098: ok //s.Seek(zf._originPosition, SeekOrigin.Begin); s.Seek(0L, SeekOrigin.Begin); ReadIntoInstance_Orig(zf); } } catch (Exception ex1) { if (zf._ReadStreamIsOurs && zf._readstream != null) { try { #if NETCF zf._readstream.Close(); #else zf._readstream.Dispose(); #endif zf._readstream = null; } finally { } } throw new ZipException("Cannot read that as a ZipFile", ex1); } // the instance has been read in zf._contentsChanged = false; } private static void Zip64SeekToCentralDirectory(ZipFile zf) { Stream s = zf.ReadStream; byte[] block = new byte[16]; // seek back to find the ZIP64 EoCD. // I think this might not work for .NET CF ? s.Seek(-40, SeekOrigin.Current); s.Read(block, 0, 16); Int64 offset64 = BitConverter.ToInt64(block, 8); zf._OffsetOfCentralDirectory = 0xFFFFFFFF; zf._OffsetOfCentralDirectory64 = offset64; // change for workitem 8098 s.Seek(offset64, SeekOrigin.Begin); //zf.SeekFromOrigin(Offset64); uint datum = (uint)Ionic.Zip.SharedUtilities.ReadInt(s); if (datum != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature) throw new BadReadException(String.Format(" Bad signature (0x{0:X8}) looking for ZIP64 EoCD Record at position 0x{1:X8}", datum, s.Position)); s.Read(block, 0, 8); Int64 Size = BitConverter.ToInt64(block, 0); block = new byte[Size]; s.Read(block, 0, block.Length); offset64 = BitConverter.ToInt64(block, 36); // change for workitem 8098 s.Seek(offset64, SeekOrigin.Begin); //zf.SeekFromOrigin(Offset64); } private static uint ReadFirstFourBytes(Stream s) { uint datum = (uint)Ionic.Zip.SharedUtilities.ReadInt(s); return datum; } private static void ReadCentralDirectory(ZipFile zf) { // We must have the central directory footer record, in order to properly // read zip dir entries from the central directory. This because the logic // knows when to open a spanned file when the volume number for the central // directory differs from the volume number for the zip entry. The // _diskNumberWithCd was set when originally finding the offset for the // start of the Central Directory. // workitem 9214 bool inputUsesZip64 = false; ZipEntry de; // in lieu of hashset, use a dictionary var previouslySeen = new Dictionary<String,object>(); while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null) { de.ResetDirEntry(); zf.OnReadEntry(true, null); if (zf.Verbose) zf.StatusMessageTextWriter.WriteLine("entry {0}", de.FileName); zf._entries.Add(de.FileName,de); // workitem 9214 if (de._InputUsesZip64) inputUsesZip64 = true; previouslySeen.Add(de.FileName, null); // to prevent dupes } // workitem 9214; auto-set the zip64 flag if (inputUsesZip64) zf.UseZip64WhenSaving = Zip64Option.Always; // workitem 8299 if (zf._locEndOfCDS > 0) zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin); ReadCentralDirectoryFooter(zf); if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment)) zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment); // We keep the read stream open after reading. if (zf.Verbose) zf.StatusMessageTextWriter.WriteLine("read in {0} entries.", zf._entries.Count); zf.OnReadCompleted(); } // build the TOC by reading each entry in the file. private static void ReadIntoInstance_Orig(ZipFile zf) { zf.OnReadStarted(); //zf._entries = new System.Collections.Generic.List<ZipEntry>(); zf._entries = new System.Collections.Generic.Dictionary<String,ZipEntry>(); ZipEntry e; if (zf.Verbose) if (zf.Name == null) zf.StatusMessageTextWriter.WriteLine("Reading zip from stream..."); else zf.StatusMessageTextWriter.WriteLine("Reading zip {0}...", zf.Name); // work item 6647: PK00 (packed to removable disk) bool firstEntry = true; ZipContainer zc = new ZipContainer(zf); while ((e = ZipEntry.ReadEntry(zc, firstEntry)) != null) { if (zf.Verbose) zf.StatusMessageTextWriter.WriteLine(" {0}", e.FileName); zf._entries.Add(e.FileName,e); firstEntry = false; } // read the zipfile's central directory structure here. // workitem 9912 // But, because it may be corrupted, ignore errors. try { ZipEntry de; // in lieu of hashset, use a dictionary var previouslySeen = new Dictionary<String,Object>(); while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null) { // Housekeeping: Since ZipFile exposes ZipEntry elements in the enumerator, // we need to copy the comment that we grab from the ZipDirEntry // into the ZipEntry, so the application can access the comment. // Also since ZipEntry is used to Write zip files, we need to copy the // file attributes to the ZipEntry as appropriate. ZipEntry e1 = zf._entries[de.FileName]; if (e1 != null) { e1._Comment = de.Comment; if (de.IsDirectory) e1.MarkAsDirectory(); } previouslySeen.Add(de.FileName,null); // to prevent dupes } // workitem 8299 if (zf._locEndOfCDS > 0) zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin); ReadCentralDirectoryFooter(zf); if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment)) zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment); } catch (ZipException) { } catch (IOException) { } zf.OnReadCompleted(); } private static void ReadCentralDirectoryFooter(ZipFile zf) { Stream s = zf.ReadStream; int signature = Ionic.Zip.SharedUtilities.ReadSignature(s); byte[] block = null; int j = 0; if (signature == ZipConstants.Zip64EndOfCentralDirectoryRecordSignature) { // We have a ZIP64 EOCD // This data block is 4 bytes sig, 8 bytes size, 44 bytes fixed data, // followed by a variable-sized extension block. We have read the sig already. // 8 - datasize (64 bits) // 2 - version made by // 2 - version needed to extract // 4 - number of this disk // 4 - number of the disk with the start of the CD // 8 - total number of entries in the CD on this disk // 8 - total number of entries in the CD // 8 - size of the CD // 8 - offset of the CD // ----------------------- // 52 bytes block = new byte[8 + 44]; s.Read(block, 0, block.Length); Int64 DataSize = BitConverter.ToInt64(block, 0); // == 44 + the variable length if (DataSize < 44) throw new ZipException("Bad size in the ZIP64 Central Directory."); zf._versionMadeBy = BitConverter.ToUInt16(block, j); j += 2; zf._versionNeededToExtract = BitConverter.ToUInt16(block, j); j += 2; zf._diskNumberWithCd = BitConverter.ToUInt32(block, j); j += 2; //zf._diskNumberWithCd++; // hack!! // read the extended block block = new byte[DataSize - 44]; s.Read(block, 0, block.Length); // discard the result signature = Ionic.Zip.SharedUtilities.ReadSignature(s); if (signature != ZipConstants.Zip64EndOfCentralDirectoryLocatorSignature) throw new ZipException("Inconsistent metadata in the ZIP64 Central Directory."); block = new byte[16]; s.Read(block, 0, block.Length); // discard the result signature = Ionic.Zip.SharedUtilities.ReadSignature(s); } // Throw if this is not a signature for "end of central directory record" // This is a sanity check. if (signature != ZipConstants.EndOfCentralDirectorySignature) { s.Seek(-4, SeekOrigin.Current); throw new BadReadException(String.Format("Bad signature ({0:X8}) at position 0x{1:X8}", signature, s.Position)); } // read the End-of-Central-Directory-Record block = new byte[16]; zf.ReadStream.Read(block, 0, block.Length); // off sz data // ------------------------------------------------------- // 0 4 end of central dir signature (0x06054b50) // 4 2 number of this disk // 6 2 number of the disk with start of the central directory // 8 2 total number of entries in the central directory on this disk // 10 2 total number of entries in the central directory // 12 4 size of the central directory // 16 4 offset of start of central directory with respect to the starting disk number // 20 2 ZIP file comment length // 22 ?? ZIP file comment if (zf._diskNumberWithCd == 0) { zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2); //zf._diskNumberWithCd++; // hack!! } // read the comment here ReadZipFileComment(zf); } private static void ReadZipFileComment(ZipFile zf) { // read the comment here byte[] block = new byte[2]; zf.ReadStream.Read(block, 0, block.Length); Int16 commentLength = (short)(block[0] + block[1] * 256); if (commentLength > 0) { block = new byte[commentLength]; zf.ReadStream.Read(block, 0, block.Length); // workitem 10392 - prefer ProvisionalAlternateEncoding, // first. The fix for workitem 6513 tried to use UTF8 // only as necessary, but that is impossible to test // for, in this direction. There's no way to know what // characters the already-encoded bytes refer // to. Therefore, must do what the user tells us. string s1 = zf.AlternateEncoding.GetString(block, 0, block.Length); zf.Comment = s1; } } // private static bool BlocksAreEqual(byte[] a, byte[] b) // { // if (a.Length != b.Length) return false; // for (int i = 0; i < a.Length; i++) // { // if (a[i] != b[i]) return false; // } // return true; // } /// <summary> /// Checks the given file to see if it appears to be a valid zip file. /// </summary> /// <remarks> /// /// <para> /// Calling this method is equivalent to calling <see cref="IsZipFile(string, /// bool)"/> with the testExtract parameter set to false. /// </para> /// </remarks> /// /// <param name="fileName">The file to check.</param> /// <returns>true if the file appears to be a zip file.</returns> public static bool IsZipFile(string fileName) { return IsZipFile(fileName, false); } /// <summary> /// Checks a file to see if it is a valid zip file. /// </summary> /// /// <remarks> /// <para> /// This method opens the specified zip file, reads in the zip archive, /// verifying the ZIP metadata as it reads. /// </para> /// /// <para> /// If everything succeeds, then the method returns true. If anything fails - /// for example if an incorrect signature or CRC is found, indicating a /// corrupt file, the the method returns false. This method also returns /// false for a file that does not exist. /// </para> /// /// <para> /// If <paramref name="testExtract"/> is true, as part of its check, this /// method reads in the content for each entry, expands it, and checks CRCs. /// This provides an additional check beyond verifying the zip header and /// directory data. /// </para> /// /// <para> /// If <paramref name="testExtract"/> is true, and if any of the zip entries /// are protected with a password, this method will return false. If you want /// to verify a <c>ZipFile</c> that has entries which are protected with a /// password, you will need to do that manually. /// </para> /// /// </remarks> /// /// <param name="fileName">The zip file to check.</param> /// <param name="testExtract">true if the caller wants to extract each entry.</param> /// <returns>true if the file contains a valid zip file.</returns> public static bool IsZipFile(string fileName, bool testExtract) { bool result = false; try { if (!File.Exists(fileName)) return false; using (var s = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { result = IsZipFile(s, testExtract); } } catch (IOException) { } catch (ZipException) { } return result; } /// <summary> /// Checks a stream to see if it contains a valid zip archive. /// </summary> /// /// <remarks> /// <para> /// This method reads the zip archive contained in the specified stream, verifying /// the ZIP metadata as it reads. If testExtract is true, this method also extracts /// each entry in the archive, dumping all the bits into <see cref="Stream.Null"/>. /// </para> /// /// <para> /// If everything succeeds, then the method returns true. If anything fails - /// for example if an incorrect signature or CRC is found, indicating a corrupt /// file, the the method returns false. This method also returns false for a /// file that does not exist. /// </para> /// /// <para> /// If <c>testExtract</c> is true, this method reads in the content for each /// entry, expands it, and checks CRCs. This provides an additional check /// beyond verifying the zip header data. /// </para> /// /// <para> /// If <c>testExtract</c> is true, and if any of the zip entries are protected /// with a password, this method will return false. If you want to verify a /// ZipFile that has entries which are protected with a password, you will need /// to do that manually. /// </para> /// </remarks> /// /// <seealso cref="IsZipFile(string, bool)"/> /// /// <param name="stream">The stream to check.</param> /// <param name="testExtract">true if the caller wants to extract each entry.</param> /// <returns>true if the stream contains a valid zip archive.</returns> public static bool IsZipFile(Stream stream, bool testExtract) { if (stream == null) throw new ArgumentNullException("stream"); bool result = false; try { if (!stream.CanRead) return false; var bitBucket = Stream.Null; using (ZipFile zip1 = ZipFile.Read(stream, null, null, null)) { if (testExtract) { foreach (var e in zip1) { if (!e.IsDirectory) { e.Extract(bitBucket); } } } } result = true; } catch (IOException) { } catch (ZipException) { } return result; } } }
// // Util.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Drawing; using Xwt.Backends; using System.Collections.Generic; using System.Linq; namespace Xwt.GtkBackend { public static class Util { static uint targetIdCounter = 0; static Dictionary<TransferDataType, Gtk.TargetEntry[]> dragTargets = new Dictionary<TransferDataType, Gtk.TargetEntry[]> (); static Dictionary<string, TransferDataType> atomToType = new Dictionary<string, TransferDataType> (); static Size[] iconSizes = new Size[7]; static Util () { for (int i = 0; i < iconSizes.Length; i++) { int w, h; if (!Gtk.Icon.SizeLookup ((Gtk.IconSize)i, out w, out h)) w = h = -1; iconSizes[i].Width = w; iconSizes[i].Height = h; } if (Platform.IsWindows) { // Workaround for an issue in GTK for Windows. In windows Menu-sized icons are not 16x16, but 14x14 iconSizes[(int)Gtk.IconSize.Menu].Width = 16; iconSizes[(int)Gtk.IconSize.Menu].Height = 16; } } public static void SetDragData (TransferDataSource data, Gtk.DragDataGetArgs args) { foreach (var t in data.DataTypes) { object val = data.GetValue (t); SetSelectionData (args.SelectionData, t.Id, val); } } public static void SetSelectionData (Gtk.SelectionData data, string atomType, object val) { if (val == null) return; if (val is string) data.Text = (string)val; else if (val is Xwt.Drawing.Image) { var bmp = ((Image)val).ToBitmap (); data.SetPixbuf (((GtkImage)Toolkit.GetBackend (bmp)).Frames[0].Pixbuf); } else { var at = Gdk.Atom.Intern (atomType, false); data.Set (at, 0, TransferDataSource.SerializeValue (val)); } } public static bool GetSelectionData (ApplicationContext context, Gtk.SelectionData data, TransferDataStore target) { TransferDataType type = Util.AtomToType (data.Target.Name); if (type == null || data.Length <= 0) return false; if (type == TransferDataType.Text) target.AddText (data.Text); else if (type == TransferDataType.PrimaryText) target.AddPrimaryText (data.Text); else if (data.TargetsIncludeImage (false)) target.AddImage (context.Toolkit.WrapImage (data.Pixbuf)); else if (type == TransferDataType.Uri) { var uris = System.Text.Encoding.UTF8.GetString (data.Data).Split ('\n').Where (u => !string.IsNullOrEmpty(u)).Select (u => new Uri (u)).ToArray (); target.AddUris (uris); } else target.AddValue (type, data.Data); return true; } internal static TransferDataType AtomToType (string targetName) { TransferDataType type; atomToType.TryGetValue (targetName, out type); return type; } internal static TransferDataType[] GetDragTypes (Gdk.Atom[] dropTypes) { List<TransferDataType> types = new List<TransferDataType> (); foreach (var dt in dropTypes) { TransferDataType type; if (atomToType.TryGetValue (dt.Name, out type)) types.Add (type); } return types.ToArray (); } public static Gtk.TargetList BuildTargetTable (TransferDataType[] types) { var tl = new Gtk.TargetList (); foreach (var tt in types) tl.AddTable (CreateTargetEntries (tt)); return tl; } static Gtk.TargetEntry[] CreateTargetEntries (TransferDataType type) { lock (dragTargets) { Gtk.TargetEntry[] entries; if (dragTargets.TryGetValue (type, out entries)) return entries; uint id = targetIdCounter++; if (type == TransferDataType.Uri) { Gtk.TargetList list = new Gtk.TargetList (); list.AddUriTargets (id); entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Text || type == TransferDataType.PrimaryText) { Gtk.TargetList list = new Gtk.TargetList (); list.AddTextTargets (id); //HACK: work around gtk_selection_data_set_text causing crashes on Mac w/ QuickSilver, Clipbard History etc. if (Platform.IsMac) { list.Remove ("COMPOUND_TEXT"); list.Remove ("TEXT"); list.Remove ("STRING"); } entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Rtf) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("NSRTFPboardType", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("Rich Text Format", false); } else { atom = Gdk.Atom.Intern ("text/rtf", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else if (type == TransferDataType.Html) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("Apple HTML pasteboard type", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("HTML Format", false); } else { atom = Gdk.Atom.Intern ("text/html", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else { entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (Gdk.Atom.Intern ("application/" + type.Id, false), 0, id) }; } foreach (var a in entries.Select (e => e.Target)) atomToType [a] = type; return dragTargets [type] = entries; } } static Dictionary<string,string> icons; public static GtkImage ToGtkStock (string id) { if (icons == null) { icons = new Dictionary<string, string> (); icons [StockIconId.ZoomIn] = Gtk.Stock.ZoomIn; icons [StockIconId.ZoomOut] = Gtk.Stock.ZoomOut; icons [StockIconId.Zoom100] = Gtk.Stock.Zoom100; icons [StockIconId.ZoomFit] = Gtk.Stock.ZoomFit; icons [StockIconId.OrientationPortrait] = Gtk.Stock.OrientationPortrait; icons [StockIconId.OrientationLandscape] = Gtk.Stock.OrientationLandscape; icons [StockIconId.Add] = Gtk.Stock.Add; icons [StockIconId.Remove] = Gtk.Stock.Remove; icons [StockIconId.Warning] = Gtk.Stock.DialogWarning; icons [StockIconId.Error] = Gtk.Stock.DialogError; icons [StockIconId.Information] = Gtk.Stock.DialogInfo; icons [StockIconId.Question] = Gtk.Stock.DialogQuestion; } string res; if (!icons.TryGetValue (id, out res)) throw new NotSupportedException ("Unknown image: " + id); return new GtkImage (res); } public static Gtk.IconSize GetBestSizeFit (double size, Gtk.IconSize[] availablesizes = null) { // Find the size that better fits the requested size for (int n=0; n<iconSizes.Length; n++) { if (availablesizes != null && !availablesizes.Contains ((Gtk.IconSize)n)) continue; if (size <= iconSizes [n].Width) return (Gtk.IconSize)n; } if (availablesizes == null || availablesizes.Contains (Gtk.IconSize.Dialog)) return Gtk.IconSize.Dialog; else return Gtk.IconSize.Invalid; } public static double GetBestSizeFitSize (double size) { var s = GetBestSizeFit (size); return iconSizes [(int)s].Width; } public static ImageDescription WithDefaultSize (this ImageDescription image, Gtk.IconSize defaultIconSize) { if (image.Size.IsZero) { var s = iconSizes [(int)defaultIconSize]; image.Size = s; } return image; } public static double GetScaleFactor (Gtk.Widget w) { return GtkWorkarounds.GetScaleFactor (w); } public static double GetDefaultScaleFactor () { return 1; } internal static void SetSourceColor (this Cairo.Context cr, Cairo.Color color) { cr.SetSourceRGBA (color.R, color.G, color.B, color.A); } //this is needed for building against old Mono.Cairo versions [Obsolete] internal static void SetSource (this Cairo.Context cr, Cairo.Pattern pattern) { cr.Pattern = pattern; } [Obsolete] internal static Cairo.Surface GetTarget (this Cairo.Context cr) { return cr.Target; } [Obsolete] internal static void Dispose (this Cairo.Context cr) { ((IDisposable)cr).Dispose (); } } }
// 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.Collections.Generic; using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play.HUD; using osu.Game.Screens.Ranking.Expanded; using osuTK; namespace osu.Game.Screens.Play { /// <summary> /// Displays beatmap metadata inside <see cref="PlayerLoader"/> /// </summary> public class BeatmapMetadataDisplay : Container { private readonly WorkingBeatmap beatmap; private readonly Bindable<IReadOnlyList<Mod>> mods; private readonly Drawable logoFacade; private LoadingSpinner loading; public IBindable<IReadOnlyList<Mod>> Mods => mods; public bool Loading { set { if (value) loading.Show(); else loading.Hide(); } } public BeatmapMetadataDisplay(WorkingBeatmap beatmap, Bindable<IReadOnlyList<Mod>> mods, Drawable logoFacade) { this.beatmap = beatmap; this.logoFacade = logoFacade; this.mods = new Bindable<IReadOnlyList<Mod>>(); this.mods.BindTo(mods); } private IBindable<StarDifficulty?> starDifficulty; private FillFlowContainer versionFlow; private StarRatingDisplay starRatingDisplay; [BackgroundDependencyLoader] private void load(BeatmapDifficultyCache difficultyCache) { var metadata = beatmap.BeatmapInfo.Metadata; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Direction = FillDirection.Vertical, Children = new[] { logoFacade.With(d => { d.Anchor = Anchor.TopCentre; d.Origin = Anchor.TopCentre; }), new OsuSpriteText { Text = new RomanisableString(metadata.TitleUnicode, metadata.Title), Font = OsuFont.GetFont(size: 36, italics: true), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Margin = new MarginPadding { Top = 15 }, }, new OsuSpriteText { Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist), Font = OsuFont.GetFont(size: 26, italics: true), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, }, new Container { Size = new Vector2(300, 60), Margin = new MarginPadding(10), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, CornerRadius = 10, Masking = true, Children = new Drawable[] { new Sprite { RelativeSizeAxes = Axes.Both, Texture = beatmap?.Background, Origin = Anchor.Centre, Anchor = Anchor.Centre, FillMode = FillMode.Fill, }, loading = new LoadingLayer(true) } }, versionFlow = new FillFlowContainer { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Margin = new MarginPadding { Bottom = 40 }, Children = new Drawable[] { new OsuSpriteText { Text = beatmap?.BeatmapInfo?.Version, Font = OsuFont.GetFont(size: 26, italics: true), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, starRatingDisplay = new StarRatingDisplay(default) { Alpha = 0f, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, } } }, new GridContainer { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, AutoSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), }, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), }, Content = new[] { new Drawable[] { new MetadataLineLabel("Source"), new MetadataLineInfo(metadata.Source) }, new Drawable[] { new MetadataLineLabel("Mapper"), new MetadataLineInfo(metadata.AuthorString) } } }, new ModDisplay { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 20 }, Current = mods }, }, } }; starDifficulty = difficultyCache.GetBindableDifficulty(beatmap.BeatmapInfo); Loading = true; } protected override void LoadComplete() { base.LoadComplete(); if (starDifficulty.Value != null) { starRatingDisplay.Current.Value = starDifficulty.Value.Value; starRatingDisplay.Show(); } else { starRatingDisplay.Hide(); starDifficulty.ValueChanged += d => { Debug.Assert(d.NewValue != null); starRatingDisplay.Current.Value = d.NewValue.Value; versionFlow.AutoSizeDuration = 300; versionFlow.AutoSizeEasing = Easing.OutQuint; starRatingDisplay.FadeIn(300, Easing.InQuint); }; } } private class MetadataLineLabel : OsuSpriteText { public MetadataLineLabel(string text) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Margin = new MarginPadding { Right = 5 }; Colour = OsuColour.Gray(0.8f); Text = text; } } private class MetadataLineInfo : OsuSpriteText { public MetadataLineInfo(string text) { Margin = new MarginPadding { Left = 5 }; Text = string.IsNullOrEmpty(text) ? @"-" : text; } } } }
using System; using System.Reflection; using System.Collections.Generic; namespace InstallerLib { /// <summary> /// A configuration template /// </summary> public class Template { private static Template m_CurrentTemplate = null; private static List<Template> m_EmbeddedTemplates = null; static Template() { foreach (Template template in EmbeddedTemplates) { if (m_CurrentTemplate == null || template.Name == "English") m_CurrentTemplate = template; } } public static List<Template> EmbeddedTemplates { get { if (m_EmbeddedTemplates == null) { m_EmbeddedTemplates = GetEmbeddedTemplates(); } return m_EmbeddedTemplates; } } private static List<Template> GetEmbeddedTemplates() { List<Template> templates = new List<Template>(); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (string name in names) { if (name.StartsWith("InstallerLib.templates.")) { Template template = new Template(Assembly.GetExecutingAssembly().GetManifestResourceStream(name)); templates.Insert(0, template); } } return templates; } public static Template CurrentTemplate { get { return m_CurrentTemplate; } set { m_CurrentTemplate = value; } } private System.Xml.XmlDocument m_Document = new System.Xml.XmlDocument(); private System.Xml.XmlNode m_editortemplate_Node; private string m_Name; public Template(System.IO.Stream stream) : this(stream, "Untitled") { if (m_editortemplate_Node.Attributes["name"] != null) { m_Name = m_editortemplate_Node.Attributes["name"].InnerText; } } public Template(System.IO.Stream stream, string pName) { m_Document.Load(stream); m_editortemplate_Node = m_Document.SelectSingleNode("//editortemplate"); if (m_editortemplate_Node == null) { throw new Exception("Invalid template file"); } m_Name = pName; } public string Name { get { return m_Name; } } public string GetAttribute(string xPathQuery) { System.Xml.XmlNode node = m_editortemplate_Node.SelectSingleNode(xPathQuery); if (node == null) return "!!!! ERROR - Attribute " + xPathQuery + " not found in template file!!!!!"; return node.InnerText; } public class Template_setupconfiguration { private const string c_APPLICATION_NAME = "##APPLICATION_NAME"; private Template m_tpl; private string m_ApplicationName; public Template_setupconfiguration(Template template, string applicationName) { m_tpl = template; m_ApplicationName = applicationName; } public string cancel_caption { get { return m_tpl.GetAttribute("setupconfiguration/@cancel_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string dialog_caption { get { return m_tpl.GetAttribute("setupconfiguration/@dialog_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string dialog_message { get { return m_tpl.GetAttribute("setupconfiguration/@dialog_message").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string failed_exec_command_continue { get { return m_tpl.GetAttribute("setupconfiguration/@failed_exec_command_continue").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string skip_caption { get { return m_tpl.GetAttribute("setupconfiguration/@skip_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string install_caption { get { return m_tpl.GetAttribute("setupconfiguration/@install_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string uninstall_caption { get { return m_tpl.GetAttribute("setupconfiguration/@uninstall_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string installation_completed { get { return m_tpl.GetAttribute("setupconfiguration/@installation_completed").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string uninstallation_completed { get { return m_tpl.GetAttribute("setupconfiguration/@uninstallation_completed").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string installation_none { get { return m_tpl.GetAttribute("setupconfiguration/@installation_none").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string uninstallation_none { get { return m_tpl.GetAttribute("setupconfiguration/@uninstallation_none").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string installing_component_wait { get { return m_tpl.GetAttribute("setupconfiguration/@installing_component_wait").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string uninstalling_component_wait { get { return m_tpl.GetAttribute("setupconfiguration/@uninstalling_component_wait").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string reboot_required { get { return m_tpl.GetAttribute("setupconfiguration/@reboot_required").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string status_installed { get { return m_tpl.GetAttribute("setupconfiguration/@status_installed").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string status_notinstalled { get { return m_tpl.GetAttribute("setupconfiguration/@status_notinstalled").Replace(c_APPLICATION_NAME, m_ApplicationName); } } // message and caption to show during CAB extraction public string cab_dialog_message { get { return m_tpl.GetAttribute("setupconfiguration/@cab_dialog_message").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string cab_cancelled_message { get { return m_tpl.GetAttribute("setupconfiguration/@cab_cancelled_message").Replace(c_APPLICATION_NAME, m_ApplicationName); } } public string cab_dialog_caption { get { return m_tpl.GetAttribute("setupconfiguration/@cab_dialog_caption").Replace(c_APPLICATION_NAME, m_ApplicationName); } } // path to use during CAB extraction public string cab_path { get { return m_tpl.GetAttribute("setupconfiguration/@cab_path"); } } public bool cab_path_autodelete { get { return bool.Parse(m_tpl.GetAttribute("setupconfiguration/@cab_path_autodelete")); } } public string administrator_required_message { get { return m_tpl.GetAttribute("setupconfiguration/@administrator_required_message").Replace(c_APPLICATION_NAME, m_ApplicationName); } } } public class Template_component { private const string c_COMPONENT_NAME = "##COMPONENT_NAME"; private Template m_tpl; private string m_component_name; public Template_component(Template template, string componentName) { m_tpl = template; m_component_name = componentName; } public string display_name { get { return m_tpl.GetAttribute("component/@display_name").Replace(c_COMPONENT_NAME, m_component_name); } } } public class Template_downloaddialog { private const string c_COMPONENT_NAME = "##COMPONENT_NAME"; private Template m_tpl; private string m_ComponentName; public Template_downloaddialog(Template template, string componentName) { m_tpl = template; m_ComponentName = componentName; } public string buttoncancel_caption { get { return m_tpl.GetAttribute("downloaddialog/@buttoncancel_caption").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string buttonstart_caption { get { return m_tpl.GetAttribute("downloaddialog/@buttonstart_caption").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_caption { get { return m_tpl.GetAttribute("downloaddialog/@dialog_caption").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_message { get { return m_tpl.GetAttribute("downloaddialog/@dialog_message").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_message_downloading { get { return m_tpl.GetAttribute("downloaddialog/@dialog_message_downloading").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_message_copying { get { return m_tpl.GetAttribute("downloaddialog/@dialog_message_copying").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_message_connecting { get { return m_tpl.GetAttribute("downloaddialog/@dialog_message_connecting").Replace(c_COMPONENT_NAME, m_ComponentName); } } public string dialog_message_sendingrequest { get { return m_tpl.GetAttribute("downloaddialog/@dialog_message_sendingrequest").Replace(c_COMPONENT_NAME, m_ComponentName); } } } public Template_setupconfiguration setupConfiguration(string applicationName) { return new Template_setupconfiguration(this, applicationName); } public Template_component component(string componentName) { return new Template_component(this, componentName); } public Template_downloaddialog downloaddialog(string componentName) { return new Template_downloaddialog(this, componentName); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Composing; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Logging; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.PropertyEditors.ValueConverters; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Sync; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Infrastructure.PublishedCache; using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; using Umbraco.Cms.Infrastructure.Serialization; using Umbraco.Cms.Tests.Common; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.TestHelpers { [TestFixture] public class PublishedSnapshotServiceTestBase { [SetUp] public virtual void Setup() { VariationContextAccessor = new TestVariationContextAccessor(); PublishedSnapshotAccessor = new TestPublishedSnapshotAccessor(); } [TearDown] public void Teardown() => SnapshotService?.Dispose(); protected IShortStringHelper ShortStringHelper { get; } = TestHelper.ShortStringHelper; protected virtual IPublishedModelFactory PublishedModelFactory { get; } = new NoopPublishedModelFactory(); protected IContentTypeService ContentTypeService { get; private set; } protected IMediaTypeService MediaTypeService { get; private set; } protected IDataTypeService DataTypeService { get; private set; } protected IDomainService DomainService { get; private set; } protected IPublishedValueFallback PublishedValueFallback { get; private set; } protected IPublishedSnapshotService SnapshotService { get; private set; } protected IVariationContextAccessor VariationContextAccessor { get; private set; } protected TestPublishedSnapshotAccessor PublishedSnapshotAccessor { get; private set; } protected TestNuCacheContentService NuCacheContentService { get; private set; } protected PublishedContentTypeFactory PublishedContentTypeFactory { get; private set; } protected GlobalSettings GlobalSettings { get; } = new(); protected virtual PropertyValueConverterCollection PropertyValueConverterCollection => new(() => new[] { new TestSimpleTinyMceValueConverter() }); protected IPublishedContent GetContent(int id) { IPublishedSnapshot snapshot = GetPublishedSnapshot(); IPublishedContent doc = snapshot.Content.GetById(id); Assert.IsNotNull(doc); return doc; } protected IPublishedContent GetMedia(int id) { IPublishedSnapshot snapshot = GetPublishedSnapshot(); IPublishedContent doc = snapshot.Media.GetById(id); Assert.IsNotNull(doc); return doc; } protected UrlProvider GetUrlProvider( IUmbracoContextAccessor umbracoContextAccessor, RequestHandlerSettings requestHandlerSettings, WebRoutingSettings webRoutingSettings, out UriUtility uriUtility) { uriUtility = new UriUtility(Mock.Of<IHostingEnvironment>()); var urlProvider = new DefaultUrlProvider( Options.Create(requestHandlerSettings), Mock.Of<ILogger<DefaultUrlProvider>>(), new SiteDomainMapper(), umbracoContextAccessor, uriUtility, Mock.Of<ILocalizationService>(x=>x.GetDefaultLanguageIsoCode() == GlobalSettings.DefaultUILanguage) ); var publishedUrlProvider = new UrlProvider( umbracoContextAccessor, Options.Create(webRoutingSettings), new UrlProviderCollection(() => new[] { urlProvider }), new MediaUrlProviderCollection(() => Enumerable.Empty<IMediaUrlProvider>()), Mock.Of<IVariationContextAccessor>()); return publishedUrlProvider; } protected static PublishedRouter CreatePublishedRouter( IUmbracoContextAccessor umbracoContextAccessor, IEnumerable<IContentFinder> contentFinders = null, IPublishedUrlProvider publishedUrlProvider = null) => new(Options.Create(new WebRoutingSettings()), new ContentFinderCollection(() => contentFinders ?? Enumerable.Empty<IContentFinder>()), new TestLastChanceFinder(), new TestVariationContextAccessor(), Mock.Of<IProfilingLogger>(), Mock.Of<ILogger<PublishedRouter>>(), publishedUrlProvider ?? Mock.Of<IPublishedUrlProvider>(), Mock.Of<IRequestAccessor>(), Mock.Of<IPublishedValueFallback>(), Mock.Of<IFileService>(), Mock.Of<IContentTypeService>(), umbracoContextAccessor, Mock.Of<IEventAggregator>()); protected IUmbracoContextAccessor GetUmbracoContextAccessor(string urlAsString) { IPublishedSnapshot snapshot = GetPublishedSnapshot(); var uri = new Uri(urlAsString.Contains(Uri.SchemeDelimiter) ? urlAsString : $"http://example.com{urlAsString}"); IUmbracoContext umbracoContext = Mock.Of<IUmbracoContext>( x => x.CleanedUmbracoUrl == uri && x.Content == snapshot.Content && x.PublishedSnapshot == snapshot); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); return umbracoContextAccessor; } /// <summary> /// Used as a property editor for any test property that has an editor alias called "Umbraco.Void.RTE" /// </summary> private class TestSimpleTinyMceValueConverter : SimpleTinyMceValueConverter { public override bool IsConverter(IPublishedPropertyType propertyType) => propertyType.EditorAlias == "Umbraco.Void.RTE"; } protected static DataType[] GetDefaultDataTypes() { var serializer = new ConfigurationEditorJsonSerializer(); // create data types, property types and content types var dataType = new DataType(new VoidEditor("Editor", Mock.Of<IDataValueEditorFactory>()), serializer) { Id = 3 }; return new[] { dataType }; } protected virtual ServiceContext CreateServiceContext(IContentType[] contentTypes, IMediaType[] mediaTypes, IDataType[] dataTypes) { var contentTypeService = new Mock<IContentTypeService>(); contentTypeService.Setup(x => x.GetAll()).Returns(contentTypes); contentTypeService.Setup(x => x.GetAll(It.IsAny<int[]>())).Returns(contentTypes); contentTypeService.Setup(x => x.Get(It.IsAny<string>())) .Returns((string alias) => contentTypes.FirstOrDefault(x => x.Alias.InvariantEquals(alias))); var mediaTypeService = new Mock<IMediaTypeService>(); mediaTypeService.Setup(x => x.GetAll()).Returns(mediaTypes); mediaTypeService.Setup(x => x.GetAll(It.IsAny<int[]>())).Returns(mediaTypes); mediaTypeService.Setup(x => x.Get(It.IsAny<string>())) .Returns((string alias) => mediaTypes.FirstOrDefault(x => x.Alias.InvariantEquals(alias))); var contentTypeServiceBaseFactory = new Mock<IContentTypeBaseServiceProvider>(); contentTypeServiceBaseFactory.Setup(x => x.For(It.IsAny<IContentBase>())) .Returns(contentTypeService.Object); var dataTypeServiceMock = new Mock<IDataTypeService>(); dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataTypes); return ServiceContext.CreatePartial( dataTypeService: dataTypeServiceMock.Object, memberTypeService: Mock.Of<IMemberTypeService>(), memberService: Mock.Of<IMemberService>(), contentTypeService: contentTypeService.Object, mediaTypeService: mediaTypeService.Object, localizationService: Mock.Of<ILocalizationService>(), domainService: Mock.Of<IDomainService>(), fileService: Mock.Of<IFileService>() ); } /// <summary> /// Creates a published snapshot and set the accessor to resolve the created one /// </summary> /// <returns></returns> protected IPublishedSnapshot GetPublishedSnapshot() { IPublishedSnapshot snapshot = SnapshotService.CreatePublishedSnapshot(null); PublishedSnapshotAccessor.SetCurrent(snapshot); return snapshot; } /// <summary> /// Initializes the <see cref="IPublishedSnapshotService'" /> with a source of data /// </summary> /// <param name="contentNodeKits"></param> /// <param name="contentTypes"></param> protected void InitializedCache( IEnumerable<ContentNodeKit> contentNodeKits, IContentType[] contentTypes, IDataType[] dataTypes = null, IEnumerable<ContentNodeKit> mediaNodeKits = null, IMediaType[] mediaTypes = null) { // create a data source for NuCache NuCacheContentService = new TestNuCacheContentService(contentNodeKits, mediaNodeKits); IRuntimeState runtime = Mock.Of<IRuntimeState>(); Mock.Get(runtime).Setup(x => x.Level).Returns(RuntimeLevel.Run); // create a service context ServiceContext serviceContext = CreateServiceContext( contentTypes ?? Array.Empty<IContentType>(), mediaTypes ?? Array.Empty<IMediaType>(), dataTypes ?? GetDefaultDataTypes()); DataTypeService = serviceContext.DataTypeService; ContentTypeService = serviceContext.ContentTypeService; MediaTypeService = serviceContext.MediaTypeService; DomainService = serviceContext.DomainService; // create a scope provider IScopeProvider scopeProvider = Mock.Of<IScopeProvider>(); Mock.Get(scopeProvider) .Setup(x => x.CreateScope( It.IsAny<IsolationLevel>(), It.IsAny<RepositoryCacheMode>(), It.IsAny<IEventDispatcher>(), It.IsAny<IScopedNotificationPublisher>(), It.IsAny<bool?>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns(Mock.Of<IScope>); // create a published content type factory PublishedContentTypeFactory = new PublishedContentTypeFactory( PublishedModelFactory, PropertyValueConverterCollection, DataTypeService); ITypeFinder typeFinder = TestHelper.GetTypeFinder(); var nuCacheSettings = new NuCacheSettings(); // at last, create the complete NuCache snapshot service! var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; SnapshotService = new PublishedSnapshotService( options, Mock.Of<ISyncBootStateAccessor>(x => x.GetSyncBootState() == SyncBootState.WarmBoot), new SimpleMainDom(), serviceContext, PublishedContentTypeFactory, PublishedSnapshotAccessor, VariationContextAccessor, Mock.Of<IProfilingLogger>(), NullLoggerFactory.Instance, scopeProvider, NuCacheContentService, new TestDefaultCultureAccessor(), Options.Create(GlobalSettings), PublishedModelFactory, TestHelper.GetHostingEnvironment(), Options.Create(nuCacheSettings), //ContentNestedDataSerializerFactory, new ContentDataSerializer(new DictionaryOfPropertyDataSerializer())); // invariant is the current default VariationContextAccessor.VariationContext = new VariationContext(); PublishedValueFallback = new PublishedValueFallback(serviceContext, VariationContextAccessor); } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class RecnoDatabaseTest : DatabaseTest { private string testFixtureHome; private string testFixtureName; private string testName; private string testHome; [TestFixtureSetUp] public void RunBeforeTests() { testFixtureName = "RecnoDatabaseTest"; testFixtureHome = "./TestOut/" + testFixtureName; Configuration.ClearDir(testFixtureHome); } [Test] public void TestOpenExistingRecnoDB() { testName = "TestOpenExistingRecnoDB"; testHome = testFixtureHome + "/" + testName; string recnoDBFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); RecnoDatabaseConfig recConfig = new RecnoDatabaseConfig(); recConfig.Creation = CreatePolicy.ALWAYS; RecnoDatabase recDB = RecnoDatabase.Open( recnoDBFileName, recConfig); recDB.Close(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); string backingFile = testHome + "/backingFile"; File.Copy(recnoDBFileName, backingFile); dbConfig.BackingFile = backingFile; RecnoDatabase db = RecnoDatabase.Open(recnoDBFileName, dbConfig); Assert.AreEqual(db.Type, DatabaseType.RECNO); db.Close(); } [Test] public void TestOpenNewRecnoDB() { RecnoDatabase recnoDB; RecnoDatabaseConfig recnoConfig; testName = "TestOpenNewRecnoDB"; testHome = testFixtureHome + "/" + testName; string recnoDBFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); XmlElement xmlElem = Configuration.TestSetUp( testFixtureName, testName); recnoConfig = new RecnoDatabaseConfig(); RecnoDatabaseConfigTest.Config(xmlElem, ref recnoConfig, true); recnoDB = RecnoDatabase.Open(recnoDBFileName, recnoConfig); Confirm(xmlElem, recnoDB, true); recnoDB.Close(); } [Test] public void TestAppendWithoutTxn() { testName = "TestAppendWithoutTxn"; testHome = testFixtureHome + "/" + testName; string recnoDBFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); RecnoDatabaseConfig recnoConfig = new RecnoDatabaseConfig(); recnoConfig.Creation = CreatePolicy.ALWAYS; RecnoDatabase recnoDB = RecnoDatabase.Open( recnoDBFileName, recnoConfig); DatabaseEntry data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); uint num = recnoDB.Append(data); DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes(num)); Assert.IsTrue(recnoDB.Exists(key)); KeyValuePair<DatabaseEntry, DatabaseEntry> record = recnoDB.Get(key); Assert.IsTrue(data.Data.Length == record.Value.Data.Length); for (int i = 0; i < data.Data.Length; i++) Assert.IsTrue(data.Data[i] == record.Value.Data[i]); recnoDB.Close(); } [Test] public void TestCompact() { testName = "TestCompact"; testHome = testFixtureHome + "/" + testName; string recnoDBFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); RecnoDatabaseConfig recnoConfig = new RecnoDatabaseConfig(); recnoConfig.Creation = CreatePolicy.ALWAYS; recnoConfig.Length = 512; DatabaseEntry key, data; RecnoDatabase recnoDB; using (recnoDB = RecnoDatabase.Open( recnoDBFileName, recnoConfig)) { for (int i = 1; i <= 5000; i++) { data = new DatabaseEntry( BitConverter.GetBytes(i)); recnoDB.Append(data); } for (int i = 1; i <= 5000; i++) { if (i > 500 && (i % 5 != 0)) { key = new DatabaseEntry( BitConverter.GetBytes(i)); recnoDB.Delete(key); } } int startInt = 1; int stopInt = 2500; DatabaseEntry start, stop; start = new DatabaseEntry( BitConverter.GetBytes(startInt)); stop = new DatabaseEntry( BitConverter.GetBytes(stopInt)); Assert.IsTrue(recnoDB.Exists(start)); Assert.IsTrue(recnoDB.Exists(stop)); CompactConfig cCfg = new CompactConfig(); cCfg.start = start; cCfg.stop = stop; cCfg.FillPercentage = 30; cCfg.Pages = 1; cCfg.returnEnd = true; cCfg.Timeout = 5000; cCfg.TruncatePages = true; CompactData compactData = recnoDB.Compact(cCfg); Assert.IsNotNull(compactData.End); Assert.AreNotEqual(0, compactData.PagesExamined); } } [Test] public void TestStats() { testName = "TestStats"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); ConfigCase1(dbConfig); RecnoDatabase db = RecnoDatabase.Open(dbFileName, dbConfig); RecnoStats stats = db.Stats(); ConfirmStatsPart1Case1(stats); // Put 1000 records into the database. PutRecordCase1(db, null); stats = db.Stats(); ConfirmStatsPart2Case1(stats); // Delete 500 records. for (int i = 250; i <= 750; i++) db.Delete(new DatabaseEntry(BitConverter.GetBytes(i))); stats = db.Stats(); ConfirmStatsPart3Case1(stats); db.Close(); } [Test] public void TestStatsInTxn() { testName = "TestStatsInTxn"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); StatsInTxn(testHome, testName, false); } [Test] public void TestStatsWithIsolation() { testName = "TestStatsWithIsolation"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); StatsInTxn(testHome, testName, true); } public void StatsInTxn(string home, string name, bool ifIsolation) { DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); EnvConfigCase1(envConfig); DatabaseEnvironment env = DatabaseEnvironment.Open( home, envConfig); Transaction openTxn = env.BeginTransaction(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); ConfigCase1(dbConfig); dbConfig.Env = env; RecnoDatabase db = RecnoDatabase.Open(name + ".db", dbConfig, openTxn); openTxn.Commit(); Transaction statsTxn = env.BeginTransaction(); RecnoStats stats; RecnoStats fastStats; if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_ONE); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_ONE); } ConfirmStatsPart1Case1(stats); // Put 1000 records into the database. PutRecordCase1(db, statsTxn); if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_TWO); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_TWO); } ConfirmStatsPart2Case1(stats); // Delete 500 records. for (int i = 250; i <= 750; i++) db.Delete(new DatabaseEntry(BitConverter.GetBytes(i)), statsTxn); if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_THREE); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_THREE); } ConfirmStatsPart3Case1(stats); statsTxn.Commit(); db.Close(); env.Close(); } public void EnvConfigCase1(DatabaseEnvironmentConfig cfg) { cfg.Create = true; cfg.UseTxns = true; cfg.UseMPool = true; cfg.UseLogging = true; } public void ConfigCase1(RecnoDatabaseConfig dbConfig) { dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.PageSize = 4096; dbConfig.Length = 4000; dbConfig.PadByte = 256; } public void PutRecordCase1(RecnoDatabase db, Transaction txn) { for (int i = 1; i <= 1000; i++) { if (txn == null) db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); else db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry( BitConverter.GetBytes(i)), txn); } } public void ConfirmStatsPart1Case1(RecnoStats stats) { Assert.AreEqual(1, stats.EmptyPages); Assert.AreEqual(1, stats.Levels); Assert.AreNotEqual(0, stats.MagicNumber); Assert.AreEqual(10, stats.MetadataFlags); Assert.AreEqual(2, stats.MinKey); Assert.AreEqual(2, stats.nPages); Assert.AreEqual(4096, stats.PageSize); Assert.AreEqual(4000, stats.RecordLength); Assert.AreEqual(256, stats.RecordPadByte); Assert.AreEqual(9, stats.Version); } public void ConfirmStatsPart2Case1(RecnoStats stats) { Assert.AreEqual(0, stats.DuplicatePages); Assert.AreEqual(0, stats.DuplicatePagesFreeBytes); Assert.AreNotEqual(0, stats.InternalPages); Assert.AreNotEqual(0, stats.InternalPagesFreeBytes); Assert.AreNotEqual(0, stats.LeafPages); Assert.AreNotEqual(0, stats.LeafPagesFreeBytes); Assert.AreEqual(1000, stats.nData); Assert.AreEqual(1000, stats.nKeys); Assert.AreNotEqual(0, stats.OverflowPages); Assert.AreNotEqual(0, stats.OverflowPagesFreeBytes); } public void ConfirmStatsPart3Case1(RecnoStats stats) { Assert.AreNotEqual(0, stats.FreePages); } [Test] public void TestTruncateUnusedPages() { testName = "TestTruncateUnusedPages"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseCDB = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; dbConfig.PageSize = 512; RecnoDatabase db = RecnoDatabase.Open( testName + ".db", dbConfig); ModifyRecordsInDB(db, null); Assert.Less(0, db.TruncateUnusedPages()); db.Close(); env.Close(); } [Test] public void TestTruncateUnusedPagesInTxn() { testName = "TestTruncateUnusedPagesInTxn"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseLogging = true; envConfig.UseMPool = true; envConfig.UseTxns = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); Transaction openTxn = env.BeginTransaction(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; dbConfig.PageSize = 512; RecnoDatabase db = RecnoDatabase.Open( testName + ".db", dbConfig, openTxn); openTxn.Commit(); Transaction modifyTxn = env.BeginTransaction(); ModifyRecordsInDB(db, modifyTxn); Assert.Less(0, db.TruncateUnusedPages(modifyTxn)); modifyTxn.Commit(); db.Close(); env.Close(); } public void ModifyRecordsInDB(RecnoDatabase db, Transaction txn) { uint[] recnos = new uint[100]; if (txn == null) { // Add a lot of records into database. for (int i = 0; i < 100; i++) recnos[i] = db.Append(new DatabaseEntry( new byte[10240])); // Remove some records from database. for (int i = 30; i < 100; i++) db.Delete(new DatabaseEntry( BitConverter.GetBytes(recnos[i]))); } else { // Add a lot of records into database in txn. for (int i = 0; i < 100; i++) recnos[i] = db.Append(new DatabaseEntry( new byte[10240]), txn); // Remove some records from database in txn. for (int i = 30; i < 100; i++) db.Delete(new DatabaseEntry( BitConverter.GetBytes(recnos[i])), txn); } } public static void Confirm(XmlElement xmlElem, RecnoDatabase recnoDB, bool compulsory) { DatabaseTest.Confirm(xmlElem, recnoDB, compulsory); // Confirm recno database specific field/property Configuration.ConfirmInt(xmlElem, "Delimiter", recnoDB.RecordDelimiter, compulsory); Configuration.ConfirmUint(xmlElem, "Length", recnoDB.RecordLength, compulsory); Configuration.ConfirmInt(xmlElem, "PadByte", recnoDB.RecordPad, compulsory); Configuration.ConfirmBool(xmlElem, "Renumber", recnoDB.Renumber, compulsory); Configuration.ConfirmBool(xmlElem, "Snapshot", recnoDB.Snapshot, compulsory); Assert.AreEqual(DatabaseType.RECNO, recnoDB.Type); string type = recnoDB.Type.ToString(); Assert.IsNotNull(type); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B05_SubContinent_Child (editable child object).<br/> /// This is a generated base class of <see cref="B05_SubContinent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="B04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class B05_SubContinent_Child : BusinessBase<B05_SubContinent_Child> { #region State Fields [NotUndoable] [NonSerialized] internal int subContinent_ID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name"); /// <summary> /// Gets or sets the Sub Continent Child Name. /// </summary> /// <value>The Sub Continent Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B05_SubContinent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="B05_SubContinent_Child"/> object.</returns> internal static B05_SubContinent_Child NewB05_SubContinent_Child() { return DataPortal.CreateChild<B05_SubContinent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="B05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B05_SubContinent_Child"/> object.</returns> internal static B05_SubContinent_Child GetB05_SubContinent_Child(SafeDataReader dr) { B05_SubContinent_Child obj = new B05_SubContinent_Child(); // 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="B05_SubContinent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B05_SubContinent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B05_SubContinent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); // parent properties subContinent_ID1 = dr.GetInt32("SubContinent_ID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="B05_SubContinent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(B04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddB05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="B05_SubContinent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(B04_SubContinent parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateB05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="B05_SubContinent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(B04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteB05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <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 } }
using System; using System.IO; using LibGit2Sharp.Tests.TestHelpers; using Xunit; using Xunit.Extensions; namespace LibGit2Sharp.Tests { public class StageFixture : BaseFixture { [Theory] [InlineData("1/branch_file.txt", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)] [InlineData("README", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)] [InlineData("deleted_unstaged_file.txt", FileStatus.DeletedFromWorkdir, true, FileStatus.DeletedFromIndex, false, -1)] [InlineData("modified_unstaged_file.txt", FileStatus.ModifiedInWorkdir, true, FileStatus.ModifiedInIndex, true, 0)] [InlineData("new_untracked_file.txt", FileStatus.NewInWorkdir, false, FileStatus.NewInIndex, true, 1)] [InlineData("modified_staged_file.txt", FileStatus.ModifiedInIndex, true, FileStatus.ModifiedInIndex, true, 0)] [InlineData("new_tracked_file.txt", FileStatus.NewInIndex, true, FileStatus.NewInIndex, true, 0)] public void CanStage(string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex, FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation) { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null)); Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath)); Commands.Stage(repo, relativePath); Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count); Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null)); Assert.Equal(expectedStatusOnceStaged, repo.RetrieveStatus(relativePath)); } } [Theory] [InlineData("deleted_unstaged_file.txt", FileStatus.DeletedFromIndex)] [InlineData("modified_unstaged_file.txt", FileStatus.ModifiedInIndex)] [InlineData("new_untracked_file.txt", FileStatus.NewInIndex)] public void StagingWritesIndex(string relativePath, FileStatus expectedStatus) { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { Commands.Stage(repo, relativePath); } using (var repo = new Repository(path)) { Assert.Equal(expectedStatus, repo.RetrieveStatus(relativePath)); } } [Fact] public void CanStageTheUpdationOfAStagedFile() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; const string filename = "new_tracked_file.txt"; IndexEntry blob = repo.Index[filename]; Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename)); Touch(repo.Info.WorkingDirectory, filename, "brand new content"); Assert.Equal(FileStatus.NewInIndex | FileStatus.ModifiedInWorkdir, repo.RetrieveStatus(filename)); Commands.Stage(repo, filename); IndexEntry newBlob = repo.Index[filename]; Assert.Equal(count, repo.Index.Count); Assert.NotEqual(newBlob.Id, blob.Id); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename)); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.DeletedFromIndex)] public void StagingAnUnknownFileThrowsIfExplicitPath(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); Assert.Throws<UnmatchedPathException>(() => Commands.Stage(repo, relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions() })); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.DeletedFromIndex)] public void CanStageAnUnknownFileWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); Commands.Stage(repo, relativePath); Commands.Stage(repo, relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } }); Assert.Equal(status, repo.RetrieveStatus(relativePath)); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.DeletedFromIndex)] public void StagingAnUnknownFileWithLaxExplicitPathsValidationDoesntThrow(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); Commands.Stage(repo, relativePath); Commands.Stage(repo, relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } }); } } [Fact] public void CanStageTheRemovalOfAStagedFile() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; const string filename = "new_tracked_file.txt"; Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename)); File.Delete(Path.Combine(repo.Info.WorkingDirectory, filename)); Assert.Equal(FileStatus.NewInIndex | FileStatus.DeletedFromWorkdir, repo.RetrieveStatus(filename)); Commands.Stage(repo, filename); Assert.Null(repo.Index[filename]); Assert.Equal(count - 1, repo.Index.Count); Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(filename)); } } [Theory] [InlineData("unit_test.txt")] [InlineData("!unit_test.txt")] [InlineData("!bang/unit_test.txt")] public void CanStageANewFileInAPersistentManner(string filename) { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(filename)); Assert.Null(repo.Index[filename]); Touch(repo.Info.WorkingDirectory, filename, "some contents"); Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(filename)); Assert.Null(repo.Index[filename]); Commands.Stage(repo, filename); Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename)); } using (var repo = new Repository(path)) { Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename)); } } [SkippableTheory] [InlineData(false)] [InlineData(true)] public void CanStageANewFileWithAFullPath(bool ignorecase) { // Skipping due to ignorecase issue in libgit2. // See: https://github.com/libgit2/libgit2/pull/1689. InconclusiveIf(() => ignorecase, "Skipping 'ignorecase = true' test due to ignorecase issue in libgit2."); //InconclusiveIf(() => IsFileSystemCaseSensitive && ignorecase, // "Skipping 'ignorecase = true' test on case-sensitive file system."); string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Config.Set("core.ignorecase", ignorecase); } using (var repo = new Repository(path)) { const string filename = "new_untracked_file.txt"; string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename); Assert.True(File.Exists(fullPath)); AssertStage(null, repo, fullPath); AssertStage(ignorecase, repo, fullPath.ToUpperInvariant()); AssertStage(ignorecase, repo, fullPath.ToLowerInvariant()); } } private static void AssertStage(bool? ignorecase, IRepository repo, string path) { try { Commands.Stage(repo, path); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(path)); repo.Index.Replace(repo.Head.Tip); Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(path)); } catch (ArgumentException) { Assert.False(ignorecase ?? true); } } [Fact] public void CanStageANewFileWithARelativePathContainingNativeDirectorySeparatorCharacters() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; string file = Path.Combine("Project", "a_file.txt"); Touch(repo.Info.WorkingDirectory, file, "With backward slash on Windows!"); Commands.Stage(repo, file); Assert.Equal(count + 1, repo.Index.Count); const string posixifiedPath = "Project/a_file.txt"; Assert.NotNull(repo.Index[posixifiedPath]); Assert.Equal(posixifiedPath, repo.Index[posixifiedPath].Path); } } [Fact] public void StagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirThrows() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { string fullPath = Touch(scd.RootedDirectoryPath, "unit_test.txt", "some contents"); Assert.Throws<ArgumentException>(() => Commands.Stage(repo, fullPath)); } } [Fact] public void StagingFileWithBadParamsThrows() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Throws<ArgumentException>(() => Commands.Stage(repo, string.Empty)); Assert.Throws<ArgumentNullException>(() => Commands.Stage(repo, (string)null)); Assert.Throws<ArgumentException>(() => Commands.Stage(repo, new string[] { })); Assert.Throws<ArgumentException>(() => Commands.Stage(repo, new string[] { null })); } } /* * $ git status -s * M 1/branch_file.txt * M README * M branch_file.txt * D deleted_staged_file.txt * D deleted_unstaged_file.txt * M modified_staged_file.txt * M modified_unstaged_file.txt * M new.txt * A new_tracked_file.txt * ?? new_untracked_file.txt * * By passing "*" to Stage, the following files will be added/removed/updated from the index: * - deleted_unstaged_file.txt : removed * - modified_unstaged_file.txt : updated * - new_untracked_file.txt : added */ [Theory] [InlineData("*u*", 0)] [InlineData("*", 0)] [InlineData("1/*", 0)] [InlineData("RE*", 0)] [InlineData("d*", -1)] [InlineData("*modified_unstaged*", 0)] [InlineData("new_*file.txt", 1)] public void CanStageWithPathspec(string relativePath, int expectedIndexCountVariation) { using (var repo = new Repository(SandboxStandardTestRepo())) { int count = repo.Index.Count; Commands.Stage(repo, relativePath); Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count); } } [Fact] public void CanStageWithMultiplePathspecs() { using (var repo = new Repository(SandboxStandardTestRepo())) { int count = repo.Index.Count; Commands.Stage(repo, new string[] { "*", "u*" }); Assert.Equal(count, repo.Index.Count); // 1 added file, 1 deleted file, so same count } } [Theory] [InlineData("ignored_file.txt")] [InlineData("ignored_folder/file.txt")] public void CanIgnoreIgnoredPaths(string path) { using (var repo = new Repository(SandboxStandardTestRepo())) { Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n"); Touch(repo.Info.WorkingDirectory, path, "This file is ignored."); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); Commands.Stage(repo, "*"); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); } } [Theory] [InlineData("ignored_file.txt")] [InlineData("ignored_folder/file.txt")] public void CanStageIgnoredPaths(string path) { using (var repo = new Repository(SandboxStandardTestRepo())) { Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n"); Touch(repo.Info.WorkingDirectory, path, "This file is ignored."); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); Commands.Stage(repo, path, new StageOptions { IncludeIgnored = true }); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(path)); } } [Theory] [InlineData("new_untracked_file.txt", FileStatus.Ignored)] [InlineData("modified_unstaged_file.txt", FileStatus.ModifiedInIndex)] public void IgnoredFilesAreOnlyStagedIfTheyreInTheRepo(string filename, FileStatus expected) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, ".gitignore"), String.Format("{0}\n", filename)); Commands.Stage(repo, filename); Assert.Equal(expected, repo.RetrieveStatus(filename)); } } [Theory] [InlineData("ancestor-and-ours.txt", FileStatus.Unaltered)] [InlineData("ancestor-and-theirs.txt", FileStatus.NewInIndex)] [InlineData("ancestor-only.txt", FileStatus.Nonexistent)] [InlineData("conflicts-one.txt", FileStatus.ModifiedInIndex)] [InlineData("conflicts-two.txt", FileStatus.ModifiedInIndex)] [InlineData("ours-only.txt", FileStatus.Unaltered)] [InlineData("ours-and-theirs.txt", FileStatus.ModifiedInIndex)] [InlineData("theirs-only.txt", FileStatus.NewInIndex)] public void CanStageConflictedIgnoredFiles(string filename, FileStatus expected) { var path = SandboxMergedTestRepo(); using (var repo = new Repository(path)) { File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, ".gitignore"), String.Format("{0}\n", filename)); Commands.Stage(repo, filename); Assert.Equal(expected, repo.RetrieveStatus(filename)); } } [Fact] public void CanSuccessfullyStageTheContentOfAModifiedFileOfTheSameSizeWithinTheSameSecond() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { for (int i = 0; i < 10; i++) { Touch(repo.Info.WorkingDirectory, "test.txt", Guid.NewGuid().ToString()); Commands.Stage(repo, "test.txt"); repo.Commit("Commit", Constants.Signature, Constants.Signature); } } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A fire station. With firemen. /// </summary> public class FireStation_Core : TypeCore, ICivicStructure { public FireStation_Core() { this._TypeId = 104; this._Id = "FireStation"; this._Schema_Org_Url = "http://schema.org/FireStation"; string label = ""; GetLabel(out label, "FireStation", typeof(FireStation_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{62,93}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(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; using System.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Security.Policy; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { // // Member fields // private XmlTextReaderImpl _impl; // // // Constructors // protected XmlTextReader() { _impl = new XmlTextReaderImpl(); _impl.OuterReader = this; } protected XmlTextReader(XmlNameTable nt) { _impl = new XmlTextReaderImpl(nt); _impl.OuterReader = this; } public XmlTextReader(Stream input) { _impl = new XmlTextReaderImpl(input); _impl.OuterReader = this; } public XmlTextReader(string url, Stream input) { _impl = new XmlTextReaderImpl(url, input); _impl.OuterReader = this; } public XmlTextReader(Stream input, XmlNameTable nt) { _impl = new XmlTextReaderImpl(input, nt); _impl.OuterReader = this; } public XmlTextReader(string url, Stream input, XmlNameTable nt) { _impl = new XmlTextReaderImpl(url, input, nt); _impl.OuterReader = this; } public XmlTextReader(TextReader input) { _impl = new XmlTextReaderImpl(input); _impl.OuterReader = this; } public XmlTextReader(string url, TextReader input) { _impl = new XmlTextReaderImpl(url, input); _impl.OuterReader = this; } public XmlTextReader(TextReader input, XmlNameTable nt) { _impl = new XmlTextReaderImpl(input, nt); _impl.OuterReader = this; } public XmlTextReader(string url, TextReader input, XmlNameTable nt) { _impl = new XmlTextReaderImpl(url, input, nt); _impl.OuterReader = this; } public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) { _impl = new XmlTextReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext context) { _impl = new XmlTextReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } public XmlTextReader(string url) { _impl = new XmlTextReaderImpl(url, new NameTable()); _impl.OuterReader = this; } public XmlTextReader(String url, XmlNameTable nt) { _impl = new XmlTextReaderImpl(url, nt); _impl.OuterReader = this; } // // XmlReader members // public override XmlNodeType NodeType { get { return _impl.NodeType; } } public override string Name { get { return _impl.Name; } } public override string LocalName { get { return _impl.LocalName; } } public override string NamespaceURI { get { return _impl.NamespaceURI; } } public override string Prefix { get { return _impl.Prefix; } } public override bool HasValue { get { return _impl.HasValue; } } public override string Value { get { return _impl.Value; } } public override int Depth { get { return _impl.Depth; } } public override string BaseURI { get { return _impl.BaseURI; } } public override bool IsEmptyElement { get { return _impl.IsEmptyElement; } } public override bool IsDefault { get { return _impl.IsDefault; } } public override char QuoteChar { get { return _impl.QuoteChar; } } public override XmlSpace XmlSpace { get { return _impl.XmlSpace; } } public override string XmlLang { get { return _impl.XmlLang; } } // XmlTextReader does not override SchemaInfo, ValueType and ReadTypeValue public override int AttributeCount { get { return _impl.AttributeCount; } } public override string GetAttribute(string name) { return _impl.GetAttribute(name); } public override string GetAttribute(string localName, string namespaceURI) { return _impl.GetAttribute(localName, namespaceURI); } public override string GetAttribute(int i) { return _impl.GetAttribute(i); } public override bool MoveToAttribute(string name) { return _impl.MoveToAttribute(name); } public override bool MoveToAttribute(string localName, string namespaceURI) { return _impl.MoveToAttribute(localName, namespaceURI); } public override void MoveToAttribute(int i) { _impl.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { return _impl.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return _impl.MoveToNextAttribute(); } public override bool MoveToElement() { return _impl.MoveToElement(); } public override bool ReadAttributeValue() { return _impl.ReadAttributeValue(); } public override bool Read() { return _impl.Read(); } public override bool EOF { get { return _impl.EOF; } } public override void Close() { _impl.Close(); } public override ReadState ReadState { get { return _impl.ReadState; } } public override void Skip() { _impl.Skip(); } public override XmlNameTable NameTable { get { return _impl.NameTable; } } public override String LookupNamespace(String prefix) { string ns = _impl.LookupNamespace(prefix); if (ns != null && ns.Length == 0) { ns = null; } return ns; } public override bool CanResolveEntity { get { return true; } } public override void ResolveEntity() { _impl.ResolveEntity(); } // Binary content access methods public override bool CanReadBinaryContent { get { return true; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { return _impl.ReadContentAsBase64(buffer, index, count); } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { return _impl.ReadElementContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { return _impl.ReadContentAsBinHex(buffer, index, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { return _impl.ReadElementContentAsBinHex(buffer, index, count); } // Text streaming methods // XmlTextReader does do support streaming of Value (there are backwards compatibility issues when enabled) public override bool CanReadValueChunk { get { return false; } } // Overriden helper methods public override string ReadString() { _impl.MoveOffEntityReference(); return base.ReadString(); } // // IXmlLineInfo members // public bool HasLineInfo() { return true; } public int LineNumber { get { return _impl.LineNumber; } } public int LinePosition { get { return _impl.LinePosition; } } // // IXmlNamespaceResolver members // IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return _impl.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _impl.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _impl.LookupPrefix(namespaceName); } // This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey. #pragma warning disable 3002 // FXCOP: ExplicitMethodImplementationsInUnsealedClassesHaveVisibleAlternates // public versions of IXmlNamespaceResolver methods, so that XmlTextReader subclasses can access them public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return _impl.GetNamespacesInScope(scope); } #pragma warning restore 3002 // // XmlTextReader // public bool Namespaces { get { return _impl.Namespaces; } set { _impl.Namespaces = value; } } public bool Normalization { get { return _impl.Normalization; } set { _impl.Normalization = value; } } public Encoding Encoding { get { return _impl.Encoding; } } public WhitespaceHandling WhitespaceHandling { get { return _impl.WhitespaceHandling; } set { _impl.WhitespaceHandling = value; } } [Obsolete("Use DtdProcessing property instead.")] public bool ProhibitDtd { get { return _impl.DtdProcessing == DtdProcessing.Prohibit; } set { _impl.DtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse; } } public DtdProcessing DtdProcessing { get { return _impl.DtdProcessing; } set { _impl.DtdProcessing = value; } } public EntityHandling EntityHandling { get { return _impl.EntityHandling; } set { _impl.EntityHandling = value; } } public XmlResolver XmlResolver { set { _impl.XmlResolver = value; } } public void ResetState() { _impl.ResetState(); } public TextReader GetRemainder() { return _impl.GetRemainder(); } public int ReadChars(char[] buffer, int index, int count) { return _impl.ReadChars(buffer, index, count); } public int ReadBase64(byte[] array, int offset, int len) { return _impl.ReadBase64(array, offset, len); } public int ReadBinHex(byte[] array, int offset, int len) { return _impl.ReadBinHex(array, offset, len); } // // Internal helper methods // internal XmlTextReaderImpl Impl { get { return _impl; } } internal override XmlNamespaceManager NamespaceManager { get { return _impl.NamespaceManager; } } // NOTE: System.Data.SqlXml.XmlDataSourceResolver accesses this property via reflection internal bool XmlValidatingReaderCompatibilityMode { set { _impl.XmlValidatingReaderCompatibilityMode = value; } } internal override IDtdInfo DtdInfo { get { return _impl.DtdInfo; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Python.Runtime { public class Finalizer { public class CollectArgs : EventArgs { public int ObjectCount { get; set; } } public class ErrorArgs : EventArgs { public Exception Error { get; set; } } public static readonly Finalizer Instance = new Finalizer(); public event EventHandler<CollectArgs> CollectOnce; public event EventHandler<ErrorArgs> ErrorHandler; public int Threshold { get; set; } public bool Enable { get; set; } private ConcurrentQueue<IPyDisposable> _objQueue = new ConcurrentQueue<IPyDisposable>(); private bool _pending = false; private readonly object _collectingLock = new object(); private Task _finalizerTask; #region FINALIZER_CHECK #if FINALIZER_CHECK private readonly object _queueLock = new object(); public bool RefCountValidationEnabled { get; set; } = true; #else public readonly bool RefCountValidationEnabled = false; #endif // Keep these declarations for compat even no FINALIZER_CHECK public class IncorrectFinalizeArgs : EventArgs { public IntPtr Handle { get; internal set; } public ICollection<IPyDisposable> ImpactedObjects { get; internal set; } } public class IncorrectRefCountException : Exception { public IntPtr PyPtr { get; internal set; } private string _message; public override string Message => _message; public IncorrectRefCountException(IntPtr ptr) { PyPtr = ptr; IntPtr pyname = Runtime.PyObject_Unicode(PyPtr); string name = Runtime.GetManagedString(pyname); Runtime.XDecref(pyname); _message = $"{name} may has a incorrect ref count"; } } public delegate bool IncorrectRefCntHandler(object sender, IncorrectFinalizeArgs e); public event IncorrectRefCntHandler IncorrectRefCntResolver; public bool ThrowIfUnhandleIncorrectRefCount { get; set; } = true; #endregion private Finalizer() { Enable = true; Threshold = 200; } public void Collect(bool forceDispose = true) { if (Instance._finalizerTask != null && !Instance._finalizerTask.IsCompleted) { var ts = PythonEngine.BeginAllowThreads(); Instance._finalizerTask.Wait(); PythonEngine.EndAllowThreads(ts); } else if (forceDispose) { Instance.DisposeAll(); } } public List<WeakReference> GetCollectedObjects() { return _objQueue.Select(T => new WeakReference(T)).ToList(); } internal void AddFinalizedObject(IPyDisposable obj) { if (!Enable) { return; } if (Runtime.Py_IsInitialized() == 0) { // XXX: Memory will leak if a PyObject finalized after Python shutdown, // for avoiding that case, user should call GC.Collect manual before shutdown. return; } #if FINALIZER_CHECK lock (_queueLock) #endif { _objQueue.Enqueue(obj); } GC.ReRegisterForFinalize(obj); if (!_pending && _objQueue.Count >= Threshold) { AddPendingCollect(); } } internal static void Shutdown() { if (Runtime.Py_IsInitialized() == 0) { Instance._objQueue = new ConcurrentQueue<IPyDisposable>(); return; } Instance.Collect(forceDispose: true); } private void AddPendingCollect() { if(Monitor.TryEnter(_collectingLock)) { try { if (!_pending) { _pending = true; // should already be complete but just in case _finalizerTask?.Wait(); _finalizerTask = Task.Factory.StartNew(() => { using (Py.GIL()) { Instance.DisposeAll(); _pending = false; } }); } } finally { Monitor.Exit(_collectingLock); } } } private void DisposeAll() { CollectOnce?.Invoke(this, new CollectArgs() { ObjectCount = _objQueue.Count }); #if FINALIZER_CHECK lock (_queueLock) #endif { #if FINALIZER_CHECK ValidateRefCount(); #endif IPyDisposable obj; while (_objQueue.TryDequeue(out obj)) { try { obj.Dispose(); Runtime.CheckExceptionOccurred(); } catch (Exception e) { // We should not bother the main thread ErrorHandler?.Invoke(this, new ErrorArgs() { Error = e }); } } } } #if FINALIZER_CHECK private void ValidateRefCount() { if (!RefCountValidationEnabled) { return; } var counter = new Dictionary<IntPtr, long>(); var holdRefs = new Dictionary<IntPtr, long>(); var indexer = new Dictionary<IntPtr, List<IPyDisposable>>(); foreach (var obj in _objQueue) { IntPtr[] handles = obj.GetTrackedHandles(); foreach (var handle in handles) { if (handle == IntPtr.Zero) { continue; } if (!counter.ContainsKey(handle)) { counter[handle] = 0; } counter[handle]++; if (!holdRefs.ContainsKey(handle)) { holdRefs[handle] = Runtime.Refcount(handle); } List<IPyDisposable> objs; if (!indexer.TryGetValue(handle, out objs)) { objs = new List<IPyDisposable>(); indexer.Add(handle, objs); } objs.Add(obj); } } foreach (var pair in counter) { IntPtr handle = pair.Key; long cnt = pair.Value; // Tracked handle's ref count is larger than the object's holds // it may take an unspecified behaviour if it decref in Dispose if (cnt > holdRefs[handle]) { var args = new IncorrectFinalizeArgs() { Handle = handle, ImpactedObjects = indexer[handle] }; bool handled = false; if (IncorrectRefCntResolver != null) { var funcList = IncorrectRefCntResolver.GetInvocationList(); foreach (IncorrectRefCntHandler func in funcList) { if (func(this, args)) { handled = true; break; } } } if (!handled && ThrowIfUnhandleIncorrectRefCount) { throw new IncorrectRefCountException(handle); } } // Make sure no other references for PyObjects after this method indexer[handle].Clear(); } indexer.Clear(); } #endif } }
#region License // // CacheLabel.cs July 2007 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // 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 #region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>CacheLabel</c> object is used to acquire details from an /// inner label object so that details can be retrieved repeatedly without /// the need to perform any logic for extracting the values. This ensures /// that a class XML schema requires only initial processing the first /// time the class XML schema is required. /// </summary> class CacheLabel : Label { /// <summary> /// This is the decorator that is associated with the label. /// </summary> private readonly Decorator decorator; /// <summary> /// This is the contact used to set and get the value for the node. /// </summary> private readonly Contact contact; /// <summary> /// This is used to represent the label class that this will use. /// </summary> private readonly Class type; /// <summary> /// This is used to represent the name of the entry item use. /// </summary> private readonly String entry; /// <summary> /// This is used to represent the name override for the annotation. /// </summary> private readonly String override; /// <summary> /// This is used to represent the name of the annotated element. /// </summary> private readonly String name; /// <summary> /// This is the label the this cache is wrapping the values for. /// </summary> private readonly Label label; /// <summary> /// This is used to represent the dependent type to be used. /// </summary> private readonly Type depend; /// <summary> /// This is used to represent whether the data is written as data. /// </summary> private readonly bool data; /// <summary> /// This is used to determine the styling of the label name. /// </summary> private readonly bool attribute; /// <summary> /// This is used to represent whether the entity is required or not. /// </summary> private readonly bool required; /// <summary> /// This is used to determine if the label represents a collection. /// </summary> private readonly bool collection; /// <summary> /// This is used to determine whether the entity is inline or not. /// </summary> private readonly bool inline; /// <summary> /// Constructor for the <c>CacheLabel</c> object. This is used /// to create a <c>Label</c> that acquires details from another /// label in such a way that any logic involved in acquiring details /// is performed only once. /// </summary> /// <param name="label"> /// this is the label to acquire the details from /// </param> public CacheLabel(Label label) { this.decorator = label.Decorator; this.attribute = label.IsAttribute(); this.collection = label.IsCollection(); this.contact = label.Contact; this.depend = label.Dependent; this.required = label.IsRequired(); this.override = label.Override; this.inline = label.IsInline(); this.type = label.Type; this.name = label.GetName(); this.entry = label.Entry; this.data = label.IsData(); this.label = label; } /// <summary> /// This is used to acquire the contact object for this label. The /// contact retrieved can be used to set any object or primitive that /// has been deserialized, and can also be used to acquire values to /// be serialized in the case of object persistence. All contacts /// that are retrieved from this method will be accessible. /// </summary> /// <returns> /// returns the field that this label is representing /// </returns> public Contact Contact { get { return contact; } } //public Contact GetContact() { // return contact; //} /// This is used to acquire the <c>Decorator</c> for this. /// A decorator is an object that adds various details to the /// node without changing the overall structure of the node. For /// example comments and namespaces can be added to the node with /// a decorator as they do not affect the deserialization. /// </summary> /// <returns> /// this returns the decorator associated with this /// </returns> public Decorator Decorator { get { return decorator; } } //public Decorator GetDecorator() { // return decorator; //} /// This method returns a <c>Converter</c> which can be used to /// convert an XML node into an object value and vice versa. The /// converter requires only the context object in order to perform /// serialization or deserialization of the provided XML node. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns an object that is used for conversion /// </returns> public Converter GetConverter(Context context) { return label.GetConverter(context); } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <param name="context"> /// this is the context used to style the name /// </param> /// <returns> /// returns the name that is used for the XML property /// </returns> public String GetName(Context context) { Style style = context.getStyle(); if(attribute) { return style.getAttribute(name); } return style.getElement(name); } /// <summary> /// This is used to provide a configured empty value used when the /// annotated value is null. This ensures that XML can be created /// with required details regardless of whether values are null or /// not. It also provides a means for sensible default values. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns the string to use for default values /// </returns> public Object GetEmpty(Context context) { return label.GetEmpty(context); } /// <summary> /// This returns the dependent type for the annotation. This type /// is the type other than the annotated field or method type that /// the label depends on. For the <c>ElementList</c> and /// the <c>ElementArray</c> this is the component type that /// is deserialized individually and inserted into the container. /// </summary> /// <returns> /// this is the type that the annotation depends on /// </returns> public Type Dependent { get { return depend; } } //public Type GetDependent() { // return depend; //} /// This is used to either provide the entry value provided within /// the annotation or compute a entry value. If the entry string /// is not provided the the entry value is calculated as the type /// of primitive the object is as a simplified class name. /// </summary> /// <returns> /// this returns the name of the XML entry element used /// </returns> public String Entry { get { return entry; } } //public String GetEntry() { // return entry; //} /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String Name { get { return name; } } //public String GetName() { // return name; //} /// This is used to acquire the name of the element or attribute /// as taken from the annotation. If the element or attribute /// explicitly specifies a name then that name is used for the /// XML element or attribute used. If however no overriding name /// is provided then the method or field is used for the name. /// </summary> /// <returns> /// returns the name of the annotation for the contact /// </returns> public String Override { get { return override; } } //public String GetOverride() { // return override; //} /// This acts as a convenience method used to determine the type of /// the field this represents. This is used when an object is written /// to XML. It determines whether a <c>class</c> attribute /// is required within the serialized XML element, that is, if the /// class returned by this is different from the actual value of the /// object to be serialized then that type needs to be remembered. /// </summary> /// <returns> /// this returns the type of the field class /// </returns> public Class Type { get { return type; } } //public Class GetType() { // return type; //} /// This is used to determine whether the annotation requires it /// and its children to be written as a CDATA block. This is done /// when a primitive or other such element requires a text value /// and that value needs to be encapsulated within a CDATA block. /// </summary> /// <returns> /// this returns true if the element requires CDATA /// </returns> public bool IsData() { return data; } /// <summary> /// This is used to determine whether the label represents an /// inline XML entity. The <c>ElementList</c> annotation /// and the <c>Text</c> annotation represent inline /// items. This means that they contain no containing element /// and so can not specify overrides or special attributes. /// </summary> /// <returns> /// this returns true if the annotation is inline /// </returns> public bool IsInline() { return inline; } /// <summary> /// This method is used to determine if the label represents an /// attribute. This is used to style the name so that elements /// are styled as elements and attributes are styled as required. /// </summary> /// <returns> /// this is used to determine if this is an attribute /// </returns> public bool IsAttribute() { return attribute; } /// <summary> /// This is used to determine if the label is a collection. If the /// label represents a collection then any original assignment to /// the field or method can be written to without the need to /// create a new collection. This allows obscure collections to be /// used and also allows initial entries to be maintained. /// </summary> /// <returns> /// true if the label represents a collection value /// </returns> public bool IsCollection() { return collection; } /// <summary> /// Determines whether the XML attribute or element is required. /// This ensures that if an XML element is missing from a document /// that deserialization can continue. Also, in the process of /// serialization, if a value is null it does not need to be /// written to the resulting XML document. /// </summary> /// <returns> /// true if the label represents a some required data /// </returns> public bool IsRequired() { return required; } /// <summary> /// This is used to describe the annotation and method or field /// that this label represents. This is used to provide error /// messages that can be used to debug issues that occur when /// processing a method. This should provide enough information /// such that the problem can be isolated correctly. /// </summary> /// <returns> /// this returns a string representation of the label /// </returns> public String ToString() { return label.ToString(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { // Soon to be dismissed [Serializable] public class ChildAgentDataUpdate { public Guid ActiveGroupID; public Guid AgentID; public bool alwaysrun; public float AVHeight; public Vector3 cameraPosition; public float drawdistance; public float godlevel; public uint GroupAccess; public Vector3 Position; public ulong regionHandle; public byte[] throttles; public Vector3 Velocity; public ChildAgentDataUpdate() { } } public interface IAgentData { UUID AgentID { get; set; } OSDMap Pack(); void Unpack(OSDMap map); } /// <summary> /// Replacement for ChildAgentDataUpdate. Used over RESTComms and LocalComms. /// </summary> public class AgentPosition : IAgentData { private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public ulong RegionHandle; public uint CircuitCode; public UUID SessionID; public float Far; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; // This probably shouldn't be here public byte[] Throttles; public OSDMap Pack() { OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentPosition"); args["region_handle"] = OSD.FromString(RegionHandle.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["far"] = OSD.FromReal(Far); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); return args; } public void Unpack(OSDMap args) { if (args.ContainsKey("region_handle")) UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle); if (args["circuit_code"] != null) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args["agent_uuid"] != null) AgentID = args["agent_uuid"].AsUUID(); if (args["session_uuid"] != null) SessionID = args["session_uuid"].AsUUID(); if (args["position"] != null) Vector3.TryParse(args["position"].AsString(), out Position); if (args["velocity"] != null) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args["center"] != null) Vector3.TryParse(args["center"].AsString(), out Center); if (args["size"] != null) Vector3.TryParse(args["size"].AsString(), out Size); if (args["at_axis"] != null) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args["left_axis"] != null) Vector3.TryParse(args["left_axis"].AsString(), out AtAxis); if (args["up_axis"] != null) Vector3.TryParse(args["up_axis"].AsString(), out AtAxis); if (args["changed_grid"] != null) ChangedGrid = args["changed_grid"].AsBoolean(); if (args["far"] != null) Far = (float)(args["far"].AsReal()); if (args["throttles"] != null) Throttles = args["throttles"].AsBinary(); } /// <summary> /// Soon to be decommissioned /// </summary> /// <param name="cAgent"></param> public void CopyFrom(ChildAgentDataUpdate cAgent) { AgentID = new UUID(cAgent.AgentID); // next: ??? Size = new Vector3(); Size.Z = cAgent.AVHeight; Center = cAgent.cameraPosition; Far = cAgent.drawdistance; Position = cAgent.Position; RegionHandle = cAgent.regionHandle; Throttles = cAgent.throttles; Velocity = cAgent.Velocity; } } public class AgentGroupData { public UUID GroupID; public ulong GroupPowers; public bool AcceptNotices; public AgentGroupData(UUID id, ulong powers, bool notices) { GroupID = id; GroupPowers = powers; AcceptNotices = notices; } public AgentGroupData(OSDMap args) { UnpackUpdateMessage(args); } public OSDMap PackUpdateMessage() { OSDMap groupdata = new OSDMap(); groupdata["group_id"] = OSD.FromUUID(GroupID); groupdata["group_powers"] = OSD.FromString(GroupPowers.ToString()); groupdata["accept_notices"] = OSD.FromBoolean(AcceptNotices); return groupdata; } public void UnpackUpdateMessage(OSDMap args) { if (args["group_id"] != null) GroupID = args["group_id"].AsUUID(); if (args["group_powers"] != null) UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers); if (args["accept_notices"] != null) AcceptNotices = args["accept_notices"].AsBoolean(); } } public class AttachmentData { public int AttachPoint; public UUID ItemID; public UUID AssetID; public AttachmentData(int point, UUID item, UUID asset) { AttachPoint = point; ItemID = item; AssetID = asset; } public AttachmentData(OSDMap args) { UnpackUpdateMessage(args); } public OSDMap PackUpdateMessage() { OSDMap attachdata = new OSDMap(); attachdata["point"] = OSD.FromInteger(AttachPoint); attachdata["item"] = OSD.FromUUID(ItemID); attachdata["asset"] = OSD.FromUUID(AssetID); return attachdata; } public void UnpackUpdateMessage(OSDMap args) { if (args["point"] != null) AttachPoint = args["point"].AsInteger(); if (args["item"] != null) ItemID = args["item"].AsUUID(); if (args["asset"] != null) AssetID = args["asset"].AsUUID(); } } public class AgentData : IAgentData { private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public ulong RegionHandle; public uint CircuitCode; public UUID SessionID; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; public float Far; public float Aspect; //public int[] Throttles; public byte[] Throttles; public uint LocomotionState; public Quaternion HeadRotation; public Quaternion BodyRotation; public uint ControlFlags; public float EnergyLevel; public Byte GodLevel; public bool AlwaysRun; public UUID PreyAgent; public Byte AgentAccess; public UUID ActiveGroupID; public AgentGroupData[] Groups; public Animation[] Anims; public UUID GranterID; // Appearance public byte[] AgentTextures; public byte[] VisualParams; public UUID[] Wearables; public AttachmentData[] Attachments; public string CallbackURI; public virtual OSDMap Pack() { OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentData"); args["region_handle"] = OSD.FromString(RegionHandle.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); args["far"] = OSD.FromReal(Far); args["aspect"] = OSD.FromReal(Aspect); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); args["locomotion_state"] = OSD.FromString(LocomotionState.ToString()); args["head_rotation"] = OSD.FromString(HeadRotation.ToString()); args["body_rotation"] = OSD.FromString(BodyRotation.ToString()); args["control_flags"] = OSD.FromString(ControlFlags.ToString()); args["energy_level"] = OSD.FromReal(EnergyLevel); args["god_level"] = OSD.FromString(GodLevel.ToString()); args["always_run"] = OSD.FromBoolean(AlwaysRun); args["prey_agent"] = OSD.FromUUID(PreyAgent); args["agent_access"] = OSD.FromString(AgentAccess.ToString()); args["active_group_id"] = OSD.FromUUID(ActiveGroupID); if ((Groups != null) && (Groups.Length > 0)) { OSDArray groups = new OSDArray(Groups.Length); foreach (AgentGroupData agd in Groups) groups.Add(agd.PackUpdateMessage()); args["groups"] = groups; } if ((Anims != null) && (Anims.Length > 0)) { OSDArray anims = new OSDArray(Anims.Length); foreach (Animation aanim in Anims) anims.Add(aanim.PackUpdateMessage()); args["animations"] = anims; } //if ((AgentTextures != null) && (AgentTextures.Length > 0)) //{ // OSDArray textures = new OSDArray(AgentTextures.Length); // foreach (UUID uuid in AgentTextures) // textures.Add(OSD.FromUUID(uuid)); // args["agent_textures"] = textures; //} if ((AgentTextures != null) && (AgentTextures.Length > 0)) args["texture_entry"] = OSD.FromBinary(AgentTextures); if ((VisualParams != null) && (VisualParams.Length > 0)) args["visual_params"] = OSD.FromBinary(VisualParams); // We might not pass this in all cases... if ((Wearables != null) && (Wearables.Length > 0)) { OSDArray wears = new OSDArray(Wearables.Length); foreach (UUID uuid in Wearables) wears.Add(OSD.FromUUID(uuid)); args["wearables"] = wears; } if ((Attachments != null) && (Attachments.Length > 0)) { OSDArray attachs = new OSDArray(Attachments.Length); foreach (AttachmentData att in Attachments) attachs.Add(att.PackUpdateMessage()); args["attachments"] = attachs; } if ((CallbackURI != null) && (!CallbackURI.Equals(""))) args["callback_uri"] = OSD.FromString(CallbackURI); return args; } /// <summary> /// Deserialization of agent data. /// Avoiding reflection makes it painful to write, but that's the price! /// </summary> /// <param name="hash"></param> public virtual void Unpack(OSDMap args) { if (args.ContainsKey("region_handle")) UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle); if (args["circuit_code"] != null) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args["agent_uuid"] != null) AgentID = args["agent_uuid"].AsUUID(); if (args["session_uuid"] != null) SessionID = args["session_uuid"].AsUUID(); if (args["position"] != null) Vector3.TryParse(args["position"].AsString(), out Position); if (args["velocity"] != null) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args["center"] != null) Vector3.TryParse(args["center"].AsString(), out Center); if (args["size"] != null) Vector3.TryParse(args["size"].AsString(), out Size); if (args["at_axis"] != null) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args["left_axis"] != null) Vector3.TryParse(args["left_axis"].AsString(), out AtAxis); if (args["up_axis"] != null) Vector3.TryParse(args["up_axis"].AsString(), out AtAxis); if (args["changed_grid"] != null) ChangedGrid = args["changed_grid"].AsBoolean(); if (args["far"] != null) Far = (float)(args["far"].AsReal()); if (args["aspect"] != null) Aspect = (float)args["aspect"].AsReal(); if (args["throttles"] != null) Throttles = args["throttles"].AsBinary(); if (args["locomotion_state"] != null) UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState); if (args["head_rotation"] != null) Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation); if (args["body_rotation"] != null) Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation); if (args["control_flags"] != null) UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags); if (args["energy_level"] != null) EnergyLevel = (float)(args["energy_level"].AsReal()); if (args["god_level"] != null) Byte.TryParse(args["god_level"].AsString(), out GodLevel); if (args["always_run"] != null) AlwaysRun = args["always_run"].AsBoolean(); if (args["prey_agent"] != null) PreyAgent = args["prey_agent"].AsUUID(); if (args["agent_access"] != null) Byte.TryParse(args["agent_access"].AsString(), out AgentAccess); if (args["active_group_id"] != null) ActiveGroupID = args["active_group_id"].AsUUID(); if ((args["groups"] != null) && (args["groups"]).Type == OSDType.Array) { OSDArray groups = (OSDArray)(args["groups"]); Groups = new AgentGroupData[groups.Count]; int i = 0; foreach (OSD o in groups) { if (o.Type == OSDType.Map) { Groups[i++] = new AgentGroupData((OSDMap)o); } } } if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array) { OSDArray anims = (OSDArray)(args["animations"]); Anims = new Animation[anims.Count]; int i = 0; foreach (OSD o in anims) { if (o.Type == OSDType.Map) { Anims[i++] = new Animation((OSDMap)o); } } } //if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array) //{ // OSDArray textures = (OSDArray)(args["agent_textures"]); // AgentTextures = new UUID[textures.Count]; // int i = 0; // foreach (OSD o in textures) // AgentTextures[i++] = o.AsUUID(); //} if (args["texture_entry"] != null) AgentTextures = args["texture_entry"].AsBinary(); if (args["visual_params"] != null) VisualParams = args["visual_params"].AsBinary(); if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array) { OSDArray wears = (OSDArray)(args["wearables"]); Wearables = new UUID[wears.Count]; int i = 0; foreach (OSD o in wears) Wearables[i++] = o.AsUUID(); } if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array) { OSDArray attachs = (OSDArray)(args["attachments"]); Attachments = new AttachmentData[attachs.Count]; int i = 0; foreach (OSD o in attachs) { if (o.Type == OSDType.Map) { Attachments[i++] = new AttachmentData((OSDMap)o); } } } if (args["callback_uri"] != null) CallbackURI = args["callback_uri"].AsString(); } public AgentData() { } public AgentData(Hashtable hash) { //UnpackUpdateMessage(hash); } public void Dump() { System.Console.WriteLine("------------ AgentData ------------"); System.Console.WriteLine("UUID: " + AgentID); System.Console.WriteLine("Region: " + RegionHandle); System.Console.WriteLine("Position: " + Position); } } public class CompleteAgentData : AgentData { public override OSDMap Pack() { return base.Pack(); } public override void Unpack(OSDMap map) { base.Unpack(map); } } }
// // EqualizerManager.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Alexander Hixon <hixon.alexander@mediati.org> // // Copyright 2006-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.IO; using System.Xml; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Json; using Banshee.Base; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; namespace Banshee.Equalizer { public class EqualizerManager : IEnumerable<EqualizerSetting>, IEnumerable { private static string legacy_xml_path = System.IO.Path.Combine ( Paths.ApplicationData, "equalizers.xml"); private static EqualizerManager instance; public static EqualizerManager Instance { get { if (instance == null) { instance = new EqualizerManager (System.IO.Path.Combine ( Paths.ApplicationData, "equalizers.json")); } return instance; } } private List<EqualizerSetting> equalizers = new List<EqualizerSetting> (); public string Path { get; private set; } public EqualizerSetting SelectedEqualizer { get; private set; } public delegate void EqualizerSettingEventHandler (object o, Hyena.EventArgs<EqualizerSetting> args); public event EqualizerSettingEventHandler EqualizerAdded; public event EqualizerSettingEventHandler EqualizerRemoved; public event EqualizerSettingEventHandler EqualizerChanged; private EqualizerManager (string path) { Path = path; try { Load (); } catch (Exception e) { Log.Exception ("Failed to load equalizer", e); } } public void Add (EqualizerSetting eq) { eq.Changed += OnEqualizerSettingChanged; equalizers.Add (eq); QueueSave (); OnEqualizerAdded (eq); } public void Remove (EqualizerSetting eq) { Remove (eq, true); } private void Remove (EqualizerSetting eq, bool shouldQueueSave) { if (eq == null || eq.IsReadOnly) { return; } eq.Changed -= OnEqualizerSettingChanged; equalizers.Remove (eq); OnEqualizerRemoved (eq); if (shouldQueueSave) { QueueSave (); } } public void Clear () { while (equalizers.Count > 0) { Remove (equalizers[0], false); } QueueSave (); } public EqualizerSetting Find (string name) { return String.IsNullOrEmpty (name) ? null : equalizers.Find (eq => eq.Name == name); } public void Select () { Select (PresetSchema.Get ()); } public void Select (string name) { Select (Find (name)); } public void Select (EqualizerSetting eq) { if (SelectedEqualizer == eq) { return; } bool sync = SelectedEqualizer != eq; SelectedEqualizer = eq; if (eq != null) { PresetSchema.Set (eq.Name); Log.DebugFormat ("Selected equalizer: {0}", eq.Name); } if (IsActive && sync) { FlushToEngine (eq); } } private void FlushToEngine (EqualizerSetting eq) { if (eq == null) { var engine_eq = (IEqualizer)ServiceManager.PlayerEngine.ActiveEngine; engine_eq.AmplifierLevel = 0; for (uint i = 0; i < engine_eq.EqualizerFrequencies.Length; i++) { engine_eq.SetEqualizerGain (i, 0); } Log.DebugFormat ("Disabled equalizer"); } else { eq.FlushToEngine (); Log.DebugFormat ("Syncing equalizer to engine: {0}", eq.Name); } } public bool IsActive { get { return EnabledSchema.Get (); } set { EnabledSchema.Set (value); if (value) { if (SelectedEqualizer != null) { FlushToEngine (SelectedEqualizer); } } else { FlushToEngine (null); } } } public void Load () { var timer = Log.DebugTimerStart (); if (equalizers.Count > 0) { Clear (); } try { if (Banshee.IO.File.Exists (new SafeUri (Path))) { using (var reader = new StreamReader (Path)) { var deserializer = new Deserializer (reader); foreach (var node in (JsonArray)deserializer.Deserialize ()) { var eq_data = (JsonObject)node; var name = (string)eq_data["name"]; var preamp = Convert.ToDouble (eq_data["preamp"]); var bands = (JsonArray)eq_data["bands"]; var eq = new EqualizerSetting (this, name); eq.SetAmplifierLevel (preamp, false); for (uint band = 0; band < bands.Count; band++) { eq.SetGain (band, Convert.ToDouble (bands[(int)band]), false); } Add (eq); } } } else if (Banshee.IO.File.Exists (new SafeUri (legacy_xml_path))) { try { using (var reader = new XmlTextReader (legacy_xml_path)) { if (reader.ReadToDescendant ("equalizers")) { while (reader.ReadToFollowing ("equalizer")) { var eq = new EqualizerSetting (this, reader["name"]); while (reader.Read () && !(reader.NodeType == XmlNodeType.EndElement && reader.Name == "equalizer")) { if (reader.NodeType != XmlNodeType.Element) { continue; } else if (reader.Name == "preamp") { eq.SetAmplifierLevel (reader.ReadElementContentAsDouble (), false); } else if (reader.Name == "band") { eq.SetGain (Convert.ToUInt32 (reader["num"]), reader.ReadElementContentAsDouble (), false); } } Add (eq); } } } Log.Information ("Converted legacy XML equalizer presets to new JSON format"); } catch (Exception xe) { Log.Exception ("Could not load equalizers.xml", xe); } } } catch (Exception e) { Log.Exception ("Could not load equalizers.json", e); } Log.DebugTimerPrint (timer, "Loaded equalizer presets: {0}"); equalizers.AddRange (GetDefaultEqualizers ()); Select (); } private IEnumerable<EqualizerSetting> GetDefaultEqualizers () { yield return new EqualizerSetting (this, Catalog.GetString ("Classical"), 0, new [] { 0, 0, 0, 0, 0, 0, -7.2, -7.2, -7.2, -9.6 }); yield return new EqualizerSetting (this, Catalog.GetString ("Club"), 0, new [] { 0, 0, 8, 5.6, 5.6, 5.6, 3.2, 0, 0, 0 }); yield return new EqualizerSetting (this, Catalog.GetString ("Dance"), -1.1, new [] { 9.6, 7.2, 2.4, -1.1, -1.1, -5.6, -7.2, -7.2, -1.1, -1.1 }); yield return new EqualizerSetting (this, Catalog.GetString ("Full Bass"), -1.1, new [] { -8, 9.6, 9.6, 5.6, 1.6, -4, -8, -10.4, -11.2, -11.2 }); yield return new EqualizerSetting (this, Catalog.GetString ("Full Bass and Treble"), -1.1, new [] { 7.2, 5.6, -1.1, -7.2, -4.8, 1.6, 8, 11.2, 12, 12 }); yield return new EqualizerSetting (this, Catalog.GetString ("Full Treble"), -1.1, new [] { -9.6, -9.6, -9.6, -4, 2.4, 11.2, 11.5, 11.8, 11.8, 12 }); yield return new EqualizerSetting (this, Catalog.GetString ("Laptop Speakers and Headphones"), -1.1, new [] { 4.8, 11.2, 5.6, -3.2, -2.4, 1.6, 4.8, 9.6, 11.9, 11.9 }); yield return new EqualizerSetting (this, Catalog.GetString ("Large Hall"), -1.1, new [] { 10.4, 10.4, 5.6, 5.6, -1.1, -4.8, -4.8, -4.8, -1.1, -1.1 }); yield return new EqualizerSetting (this, Catalog.GetString ("Live"), -1.1, new [] { -4.8, -1.1, 4, 5.6, 5.6, 5.6, 4, 2.4, 2.4, 2.4 }); yield return new EqualizerSetting (this, Catalog.GetString ("Party"), -1.1, new [] { 7.2, 7.2, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, 7.2, 7.2 }); yield return new EqualizerSetting (this, Catalog.GetString ("Pop"), -1.1, new [] { -1.6, 4.8, 7.2, 8, 5.6, -1.1, -2.4, -2.4, -1.6, -1.6 }); yield return new EqualizerSetting (this, Catalog.GetString ("Reggae"), -1.1, new [] { -1.1, -1.1, -1.1, -5.6, -1.1, 6.4, 6.4, -1.1, -1.1, -1.1 }); yield return new EqualizerSetting (this, Catalog.GetString ("Rock"), -1.1, new [] { 8, 4.8, -5.6, -8, -3.2, 4, 8.8, 11.2, 11.2, 11.2 }); yield return new EqualizerSetting (this, Catalog.GetString ("Ska"), -1.1, new [] { -2.4, -4.8, -4, -1.1, 4, 5.6, 8.8, 9.6, 11.2, 9.6 }); yield return new EqualizerSetting (this, Catalog.GetString ("Smiley Face Curve"), -7, new [] { 12, 8, 6, 3, 0.0, 0.0, 3, 6, 8, 12 }); yield return new EqualizerSetting (this, Catalog.GetString ("Soft"), -1.1, new [] { 4.8, 1.6, -1.1, -2.4, -1.1, 4, 8, 9.6, 11.2, 12, }); yield return new EqualizerSetting (this, Catalog.GetString ("Soft Rock"), -1.1, new [] { 4, 4, 2.4, -1.1, -4, -5.6, -3.2, -1.1, 2.4, 8.8, }); yield return new EqualizerSetting (this, Catalog.GetString ("Techno"), -1.1, new [] { 8, 5.6, -1.1, -5.6, -4.8, -1.1, 8, 9.6, 9.6, 8.8 }); } public void Save () { try { using (var writer = new StreamWriter (Path)) { writer.Write ("["); writer.WriteLine (); for (int i = 0; i < equalizers.Count; i++) { if (equalizers[i].IsReadOnly) { continue; } writer.Write (equalizers[i]); if (i < equalizers.Count - 1) { writer.Write (","); } writer.WriteLine (); } writer.Write ("]"); } Log.Debug ("EqualizerManager", "Saved equalizers to disk"); } catch (Exception e) { Log.Exception ("Unable to save equalizers", e); } } protected virtual void OnEqualizerAdded (EqualizerSetting eq) { EqualizerSettingEventHandler handler = EqualizerAdded; if (handler != null) { handler (this, new EventArgs<EqualizerSetting> (eq)); } } protected virtual void OnEqualizerRemoved (EqualizerSetting eq) { EqualizerSettingEventHandler handler = EqualizerRemoved; if (handler != null) { handler (this, new EventArgs<EqualizerSetting> (eq)); } } protected virtual void OnEqualizerChanged (EqualizerSetting eq) { EqualizerSettingEventHandler handler = EqualizerChanged; if (handler != null) { handler (this, new EventArgs<EqualizerSetting> (eq)); } } private void OnEqualizerSettingChanged (object o, EventArgs args) { OnEqualizerChanged (o as EqualizerSetting); QueueSave (); } private uint queue_save_id = 0; private void QueueSave () { if (queue_save_id > 0) { return; } queue_save_id = GLib.Timeout.Add (2500, delegate { Save (); queue_save_id = 0; return false; }); } IEnumerator IEnumerable.GetEnumerator () { return equalizers.GetEnumerator (); } public IEnumerator<EqualizerSetting> GetEnumerator () { return equalizers.GetEnumerator (); } public static readonly SchemaEntry<bool> EnabledSchema = new SchemaEntry<bool> ( "player_engine", "equalizer_enabled", false, "Equalizer status", "Whether or not the equalizer is set to be enabled." ); public static readonly SchemaEntry<string> PresetSchema = new SchemaEntry<string> ( "player_engine", "equalizer_preset", "Rock", "Equalizer preset", "Default preset to load into equalizer." ); } }
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class GrainTimer : IGrainTimer { private Func<object, Task> asyncCallback; private AsyncTaskSafeTimer timer; private readonly TimeSpan dueTime; private readonly TimeSpan timerFrequency; private DateTime previousTickTime; private int totalNumTicks; private readonly ILogger logger; private Task currentlyExecutingTickTask; private readonly OrleansTaskScheduler scheduler; private readonly IActivationData activationData; public string Name { get; } private bool TimerAlreadyStopped { get { return timer == null || asyncCallback == null; } } private GrainTimer(OrleansTaskScheduler scheduler, IActivationData activationData, ILogger logger, Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name) { var ctxt = RuntimeContext.CurrentActivationContext; scheduler.CheckSchedulingContextValidity(ctxt); this.scheduler = scheduler; this.activationData = activationData; this.logger = logger; this.Name = name; this.asyncCallback = asyncCallback; timer = new AsyncTaskSafeTimer(logger, stateObj => TimerTick(stateObj, ctxt), state); this.dueTime = dueTime; timerFrequency = period; previousTickTime = DateTime.UtcNow; totalNumTicks = 0; } internal static GrainTimer FromTimerCallback( OrleansTaskScheduler scheduler, ILogger logger, TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period, string name = null) { return new GrainTimer( scheduler, null, logger, ob => { if (callback != null) callback(ob); return Task.CompletedTask; }, state, dueTime, period, name); } internal static IGrainTimer FromTaskCallback( OrleansTaskScheduler scheduler, ILogger logger, Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name = null, IActivationData activationData = null) { return new GrainTimer(scheduler, activationData, logger, asyncCallback, state, dueTime, period, name); } public void Start() { if (TimerAlreadyStopped) throw new ObjectDisposedException(String.Format("The timer {0} was already disposed.", GetFullName())); timer.Start(dueTime, timerFrequency); } public void Stop() { asyncCallback = null; } private async Task TimerTick(object state, ISchedulingContext context) { if (TimerAlreadyStopped) return; try { // Schedule call back to grain context await this.scheduler.QueueNamedTask(() => ForwardToAsyncCallback(state), context, this.Name); } catch (InvalidSchedulingContextException exc) { logger.Error(ErrorCode.Timer_InvalidContext, string.Format("Caught an InvalidSchedulingContextException on timer {0}, context is {1}. Going to dispose this timer!", GetFullName(), context), exc); DisposeTimer(); } } private async Task ForwardToAsyncCallback(object state) { // AsyncSafeTimer ensures that calls to this method are serialized. if (TimerAlreadyStopped) return; totalNumTicks++; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerBeforeCallback, "About to make timer callback for timer {0}", GetFullName()); try { RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake. currentlyExecutingTickTask = asyncCallback(state); await currentlyExecutingTickTask; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed timer callback for timer {0}", GetFullName()); } catch (Exception exc) { logger.Error( ErrorCode.Timer_GrainTimerCallbackError, string.Format( "Caught and ignored exception: {0} with mesagge: {1} thrown from timer callback {2}", exc.GetType(), exc.Message, GetFullName()), exc); } finally { previousTickTime = DateTime.UtcNow; currentlyExecutingTickTask = null; // if this is not a repeating timer, then we can // dispose of the timer. if (timerFrequency == Constants.INFINITE_TIMESPAN) DisposeTimer(); } } public Task GetCurrentlyExecutingTickTask() { return currentlyExecutingTickTask ?? Task.CompletedTask; } private string GetFullName() { var callbackTarget = string.Empty; var callbackMethodInfo = string.Empty; if (asyncCallback != null) { if (asyncCallback.Target != null) { callbackTarget = asyncCallback.Target.ToString(); } var methodInfo = asyncCallback.GetMethodInfo(); if (methodInfo != null) { callbackMethodInfo = methodInfo.ToString(); } } return string.Format("GrainTimer.{0} TimerCallbackHandler:{1}->{2}", Name == null ? "" : Name + ".", callbackTarget, callbackMethodInfo); } public int GetNumTicks() { return totalNumTicks; } // The reason we need to check CheckTimerFreeze on both the SafeTimer and this GrainTimer // is that SafeTimer may tick OK (no starvation by .NET thread pool), but then scheduler.QueueWorkItem // may not execute and starve this GrainTimer callback. public bool CheckTimerFreeze(DateTime lastCheckTime) { if (TimerAlreadyStopped) return true; // check underlying SafeTimer (checking that .NET thread pool does not starve this timer) if (!timer.CheckTimerFreeze(lastCheckTime, () => Name)) return false; // if SafeTimer failed the check, no need to check GrainTimer too, since it will fail as well. // check myself (checking that scheduler.QueueWorkItem does not starve this timer) return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks, dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, true); } public bool CheckTimerDelay() { return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks, dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, false); } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects. // Dispose() may be called multiple times protected virtual void Dispose(bool disposing) { if (disposing) DisposeTimer(); asyncCallback = null; } private void DisposeTimer() { var tmp = timer; if (tmp == null) return; Utils.SafeExecute(tmp.Dispose); timer = null; asyncCallback = null; activationData?.OnTimerDisposed(this); } #endregion } }
#region File Description //----------------------------------------------------------------------------- // CommandHistory.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion //----------------------------------------------------------------------------- // CommandHistory.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #region Using Statements using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Text; #endregion namespace Xna.Tools { /// <summary> /// This class provides Undo/Redo feature. /// </summary> public class CommandHistory { #region Properties /// <summary> /// Changed event that fired when command history changed. /// </summary> public event EventHandler Changed; /// <summary> /// It returns true if it can process undo; otherwise it returns false. /// </summary> public bool CanUndo { get { return commands.CanUndo; } } /// <summary> /// It returns true if it can process redo; otherwise it returns false. /// </summary> public bool CanRedo { get { return commands.CanRedo; } } #endregion #region Public Methods /// <summary> /// Make sure CommandHistory added as a service to given site. /// </summary> /// <param name="serviceProvider"></param> /// <remarks>You have to make sure added IServiceContainer to this /// serviceProvider.</remarks> public static CommandHistory EnsureHasService(IServiceProvider serviceProvider) { CommandHistory result = null; IServiceProvider sp = serviceProvider; if (sp != null) { // Add this CommandHistory service if given service // doesn't contains it. result = sp.GetService(typeof(CommandHistory)) as CommandHistory; if (result == null) { // If there are no service, added new instance. IServiceContainer s = sp.GetService(typeof(IServiceContainer)) as IServiceContainer; if (s == null) { throw new InvalidOperationException( CurveControlResources.RequireServiceContainer); } result = new CommandHistory(); s.AddService(typeof(CommandHistory), result); } } else { // If they don't have ISite, returns static instance. if (staticCommandHistory == null) staticCommandHistory = new CommandHistory(); result = staticCommandHistory; } return result; } /// <summary> /// Execute given command and added to history. /// </summary> /// <param name="command"></param> public void Do(ICommand command) { if (command == null) throw new ArgumentNullException("command"); command.Execute(); Add(command); } /// <summary> /// Add command to history. /// </summary> /// <param name="command"></param> public void Add(ICommand command) { DebugPrintCommand("Add", command); // Add given command to commands or recordingCommands. if (recordingCommands != null) { recordingCommands.Add(command); } else { commands.Add(command); if (Changed != null) Changed(this, EventArgs.Empty); } } /// <summary> /// Undo command. /// </summary> public void Undo() { if (recordingNestCount != 0) throw new InvalidOperationException(String.Format( CurveControlResources.CantExecuteCommandHistory, "Undo")); DebugPrintCommand("Undo", -1); commands.Undo(); if (Changed != null) Changed(this, EventArgs.Empty); } /// <summary> /// Redo command. /// </summary> public void Redo() { if (recordingNestCount != 0) throw new InvalidOperationException(String.Format( CurveControlResources.CantExecuteCommandHistory, "Redo")); DebugPrintCommand("Redo", 0); commands.Redo(); if (Changed != null) Changed(this, EventArgs.Empty); } /// <summary> /// Record multiple commands as one command. /// </summary> public void BeginRecordCommands() { if (recordingNestCount++ == 0) recordingCommands = new CommandCollection(); } /// <summary> /// Stop recording commands and added as a command. /// </summary> public void EndRecordCommands() { if (--recordingNestCount != 0) return; // Added recorded commands to commands. // If recording commands recored one command, we just add that command to // main commands. if (recordingCommands.Count != 0) { if (recordingCommands.Count == 1) commands.Add(recordingCommands[0]); else commands.Add(recordingCommands); if (Changed != null) Changed(this, EventArgs.Empty); } recordingCommands = null; } #endregion #region Private Members /// <summary> /// Main CommandQueue. /// </summary> CommandCollection commands = new CommandCollection(); /// <summary> /// Sub CommandQueue that uses for command recoording. /// </summary> CommandCollection recordingCommands = null; /// <summary> /// For keep tracking nested call of Begin/EndRecoord method. /// </summary> int recordingNestCount = 0; /// <summary> /// Static command history that only avilable when user doesn't provide /// ISite object. /// </summary> static CommandHistory staticCommandHistory = null; #endregion #region Debug Code [Conditional("DEBUG")] static void DebugPrintCommand(string prefix, ICommand command) { System.Diagnostics.Debugger.Log(0, "CmdHistory", String.Format("{0}:{1}\n", prefix, command.ToString())); CommandCollection cq = command as CommandCollection; if (cq != null) { for (int i = 0; i < cq.Count; ++i) { System.Diagnostics.Debugger.Log(0, "CmdHistory", String.Format(" [{0}]:{1}\n", i, cq[i].ToString())); } } } [Conditional("DEBUG")] private void DebugPrintCommand(string prefix, int offset) { DebugPrintCommand(prefix, commands[commands.Index + offset]); } #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F05Level111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="F05Level111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F04Level11"/> collection. /// </remarks> [Serializable] public partial class F05Level111ReChild : BusinessBase<F05Level111ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int cMarentID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1 Child Name.</value> public string Level_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F05Level111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="F05Level111ReChild"/> object.</returns> internal static F05Level111ReChild NewF05Level111ReChild() { return DataPortal.CreateChild<F05Level111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="F05Level111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F05Level111ReChild"/> object.</returns> internal static F05Level111ReChild GetF05Level111ReChild(SafeDataReader dr) { F05Level111ReChild obj = new F05Level111ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F05Level111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private F05Level111ReChild() { // 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="F05Level111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F05Level111ReChild"/> 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_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name")); cMarentID2 = dr.GetInt32("CMarentID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F05Level111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddF05Level111ReChild", 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_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="F05Level111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateF05Level111ReChild", 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_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="F05Level111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteF05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #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 } }
// 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 Xunit; namespace System.Tests { public partial class ByteTests { [Fact] public static void Ctor_Empty() { var b = new byte(); Assert.Equal(0, b); } [Fact] public static void Ctor_Value() { byte b = 41; Assert.Equal(41, b); } [Fact] public static void MaxValue() { Assert.Equal(0xFF, byte.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(0, byte.MinValue); } [Theory] [InlineData((byte)234, (byte)234, 0)] [InlineData((byte)234, byte.MinValue, 1)] [InlineData((byte)234, (byte)0, 1)] [InlineData((byte)234, (byte)123, 1)] [InlineData((byte)234, (byte)235, -1)] [InlineData((byte)234, byte.MaxValue, -1)] [InlineData((byte)234, null, 1)] public void CompareTo_Other_ReturnsExpected(byte i, object value, int expected) { if (value is byte byteValue) { Assert.Equal(expected, Math.Sign(i.CompareTo(byteValue))); } Assert.Equal(expected, Math.Sign(i.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotByte_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((byte)123).CompareTo(value)); } [Theory] [InlineData((byte)78, (byte)78, true)] [InlineData((byte)78, (byte)0, false)] [InlineData((byte)0, (byte)0, true)] [InlineData((byte)78, null, false)] [InlineData((byte)78, "78", false)] [InlineData((byte)78, 78, false)] public static void Equals(byte b, object obj, bool expected) { if (obj is byte b2) { Assert.Equal(expected, b.Equals(b2)); Assert.Equal(expected, b.GetHashCode().Equals(b2.GetHashCode())); Assert.Equal(b, b.GetHashCode()); } Assert.Equal(expected, b.Equals(obj)); } [Fact] public void GetTypeCode_Invoke_ReturnsByte() { Assert.Equal(TypeCode.Byte, ((byte)1).GetTypeCode()); } public static IEnumerable<object[]> ToString_TestData() { NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo; yield return new object[] { (byte)0, "G", emptyFormat, "0" }; yield return new object[] { (byte)123, "G", emptyFormat, "123" }; yield return new object[] { byte.MaxValue, "G", emptyFormat, "255" }; yield return new object[] { (byte)0x24, "x", emptyFormat, "24" }; yield return new object[] { (byte)24, "N", emptyFormat, string.Format("{0:N}", 24.00) }; NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.NegativeSign = "#"; customFormat.NumberDecimalSeparator = "~"; customFormat.NumberGroupSeparator = "*"; yield return new object[] { (byte)24, "N", customFormat, "24~00" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(byte b, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, b.ToString()); Assert.Equal(upperExpected, b.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, b.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, b.ToString(upperFormat)); Assert.Equal(lowerExpected, b.ToString(lowerFormat)); Assert.Equal(upperExpected, b.ToString(upperFormat, null)); Assert.Equal(lowerExpected, b.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, b.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, b.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { byte b = 123; Assert.Throws<FormatException>(() => b.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => b.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { NumberStyles defaultStyle = NumberStyles.Integer; NumberFormatInfo emptyFormat = new NumberFormatInfo(); NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.CurrencySymbol = "$"; yield return new object[] { "0", defaultStyle, null, (byte)0 }; yield return new object[] { "123", defaultStyle, null, (byte)123 }; yield return new object[] { "+123", defaultStyle, null, (byte)123 }; yield return new object[] { " 123 ", defaultStyle, null, (byte)123 }; yield return new object[] { "255", defaultStyle, null, (byte)255 }; yield return new object[] { "12", NumberStyles.HexNumber, null, (byte)0x12 }; yield return new object[] { "10", NumberStyles.AllowThousands, null, (byte)10 }; yield return new object[] { "123", defaultStyle, emptyFormat, (byte)123 }; yield return new object[] { "123", NumberStyles.Any, emptyFormat, (byte)123 }; yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (byte)0x12 }; yield return new object[] { "ab", NumberStyles.HexNumber, emptyFormat, (byte)0xab }; yield return new object[] { "AB", NumberStyles.HexNumber, null, (byte)0xab }; yield return new object[] { "$100", NumberStyles.Currency, customFormat, (byte)100 }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string value, NumberStyles style, IFormatProvider provider, byte expected) { byte result; // If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.True(byte.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, byte.Parse(value)); // If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (provider != null) { Assert.Equal(expected, byte.Parse(value, provider)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.True(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result)); Assert.Equal(expected, result); // If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (provider == null) { Assert.Equal(expected, byte.Parse(value, style)); } Assert.Equal(expected, byte.Parse(value, style, provider ?? new NumberFormatInfo())); } public static IEnumerable<object[]> Parse_Invalid_TestData() { NumberStyles defaultStyle = NumberStyles.Integer; NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.CurrencySymbol = "$"; customFormat.NumberDecimalSeparator = "."; yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) }; yield return new object[] { "", defaultStyle, null, typeof(FormatException) }; yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "ab", defaultStyle, null, typeof(FormatException) }; // Hex value yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses yield return new object[] { 100.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands yield return new object[] { 67.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "ab", NumberStyles.None, null, typeof(FormatException) }; // Hex value yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal yield return new object[] { "-1", defaultStyle, null, typeof(OverflowException) }; // < min value yield return new object[] { "256", defaultStyle, null, typeof(OverflowException) }; // > max value yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, typeof(OverflowException) }; // Parentheses = negative yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { byte result; // If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.False(byte.TryParse(value, out result)); Assert.Equal(default(byte), result); Assert.Throws(exceptionType, () => byte.Parse(value)); // If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (provider != null) { Assert.Throws(exceptionType, () => byte.Parse(value, provider)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.False(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result)); Assert.Equal(default(byte), result); // If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (provider == null) { Assert.Throws(exceptionType, () => byte.Parse(value, style)); } Assert.Throws(exceptionType, () => byte.Parse(value, style, provider ?? new NumberFormatInfo())); } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)] [InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName) { byte result = 0; AssertExtensions.Throws<ArgumentException>(paramName, () => byte.TryParse("1", style, null, out result)); Assert.Equal(default(byte), result); AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style)); AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style, null)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.BuildEngine.Shared; using System.Xml; namespace Microsoft.Build.UnitTests { [TestFixture] public class BuildItem_Tests { [Test] public void Basic() { BuildItem item = new BuildItem("i", "i1"); Assertion.AssertEquals("i", item.Name); Assertion.AssertEquals("i1", item.EvaluatedItemSpec); Assertion.AssertEquals("i1", item.FinalItemSpec); Assertion.AssertEquals("i1", item.FinalItemSpecEscaped); } [Test] [ExpectedException(typeof(InvalidProjectFileException))] public void InvalidNamespace() { string content = @" <i Include='i1' xmlns='XXX'> <m>m1</m> <n>n1</n> </i>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); CreateBuildItemFromXmlDocument(doc); } [Test] [ExpectedException(typeof(InvalidProjectFileException))] public void MissingInclude() { string content = @"<i xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); BuildItem item = CreateBuildItemFromXmlDocument(doc); } [Test] [ExpectedException(typeof(InvalidProjectFileException))] public void MissingInclude2() { string content = @"<i Exclude='x' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); BuildItem item = CreateBuildItemFromXmlDocument(doc); } [Test] public void Metadata() { string content = @" <i Include='i1' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <m>$(p)</m> <n>n1</n> </i>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); BuildItem item = CreateBuildItemFromXmlDocument(doc); Assertion.AssertEquals("i", item.Name); BuildPropertyGroup properties = new BuildPropertyGroup(); properties.SetProperty("p", "p1"); // Evaluated Expander expander = new Expander(properties, null, ExpanderOptions.ExpandAll); item.EvaluateAllItemMetadata(expander, ParserOptions.AllowPropertiesAndItemLists, null, null); Assertion.AssertEquals("p1", item.GetEvaluatedMetadata("m")); // Unevaluated Assertion.AssertEquals("$(p)", item.GetMetadata("m")); Assertion.AssertEquals("n1", item.GetMetadata("n")); // All custom metadata ArrayList metadataNames = new ArrayList(item.CustomMetadataNames); Assertion.Assert(metadataNames.Contains("n")); Assertion.Assert(metadataNames.Contains("m")); // Custom metadata count only Assertion.AssertEquals(2, item.CustomMetadataCount); // All metadata count Assertion.AssertEquals(2 + FileUtilities.ItemSpecModifiers.All.Length, item.MetadataCount); } [Test] public void MetadataIncludesItemDefinitionMetadata() { // Get an item of type "i" that has an item definition library // for type "i" that has default value "m1" for metadata "m" // and has value "n1" for metadata "n" BuildItem item = GetXmlBackedItemWithDefinitionLibrary(); // Evaluated Expander expander = new Expander(new BuildPropertyGroup(), null, ExpanderOptions.ExpandAll); item.EvaluateAllItemMetadata(expander, ParserOptions.AllowPropertiesAndItemLists, null, null); Assertion.AssertEquals("m1", item.GetEvaluatedMetadata("m")); Assertion.AssertEquals("n1", item.GetEvaluatedMetadata("n")); // Unevaluated Assertion.AssertEquals("m1", item.GetMetadata("m")); Assertion.AssertEquals("n1", item.GetMetadata("n")); // All custom metadata List<string> metadataNames = new List<string>((IList<string>)item.CustomMetadataNames); Assertion.AssertEquals("n", (string)metadataNames[0]); Assertion.AssertEquals("m", (string)metadataNames[1]); // Custom metadata count only Assertion.AssertEquals(3, item.CustomMetadataCount); // All metadata count Assertion.AssertEquals(item.CustomMetadataCount + FileUtilities.ItemSpecModifiers.All.Length, item.MetadataCount); } [Test] public void VirtualClone() { BuildItem item = new BuildItem("i", "i1"); BuildItem clone = item.Clone(); Assertion.AssertEquals("i", clone.Name); Assertion.AssertEquals("i1", clone.EvaluatedItemSpec); Assertion.AssertEquals("i1", clone.FinalItemSpec); Assertion.AssertEquals("i1", clone.FinalItemSpecEscaped); } [Test] public void RegularClone() { BuildItem item = GetXmlBackedItemWithDefinitionLibrary(); BuildItem clone = item.Clone(); Assertion.AssertEquals("i", clone.Name); Assertion.AssertEquals("i1", clone.EvaluatedItemSpec); Assertion.AssertEquals("i1", clone.FinalItemSpec); Assertion.AssertEquals("i1", clone.FinalItemSpecEscaped); // Make sure the itemdefinitionlibrary is cloned, too Assertion.AssertEquals("m1", clone.GetEvaluatedMetadata("m")); } [Test] public void CreateClonedParentedItem() { BuildItem parent = GetXmlBackedItemWithDefinitionLibrary(); BuildItem child = new BuildItem("i", "i2"); child.SetMetadata("n", "n2"); BuildItem clone = BuildItem.CreateClonedParentedItem(child, parent); Assertion.AssertEquals("i", clone.Name); Assertion.AssertEquals("i2", clone.EvaluatedItemSpec); Assertion.AssertEquals("i2", clone.FinalItemSpec); Assertion.AssertEquals("i2", clone.FinalItemSpecEscaped); // Make sure the itemdefinitionlibrary is cloned, too Assertion.AssertEquals("m1", clone.GetEvaluatedMetadata("m")); Assertion.AssertEquals("n1", clone.GetEvaluatedMetadata("n")); } internal static BuildItem GetXmlBackedItemWithDefinitionLibrary() { string content = @"<i xmlns='http://schemas.microsoft.com/developer/msbuild/2003' Include='i1'/>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); XmlElement groupElement = XmlTestUtilities.CreateBasicElement("ItemDefinitionGroup"); XmlElement itemElement = XmlTestUtilities.AddChildElement(groupElement, "i"); XmlElement metaElement = XmlTestUtilities.AddChildElementWithInnerText(itemElement, "m", "m1"); XmlElement metaElement2 = XmlTestUtilities.AddChildElementWithInnerText(itemElement, "o", "o1"); ItemDefinitionLibrary library = new ItemDefinitionLibrary(new Project()); library.Add(groupElement); library.Evaluate(null); BuildItem item = new BuildItem((XmlElement)doc.FirstChild, false, library); item.SetMetadata("n", "n1"); return item; } private static BuildItem CreateBuildItemFromXmlDocument(XmlDocument doc) { ItemDefinitionLibrary itemDefinitionLibrary = new ItemDefinitionLibrary(new Project()); itemDefinitionLibrary.Evaluate(new BuildPropertyGroup()); BuildItem item = new BuildItem((XmlElement)doc.FirstChild, false, itemDefinitionLibrary); return item; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class GoTweenConfig { private List<AbstractTweenProperty> _tweenProperties = new List<AbstractTweenProperty>( 2 ); public List<AbstractTweenProperty> tweenProperties { get { return _tweenProperties; } } public int id; // id for finding the Tween at a later time. multiple Tweens can have the same id public float delay; // how long should we delay before starting the Tween public int iterations = 1; // number of times to iterate. -1 will loop indefinitely public int timeScale = 1; public GoLoopType loopType = Go.defaultLoopType; public GoEaseType easeType = Go.defaultEaseType; public AnimationCurve easeCurve; public bool isPaused; public GoUpdateType propertyUpdateType = Go.defaultUpdateType; public bool isFrom; public Action<AbstractGoTween> onInitHandler; public Action<AbstractGoTween> onBeginHandler; public Action<AbstractGoTween> onIterationStartHandler; public Action<AbstractGoTween> onUpdateHandler; public Action<AbstractGoTween> onIterationEndHandler; public Action<AbstractGoTween> onCompleteHandler; #region TweenProperty adders /// <summary> /// position tween /// </summary> public GoTweenConfig position( Vector3 endValue, bool isRelative = false ) { var prop = new PositionTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localPosition tween /// </summary> public GoTweenConfig localPosition( Vector3 endValue, bool isRelative = false ) { var prop = new PositionTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// position path tween /// </summary> public GoTweenConfig positionPath( GoSpline path, bool isRelative = false, GoLookAtType lookAtType = GoLookAtType.None, Transform lookTarget = null ) { var prop = new PositionPathTweenProperty( path, isRelative, false, lookAtType, lookTarget ); _tweenProperties.Add( prop ); return this; } /// <summary> /// uniform scale tween (x, y and z scale to the same value) /// </summary> public GoTweenConfig scale( float endValue, bool isRelative = false ) { return this.scale( new Vector3( endValue, endValue, endValue ), isRelative ); } /// <summary> /// scale tween /// </summary> public GoTweenConfig scale( Vector3 endValue, bool isRelative = false ) { var prop = new ScaleTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// scale through a series of Vector3s /// </summary> public GoTweenConfig scalePath( GoSpline path, bool isRelative = false ) { var prop = new ScalePathTweenProperty( path, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// eulerAngle tween /// </summary> public GoTweenConfig eulerAngles( Vector3 endValue, bool isRelative = false ) { var prop = new EulerAnglesTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// local eulerAngle tween /// </summary> public GoTweenConfig localEulerAngles( Vector3 endValue, bool isRelative = false ) { var prop = new EulerAnglesTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// rotation tween /// </summary> public GoTweenConfig rotation( Vector3 endValue, bool isRelative = false ) { var prop = new RotationTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localRotation tween /// </summary> public GoTweenConfig localRotation( Vector3 endValue, bool isRelative = false ) { var prop = new RotationTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// rotation tween as Quaternion /// </summary> public GoTweenConfig rotation( Quaternion endValue, bool isRelative = false ) { var prop = new RotationQuaternionTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localRotation tween as Quaternion /// </summary> public GoTweenConfig localRotation( Quaternion endValue, bool isRelative = false ) { var prop = new RotationQuaternionTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// material color tween /// </summary> public GoTweenConfig materialColor( Color endValue, string colorName = "_Color", bool isRelative = false ) { var prop = new MaterialColorTweenProperty( endValue, colorName, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// shake tween /// </summary> public GoTweenConfig shake( Vector3 shakeMagnitude, GoShakeType shakeType = GoShakeType.Position, int frameMod = 1, bool useLocalProperties = false ) { var prop = new ShakeTweenProperty( shakeMagnitude, shakeType, frameMod, useLocalProperties ); _tweenProperties.Add( prop ); return this; } #region generic properties /// <summary> /// generic vector2 tween /// </summary> public GoTweenConfig vector2Prop( string propertyName, Vector2 endValue, bool isRelative = false ) { var prop = new Vector2TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3 tween /// </summary> public GoTweenConfig vector3Prop( string propertyName, Vector3 endValue, bool isRelative = false ) { var prop = new Vector3TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector4 tween /// </summary> public GoTweenConfig vector4Prop( string propertyName, Vector4 endValue, bool isRelative = false ) { var prop = new Vector4TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3 path tween /// </summary> public GoTweenConfig vector3PathProp( string propertyName, GoSpline path, bool isRelative = false ) { var prop = new Vector3PathTweenProperty( propertyName, path, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.x tween /// </summary> public GoTweenConfig vector3XProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3XTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.y tween /// </summary> public GoTweenConfig vector3YProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3YTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.z tween /// </summary> public GoTweenConfig vector3ZProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3ZTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic color tween /// </summary> public GoTweenConfig colorProp( string propertyName, Color endValue, bool isRelative = false ) { var prop = new ColorTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic integer tween /// </summary> public GoTweenConfig intProp( string propertyName, int endValue, bool isRelative = false ) { var prop = new IntTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic float tween /// </summary> public GoTweenConfig floatProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new FloatTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } #endregion #endregion /// <summary> /// adds a TweenProperty to the list /// </summary> public GoTweenConfig addTweenProperty( AbstractTweenProperty tweenProp ) { _tweenProperties.Add( tweenProp ); return this; } /// <summary> /// clears out all the TweenProperties /// </summary> public GoTweenConfig clearProperties() { _tweenProperties.Clear(); return this; } /// <summary> /// clears out all the TweenProperties /// </summary> public GoTweenConfig clearEvents() { onInitHandler = null; onBeginHandler = null; onIterationStartHandler = null; onUpdateHandler = null; onIterationEndHandler = null; onCompleteHandler = null; return this; } /// <summary> /// sets the delay for the tween /// </summary> public GoTweenConfig setDelay( float seconds ) { delay = seconds; return this; } /// <summary> /// sets the number of iterations. setting to -1 will loop infinitely /// </summary> public GoTweenConfig setIterations( int iterations ) { this.iterations = iterations; return this; } /// <summary> /// sets the number of iterations and the loop type. setting to -1 will loop infinitely /// </summary> public GoTweenConfig setIterations( int iterations, GoLoopType loopType ) { this.iterations = iterations; this.loopType = loopType; return this; } /// <summary> /// sets the timeScale to be used by the Tween /// </summary> public GoTweenConfig setTimeScale( int timeScale ) { this.timeScale = timeScale; return this; } /// <summary> /// sets the ease type for the Tween /// </summary> public GoTweenConfig setEaseType( GoEaseType easeType ) { this.easeType = easeType; return this; } /// <summary> /// sets the ease curve for the Tween /// </summary> public GoTweenConfig setEaseCurve( AnimationCurve easeCurve ) { this.easeCurve = easeCurve; this.easeType = GoEaseType.AnimationCurve; return this; } /// <summary> /// sets whether the Tween should start paused /// </summary> public GoTweenConfig startPaused() { isPaused = true; return this; } /// <summary> /// sets the update type for the Tween /// </summary> public GoTweenConfig setUpdateType( GoUpdateType setUpdateType ) { propertyUpdateType = setUpdateType; return this; } /// <summary> /// sets if this Tween should be a "from" Tween. From Tweens use the current property as the endValue and /// the endValue as the start value /// </summary> public GoTweenConfig setIsFrom() { isFrom = true; return this; } /// <summary> /// sets if this Tween should be a "to" Tween. /// </summary> public GoTweenConfig setIsTo() { isFrom = false; return this; } /// <summary> /// sets the onInit handler for the Tween /// </summary> public GoTweenConfig onInit( Action<AbstractGoTween> onInit ) { onInitHandler = onInit; return this; } /// <summary> /// sets the onBegin handler for the Tween /// </summary> public GoTweenConfig onBegin( Action<AbstractGoTween> onBegin ) { onBeginHandler = onBegin; return this; } /// <summary> /// sets the onIterationStart handler for the Tween /// </summary> public GoTweenConfig onIterationStart( Action<AbstractGoTween> onIterationStart ) { onIterationStartHandler = onIterationStart; return this; } /// <summary> /// sets the onUpdate handler for the Tween /// </summary> public GoTweenConfig onUpdate( Action<AbstractGoTween> onUpdate ) { onUpdateHandler = onUpdate; return this; } /// <summary> /// sets the onIterationEnd handler for the Tween /// </summary> public GoTweenConfig onIterationEnd( Action<AbstractGoTween> onIterationEnd ) { onIterationEndHandler = onIterationEnd; return this; } /// <summary> /// sets the onComplete handler for the Tween /// </summary> public GoTweenConfig onComplete( Action<AbstractGoTween> onComplete ) { onCompleteHandler = onComplete; return this; } /// <summary> /// sets the id for the Tween. Multiple Tweens can have the same id and you can retrieve them with the Go class /// </summary> public GoTweenConfig setId( int id ) { this.id = id; return this; } /// <summary> /// clones the instance /// </summary> public GoTweenConfig clone() { var other = this.MemberwiseClone() as GoTweenConfig; other._tweenProperties = new List<AbstractTweenProperty>( 2 ); for( int k = 0; k < this._tweenProperties.Count; ++k ) { AbstractTweenProperty tweenProp = this._tweenProperties[k]; other._tweenProperties.Add(tweenProp); } return other; } }
/* * Many thanks to BobJanova for a seed project for this library (see the original here: http://www.codeproject.com/Articles/25050/Embedded-NET-HTTP-Server) * Original license is CPOL. My preferred licensing is BSD, which differs only from CPOL in that CPOL explicitly grants you freedom * from prosecution for patent infringement (not that this code is patented or that I even believe in the concept). So, CPOL it is. * You can find the CPOL here: * http://www.codeproject.com/info/cpol10.aspx */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using PeanutButter.SimpleTcpServer; using static PeanutButter.SimpleHTTPServer.HttpConstants; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable InconsistentNaming namespace PeanutButter.SimpleHTTPServer { /// <summary> /// Processor for HTTP requests on top of the generic TCP processor /// </summary> public class HttpProcessor : TcpServerProcessor, IProcessor { /// <summary> /// Action to use when attempting to log arbitrary data /// </summary> public Action<string> LogAction => Server.LogAction; /// <summary> /// Action to use when attempting to log requests /// </summary> public Action<RequestLogItem> RequestLogAction => Server.RequestLogAction; private const int BUF_SIZE = 4096; /// <summary> /// Provides access to the server associated with this processor /// </summary> public HttpServerBase Server { get; protected set; } private StreamWriter _outputStream; /// <summary> /// Method of the current request being processed /// </summary> public string Method { get; private set; } /// <summary> /// Full url for the request being processed /// </summary> public string FullUrl { get; private set; } /// <summary> /// Just the path for the request being processed /// </summary> public string Path { get; private set; } /// <summary> /// Protocol for the request being processed /// </summary> public string Protocol { get; private set; } /// <summary> /// Url parameters for the request being processed /// </summary> public Dictionary<string, string> UrlParameters { get; set; } /// <summary> /// Headers on the request being processed /// </summary> public Dictionary<string, string> HttpHeaders { get; private set; } /// <summary> /// Maximum size, in bytes, to accept for a POST /// </summary> public long MaxPostSize { get; set; } = MAX_POST_SIZE; /// <inheritdoc /> public HttpProcessor(TcpClient tcpClient, HttpServerBase server) : base(tcpClient) { Server = server; HttpHeaders = new Dictionary<string, string>(); } /// <inheritdoc /> public void ProcessRequest() { using (var io = new TcpIoWrapper(TcpClient)) { try { _outputStream = io.StreamWriter; ParseRequest(); ReadHeaders(); HandleRequest(io); } catch (FileNotFoundException) { WriteFailure(HttpStatusCode.NotFound, Statuses.NOTFOUND); } catch (Exception ex) { WriteFailure(HttpStatusCode.InternalServerError, $"{Statuses.INTERNALERROR}: {ex.Message}"); LogAction("Unable to process request: " + ex.Message); } finally { _outputStream = null; } } } /// <summary> /// Handles the request, given an IO wrapper /// </summary> /// <param name="io"></param> public void HandleRequest(TcpIoWrapper io) { if (Method.Equals(Methods.GET)) { HandleGETRequest(); return; } if (Method.Equals(Methods.POST)) HandlePOSTRequest(io.RawStream); } /// <summary> /// Parses the request from the TcpClient /// </summary> public void ParseRequest() { var request = TcpClient.ReadLine(); var tokens = request.Split(' '); if (tokens.Length != 3) { throw new Exception("invalid http request line"); } Method = tokens[0].ToUpper(); FullUrl = tokens[1]; var parts = FullUrl.Split('?'); if (parts.Length == 1) UrlParameters = new Dictionary<string, string>(); else { var all = string.Join("?", parts.Skip(1)); UrlParameters = EncodedStringToDictionary(all); } Path = parts.First(); Protocol = tokens[2]; } private Dictionary<string, string> EncodedStringToDictionary(string s) { var parts = s.Split('&'); return parts.Select(p => { var subParts = p.Split('='); var key = subParts.First(); var value = string.Join("=", subParts.Skip(1)); return new { key, value }; }).ToDictionary(x => x.key, x => x.value); } /// <summary> /// Reads in the headers from the TcpClient /// </summary> public void ReadHeaders() { string line; while ((line = TcpClient.ReadLine()) != null) { if (line.Equals(string.Empty)) { return; } var separator = line.IndexOf(':'); if (separator == -1) { throw new Exception("invalid http header line: " + line); } var name = line.Substring(0, separator); var pos = separator + 1; while ((pos < line.Length) && (line[pos] == ' ')) { pos++; // strip any spaces } var value = line.Substring(pos, line.Length - pos); HttpHeaders[name] = value; } } /// <summary> /// Handles this request as a GET /// </summary> public void HandleGETRequest() { Server.HandleGETRequest(this); } /// <summary> /// Handles this request as a POST /// </summary> /// <param name="stream"></param> public void HandlePOSTRequest(Stream stream) { using (var ms = new MemoryStream()) { if (HttpHeaders.ContainsKey(Headers.CONTENT_LENGTH)) { var contentLength = Convert.ToInt32(HttpHeaders[Headers.CONTENT_LENGTH]); if (contentLength > MaxPostSize) { throw new Exception( $"POST Content-Length({contentLength}) too big for this simple server (max: {MaxPostSize})" ); } var buf = new byte[BUF_SIZE]; var toRead = contentLength; while (toRead > 0) { var numread = stream.Read(buf, 0, Math.Min(BUF_SIZE, toRead)); if (numread == 0) { if (toRead == 0) { break; } else { throw new Exception("client disconnected during post"); } } toRead -= numread; ms.Write(buf, 0, numread); } ms.Seek(0, SeekOrigin.Begin); } ParseFormElementsIfRequired(ms); Server.HandlePOSTRequest(this, ms); } } /// <summary> /// Parses form data on the request, if available /// </summary> /// <param name="ms"></param> public void ParseFormElementsIfRequired(MemoryStream ms) { if (!HttpHeaders.ContainsKey(Headers.CONTENT_TYPE)) return; if (HttpHeaders[Headers.CONTENT_TYPE] != "application/x-www-form-urlencoded") return; try { var formData = Encoding.UTF8.GetString(ms.ToArray()); FormData = EncodedStringToDictionary(formData); } catch { /* intentionally left blank */ } } /// <summary> /// Form data associated with the request /// </summary> public Dictionary<string, string> FormData { get; set; } /// <summary> /// Perform a successful write (ie, HTTP status 200) with the optionally /// provided mime type and data data /// </summary> /// <param name="mimeType"></param> /// <param name="data"></param> public void WriteSuccess(string mimeType = MimeTypes.HTML, byte[] data = null) { WriteOKStatusHeader(); WriteMIMETypeHeader(mimeType); WriteConnectionClosesAfterCommsHeader(); if (data != null) { WriteContentLengthHeader(data.Length); } WriteEmptyLineToStream(); WriteDataToStream(data); } /// <summary> /// Writes the specified MIME header (Content-Type) /// </summary> /// <param name="mimeType"></param> public void WriteMIMETypeHeader(string mimeType) { WriteResponseLine(Headers.CONTENT_TYPE + ": " + mimeType); } /// <summary> /// Writes the OK status header /// </summary> public void WriteOKStatusHeader() { WriteStatusHeader(HttpStatusCode.OK, "OK"); } /// <summary> /// Writes the Content-Length header with the provided length /// </summary> /// <param name="length"></param> public void WriteContentLengthHeader(int length) { WriteHeader("Content-Length", length); } /// <summary> /// Writes the header informing the client that the connection /// will not be held open /// </summary> public void WriteConnectionClosesAfterCommsHeader() { WriteHeader("Connection", "close"); } /// <summary> /// Writes an arbitrary header to the response stream /// </summary> /// <param name="header"></param> /// <param name="value"></param> public void WriteHeader(string header, string value) { WriteResponseLine(string.Join(": ", header, value)); } /// <summary> /// Writes an integer-value header to the response stream /// </summary> /// <param name="header"></param> /// <param name="value"></param> public void WriteHeader(string header, int value) { WriteHeader(header, value.ToString()); } /// <summary> /// Writes the specified status header to the response stream, /// with the optional message /// </summary> /// <param name="code"></param> /// <param name="message"></param> public void WriteStatusHeader(HttpStatusCode code, string message = null) { LogRequest(code, message); WriteResponseLine($"HTTP/1.0 {(int) code} {message ?? code.ToString()}"); } private void LogRequest(HttpStatusCode code, string message) { var action = RequestLogAction; action?.Invoke( new RequestLogItem(FullUrl, code, Method, message, HttpHeaders) ); } /// <summary> /// Writes arbitrary byte data to the response stream /// </summary> /// <param name="data"></param> public void WriteDataToStream(byte[] data) { if (data == null) return; _outputStream.Flush(); _outputStream.BaseStream.Write(data, 0, data.Length); _outputStream.BaseStream.Flush(); } /// <summary> /// Writes an arbitrary string to the response stream /// </summary> /// <param name="data"></param> public void WriteDataToStream(string data) { WriteDataToStream( Encoding.UTF8.GetBytes(data ?? "") ); } /// <summary> /// Writes out a simple http failure /// </summary> /// <param name="code"></param> public void WriteFailure(HttpStatusCode code) { WriteFailure(code, code.ToString()); } /// <summary> /// Writes a failure code and message to the response stream and closes /// the response /// </summary> /// <param name="code"></param> /// <param name="message"></param> public void WriteFailure( HttpStatusCode code, string message ) { WriteFailure(code, message, null); } /// <summary> /// Writes out an http failure with body text /// </summary> /// <param name="code">The http code to return</param> /// <param name="message">The message to add to the status line</param> /// <param name="body">The body to write out</param> public void WriteFailure( HttpStatusCode code, string message, string body) { WriteFailure(code, message, body, "text/plain"); } /// <summary> /// Write out a failure with a message, body and custom mime-type /// </summary> /// <param name="code"></param> /// <param name="message"></param> /// <param name="body"></param> /// <param name="mimeType"></param> public void WriteFailure( HttpStatusCode code, string message, string body, string mimeType ) { WriteStatusHeader(code, message); WriteConnectionClosesAfterCommsHeader(); if (string.IsNullOrEmpty(body)) { WriteEmptyLineToStream(); return; } WriteMIMETypeHeader(mimeType); WriteContentLengthHeader(body.Length); WriteConnectionClosesAfterCommsHeader(); WriteEmptyLineToStream(); WriteDataToStream(body); } /// <summary> /// Writes an empty line to the stream: HTTP is line-based, /// so the client will probably interpret this as an end /// of section / request /// </summary> public void WriteEmptyLineToStream() { WriteResponseLine(string.Empty); } /// <summary> /// Write an arbitrary string response to the response stream /// </summary> /// <param name="response"></param> public void WriteResponseLine(string response) { _outputStream.WriteLine(response); } /// <summary> /// Write a textural document to the response stream with /// the assumption that the mime type is text/html /// </summary> /// <param name="document"></param> public void WriteDocument(string document) { WriteDocument(document, MimeTypes.HTML); } /// <summary> /// Write a textural document to the response stream with /// the optionally-provided mime type /// </summary> /// <param name="document"></param> /// <param name="mimeType"></param> public void WriteDocument(string document, string mimeType) { WriteSuccess(mimeType, Encoding.UTF8.GetBytes(document)); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Linq; namespace LinqToDB.Reflection { using Expressions; using Extensions; using Mapping; public class MemberAccessor { public MemberAccessor(TypeAccessor typeAccessor, string memberName) { TypeAccessor = typeAccessor; if (memberName.IndexOf('.') < 0) { SetSimple(Expression.PropertyOrField(Expression.Constant(null, typeAccessor.Type), memberName).Member); } else { IsComplex = true; HasGetter = true; HasSetter = true; var members = memberName.Split('.'); var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var expr = objParam as Expression; var infos = members.Select(m => { expr = Expression.PropertyOrField(expr, m); return new { member = ((MemberExpression)expr).Member, type = expr.Type, }; }).ToArray(); var lastInfo = infos[infos.Length - 1]; MemberInfo = lastInfo.member; Type = lastInfo.type; var checkNull = infos.Take(infos.Length - 1).Any(info => info.type.IsClassEx() || info.type.IsNullable()); // Build getter. // { if (checkNull) { var ret = Expression.Variable(Type, "ret"); Func<Expression,int,Expression> makeGetter = null; makeGetter = (ex, i) => { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) return Expression.Assign(ret, next); if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); return Expression.Block( new[] { local }, new[] { Expression.Assign(local, next) as Expression, Expression.IfThen( Expression.NotEqual(local, Expression.Constant(null)), makeGetter(local, i + 1)) }); } return makeGetter(next, i + 1); }; expr = Expression.Block( new[] { ret }, new[] { Expression.Assign(ret, new DefaultValueExpression(MappingSchema.Default, Type)), makeGetter(objParam, 0), ret }); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); } GetterExpression = Expression.Lambda(expr, objParam); } // Build setter. // { HasSetter = !infos.Any(info => info.member is PropertyInfo && ((PropertyInfo)info.member).GetSetMethodEx(true) == null); var valueParam = Expression.Parameter(Type, "value"); if (HasSetter) { if (checkNull) { var vars = new List<ParameterExpression>(); var exprs = new List<Expression>(); Action<Expression,int> makeSetter = null; makeSetter = (ex, i) => { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) { exprs.Add(Expression.Assign(next, valueParam)); } else { if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); vars.Add(local); exprs.Add(Expression.Assign(local, next)); exprs.Add( Expression.IfThen( Expression.Equal(local, Expression.Constant(null)), Expression.Block( Expression.Assign(local, Expression.New(local.Type)), Expression.Assign(next, local)))); makeSetter(local, i + 1); } else { makeSetter(next, i + 1); } } }; makeSetter(objParam, 0); expr = Expression.Block(vars, exprs); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); expr = Expression.Assign(expr, valueParam); } SetterExpression = Expression.Lambda(expr, objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] { fakeParam }, new Expression[] { Expression.Assign(fakeParam, Expression.Constant(0)) }), objParam, valueParam); } } } SetExpressions(); } public MemberAccessor(TypeAccessor typeAccessor, MemberInfo memberInfo) { TypeAccessor = typeAccessor; SetSimple(memberInfo); SetExpressions(); } void SetSimple(MemberInfo memberInfo) { MemberInfo = memberInfo; Type = MemberInfo is PropertyInfo ? ((PropertyInfo)MemberInfo).PropertyType : ((FieldInfo)MemberInfo).FieldType; HasGetter = true; if (memberInfo is PropertyInfo) HasSetter = ((PropertyInfo)memberInfo).GetSetMethodEx(true) != null; else HasSetter = !((FieldInfo)memberInfo).IsInitOnly; var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var valueParam = Expression.Parameter(Type, "value"); GetterExpression = Expression.Lambda(Expression.MakeMemberAccess(objParam, memberInfo), objParam); if (HasSetter) { SetterExpression = Expression.Lambda( Expression.Assign(GetterExpression.Body, valueParam), objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] { fakeParam }, new Expression[] { Expression.Assign(fakeParam, Expression.Constant(0)) }), objParam, valueParam); } } void SetExpressions() { var objParam = Expression.Parameter(typeof(object), "obj"); var getterExpr = GetterExpression.GetBody(Expression.Convert(objParam, TypeAccessor.Type)); var getter = Expression.Lambda<Func<object,object>>(Expression.Convert(getterExpr, typeof(object)), objParam); Getter = getter.Compile(); var valueParam = Expression.Parameter(typeof(object), "value"); var setterExpr = SetterExpression.GetBody( Expression.Convert(objParam, TypeAccessor.Type), Expression.Convert(valueParam, Type)); var setter = Expression.Lambda<Action<object,object>>(setterExpr, objParam, valueParam); Setter = setter.Compile(); } #region Public Properties public MemberInfo MemberInfo { get; private set; } public TypeAccessor TypeAccessor { get; private set; } public bool HasGetter { get; private set; } public bool HasSetter { get; private set; } public Type Type { get; private set; } public bool IsComplex { get; private set; } public LambdaExpression GetterExpression { get; private set; } public LambdaExpression SetterExpression { get; private set; } public Func <object,object> Getter { get; private set; } public Action<object,object> Setter { get; private set; } public string Name { get { return MemberInfo.Name; } } #endregion #region Public Methods public T GetAttribute<T>() where T : Attribute { var attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0? (T)attrs[0]: null; } public T[] GetAttributes<T>() where T : Attribute { Array attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0? (T[])attrs: null; } public object[] GetAttributes() { var attrs = MemberInfo.GetCustomAttributesEx(true); return attrs.Length > 0? attrs: null; } public T[] GetTypeAttributes<T>() where T : Attribute { return TypeAccessor.Type.GetAttributes<T>(); } #endregion #region Set/Get Value public virtual object GetValue(object o) { return Getter(o); } public virtual void SetValue(object o, object value) { Setter(o, value); } #endregion } }
// *********************************************************************** // Assembly : CDFMonitor Author : cdfmdev Created : 07-06-2013 // // Last Modified By : cdfmdev Last Modified On : 07-06-2013 // *********************************************************************** // <copyright file="EtwNativeMethods.cs" company=""> Copyright (c) 2014 Citrix Systems, Inc. // </copyright> <summary></summary> // *********************************************************************** //++ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Module Name: // // EtwNativeMethods.cs // // Abstract: // // This module defines the native methods used by the EtwTraceController and EtwTraceConsumer classes. // //-- namespace CDFM.Trace { using System; using System.Runtime.InteropServices; /// <summary> /// Indicates which structure members are valid: /// </summary> [Flags] public enum EventTraceFlags : byte { /// <summary> /// EVENT_TRACE_USE_PROCTIME - ProcessorTime is valid. /// </summary> ProcessorTimeValid = 0x01, /// <summary> /// EVENT_TRACE_USE_NOCPUTIME - KernelTime, UserTime, and ProcessorTime are not used. /// </summary> NoTimes = 0x02, } /// <summary> /// Type of event. An event type can be user-defined or predefined. This enum identifies the /// general predefined event types. /// </summary> public enum EventTraceType : byte { /// <summary> /// EVENT_TRACE_TYPE_INFO - Informational event. This is the default event type. /// </summary> Info = 0x00, /// <summary> /// EVENT_TRACE_TYPE_START - Start event. Use to trace the initial state of a multi-step /// event. /// </summary> Start = 0x01, /// <summary> /// EVENT_TRACE_TYPE_END - End event. Use to trace the final state of a multi-step event. /// </summary> End = 0x02, /// <summary> /// EVENT_TRACE_TYPE_DC_START - Collection start event. /// </summary> CollectionStart = 0x03, /// <summary> /// EVENT_TRACE_TYPE_DC_END - Collection end event. /// </summary> CollectionEnd = 0x04, /// <summary> /// EVENT_TRACE_TYPE_EXTENSION - _extension event. Use for an event that is a continuation /// of a previous event. For example, use the _extension event type when an event trace /// records more data than can fit in a session buffer. /// </summary> Extension = 0x05, /// <summary> /// EVENT_TRACE_TYPE_REPLY - Reply event. Use when an application that requests resources c /// an receive multiple responses. For example, if a client application requests a URL, and /// the Web server reply is to send several files, each file received can be marked as a /// reply event. /// </summary> Reply = 0x06, /// <summary> /// EVENT_TRACE_TYPE_DEQUEUE - Dequeue event. Use when an activity is queued before it /// begins. Use EVENT_TRACE_TYPE_START to mark the time when a work item is queued. Use the /// dequeue event type to mark the time when work on the item actually begins. Use /// EVENT_TRACE_TYPE_END to mark the time when work on the item completes. /// </summary> Dequeue = 0x07, /// <summary> /// EVENT_TRACE_TYPE_CHECKPOINT - Checkpoint event. Use for an event that is not at the /// start or end of an activity. /// </summary> Checkpoint = 0x08, } /// <summary> /// An public class that contains all of the marshaling and structure definitions for native API /// calls. /// </summary> public static class NativeMethods { #region Public Fields public const int ERROR_ALREADY_EXISTS = 183; public const int ERROR_CANCELLED = 1223; public const int ERROR_CTX_CLOSE_PENDING = 7007; public const int ERROR_INVALID_HANDLE = 6; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_SUCCESS = 0; public const int ERROR_WMI_INSTANCE_NOT_FOUND = 4201; public const uint EventTracePropertiesStringSize = 1024; public const uint EventTracePropertiesStructSize = 120; public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); #endregion Public Fields #region Public Delegates /// <summary> /// Delegate EventCallback /// </summary> /// <param name="eventTrace">The event trace.</param> public delegate void EventCallback([In] ref EventTrace eventTrace); // ULONG WINAPI <FunctionName> (PEVENT_TRACE_LOGFILE Logfile); /// <summary> /// Delegate EventTraceBufferCallback /// </summary> /// <param name="eventTraceLogfile">The event trace logfile.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> public delegate bool EventTraceBufferCallback([In] ref EventTraceLogFile eventTraceLogfile); #endregion Public Delegates #region Public Enums /// <summary> /// Enum EventTraceFileMode /// </summary> public enum EventTraceFileMode : uint { None = 0x00000000, // Like sequential with no max Sequential = 0x00000001, // log sequentially stops at max Circular = 0x00000002, // log in circular manner Append = 0x00000004, NewFile = 0x00000008, // log sequentially until max then create new file RealTime = 0x00000100 // log in real time (no file) } /// <summary> /// Enum WNodeFlags /// </summary> [Flags] public enum WNodeFlags : uint { UseGuidPtr = 0x00080000, // Guid is actually a pointer TracedGuid = 0x00020000, // denotes a trace UseMofPtr = 0x00100000 // MOF data are dereferenced } #endregion Public Enums #region Public Methods // ULONG CloseTrace(TRACEHANDLE TraceHandle); /// <summary> /// Closes the trace. /// </summary> /// <param name="traceHandle">The trace handle.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint CloseTrace([In] ulong traceHandle); /// <summary> /// Enables the trace. /// </summary> /// <param name="enable">The enable.</param> /// <param name="enableFlag">The enable flag.</param> /// <param name="enableLevel">The enable level.</param> /// <param name="controlGuid">The control GUID.</param> /// <param name="traceHandle">The trace handle.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint EnableTrace([In] uint enable, [In] uint enableFlag, [In] uint enableLevel, [In] ref publicGuid controlGuid, [In] ulong traceHandle); // ULONG FlushTrace(TRACEHANDLE SessionHandle, LPCTSTR SessionName, PEVENT_TRACE_PROPERTIES Properties); /// <summary> /// Flushes the trace. /// </summary> /// <param name="traceHandle">The trace handle.</param> /// <param name="sessionName">Name of the session.</param> /// <param name="properties">The properties.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint FlushTrace([In] ulong traceHandle, [In] string sessionName, [In, Out] ref EventTraceProperties properties); /// <summary> /// Gets the trace logger handle. /// </summary> /// <param name="pWNODE_HEADER">The p WNOD e_ HEADER.</param> /// <returns>System.UInt32.</returns> /// Return Type: ULONG-&gt;unsigned int /// PropertyArray: ULONG* /// PropertyArrayCount: ULONG-&gt;unsigned int /// SessionCount: PULONG-&gt;ULONG* [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint GetTraceLoggerHandle([In] ulong pWNODE_HEADER); /// <summary> /// Determines whether [is valid handle] [the specified handle]. /// </summary> /// <param name="handle">The handle.</param> /// <returns><c>true</c> if [is valid handle] [the specified handle]; otherwise, /// /c>.</returns> public static bool IsValidHandle(ulong handle) { IntPtr handleValue; unchecked { if (4 == IntPtr.Size) { handleValue = new IntPtr((int)handle); } else { handleValue = new IntPtr((long)handle); } } return INVALID_HANDLE_VALUE != handleValue; } // TRACEHANDLE OpenTrace(PEVENT_TRACE_LOGFILE Logfile); /// <summary> /// Opens the trace. /// </summary> /// <param name="eventTraceLogfile">The event trace logfile.</param> /// <returns>System.UInt64.</returns> [DllImport("advapi32.dll", EntryPoint = "OpenTraceW", CharSet = CharSet.Unicode, SetLastError = true)] public static extern ulong OpenTrace([In] ref EventTraceLogFile eventTraceLogfile); /// <summary> /// Processes the trace. /// </summary> /// <param name="traceHandleArray">The trace handle array.</param> /// <param name="handleArrayLength">Length of the handle array.</param> /// <param name="startFileTime">The start file time.</param> /// <param name="endFileTime">The end file time.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint ProcessTrace( [In] ulong[] traceHandleArray, [In] int handleArrayLength, [In] ref long startFileTime, [In] ref long endFileTime); /// <summary> /// Queries the trace. /// </summary> /// <param name="traceHandle">The trace handle.</param> /// <param name="sessionName">Name of the session.</param> /// <param name="properties">The properties.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint QueryTrace([In] ulong traceHandle, [In] string sessionName, ref EventTraceProperties properties); /// <summary> /// Starts the trace. /// </summary> /// <param name="traceHandle">The trace handle.</param> /// <param name="sessionName">Name of the session.</param> /// <param name="properties">The properties.</param> /// <returns>System.UInt32.</returns> // todo: switch to Unicode but loggernameoffset and logfilenameoffset will have to be modified. [DllImport("advapi32.dll", CharSet = CharSet.Ansi)] public static extern uint StartTrace([Out] out ulong traceHandle, [In] string sessionName, [In] ref EventTraceProperties properties); /// <summary> /// Stops the trace. /// </summary> /// <param name="traceHandle">The trace handle.</param> /// <param name="sessionName">Name of the session.</param> /// <param name="properties">The properties.</param> /// <returns>System.UInt32.</returns> [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] public static extern uint StopTrace([In] ulong traceHandle, [In] string sessionName, [In, Out] ref EventTraceProperties properties); #endregion Public Methods #region Public Structs /// <summary> /// Struct BufferUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct BufferUnion { [FieldOffset(0)] public Guid LogInstanceGuid; [FieldOffset(0)] public uint StartBuffers; [FieldOffset(4)] public uint PointerSize; [FieldOffset(8)] public uint EventsLost; [FieldOffset(12)] public uint Reserved32; } /// <summary> /// Struct ContextVersionUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct ContextVersionUnion { [FieldOffset(0)] public ulong HistoricalContext; [FieldOffset(0)] public uint Version; [FieldOffset(4)] public uint Linkage; } /// <summary> /// Struct EVENT_TRACE /// </summary> [StructLayout(LayoutKind.Sequential)] public struct EventTrace { public ushort Size; public EventTraceType HeaderType; public EventTraceFlags MarkerFlags; public byte Type; public byte Level; public ushort Version; public uint ThreadId; public uint ProcessId; public Int64 TimeStamp; public Guid Guid; // Int64 RegHandle; public uint InstanceId; public uint ParentInstanceId; public TimeUnion TimeUnion; public Guid ParentGuid; public IntPtr MofData; public uint MofLength; public uint ClientContext; } /// <summary> /// Struct EVENT_TRACE_LOGFILE /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct EventTraceLogFile { public string LogfileName; public string LoggerName; public long CurrentTime; public uint BuffersRead; public uint LogFileMode; public EventTrace CurrentEvent; public TraceLogfileHeader LogfileHeader; public EventTraceBufferCallback BufferCallback; public uint BufferSize; public uint Filled; public uint EventsLost; public EventCallback EventCallback; public uint IsKernelTrace; public long Context; } /// <summary> /// Struct EVENT_TRACE_PROPERTIES /// </summary> [StructLayout(LayoutKind.Sequential)] public struct EventTraceProperties { public WnodeHeader WNode; public uint BufferSize; public uint MinimumBuffers; public uint MaximumBuffers; public uint MaximumFileSize; public EventTraceFileMode LogFileMode; public uint FlushTimer; public uint EnableFlags; public int AgeLimit; public uint NumberOfBuffers; public uint FreeBuffers; public uint EventsLost; public uint BuffersWritten; public uint LogBuffersLost; public uint RealTimeBuffersLost; public unsafe void* LoggerThreadId; public uint LogFileNameOffset; public uint LoggerNameOffset; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)EventTracePropertiesStringSize)] public string LoggerName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)EventTracePropertiesStringSize)] public string LogFileName; } /// <summary> /// Struct KernalTimestampUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct KernalTimestampUnion { [FieldOffset(0)] public uint CountLost; [FieldOffset(0)] public unsafe void* KernelHandle; [FieldOffset(0)] public long TimeStamp; } /// <summary> /// Struct publicGuid /// </summary> [StructLayout(LayoutKind.Sequential), Serializable] public struct publicGuid { public int _a; public short _b; public short _c; public byte _d; public byte _e; public byte _f; public byte _g; public byte _h; public byte _i; public byte _j; public byte _k; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="publicGuid" /> struct. /// </summary> /// <param name="guidBytes">The GUID bytes.</param> /// <exception cref="System.ArgumentNullException">guidBytes</exception> /// <exception cref="System.ArgumentException">Wrong length;guidBytes</exception> public publicGuid(byte[] guidBytes) { if (guidBytes == null) { throw new ArgumentNullException("guidBytes"); } if (guidBytes.Length != 16) { throw new ArgumentException("Wrong length", "guidBytes"); } _a = BitConverter.ToInt32(guidBytes, 0); _b = BitConverter.ToInt16(guidBytes, 4); _c = BitConverter.ToInt16(guidBytes, 6); _d = guidBytes[8]; _e = guidBytes[9]; _f = guidBytes[10]; _g = guidBytes[11]; _h = guidBytes[12]; _i = guidBytes[13]; _j = guidBytes[14]; _k = guidBytes[15]; } #endregion Constructors #region Methods /// <summary> /// Implements the operator !=. /// </summary> /// <param name="a">A.</param> /// <param name="b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(publicGuid a, publicGuid b) { return !a.Equals(b); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="a">A.</param> /// <param name="b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(publicGuid a, publicGuid b) { return a.Equals(b); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this /// instance. /// </summary> /// <param name="o">The <see cref="System.Object" /> to compare with this /// instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this /// instance; otherwise, /c>.</returns> public override bool Equals(Object o) { bool isEqual = false; // Check that o is a Guid first if (o is publicGuid) { var g = (publicGuid)o; // Now compare each of the elements isEqual = (g._a == _a && g._b == _b && g._c == _c && g._d == _d && g._e == _e && g._f == _f && g._g == _g && g._h == _h && g._i == _i && g._j == _j && g._k == _k); } return isEqual; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and /// data structures like a hash table.</returns> public override int GetHashCode() { return _a ^ ((_b << 16) | (ushort)_c) ^ ((_f << 24) | _k); } #endregion Methods } /// <summary> /// Struct SYSTEMTIME /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SYSTEMTIME { public short wYear; public short wMonth; public short wDayOfWeek; public short wDay; public short wHour; public short wMinute; public short wSecond; public short wMilliseconds; } /// <summary> /// Struct TimeUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct TimeUnion { [FieldOffset(0)] public uint KernelTime; [FieldOffset(4)] public uint UserTime; [FieldOffset(0)] public ulong ProcessorTime; } /// <summary> /// Struct TimeZoneInformation /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TimeZoneInformation { public int Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SYSTEMTIME StandardDate; public int StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SYSTEMTIME DaylightDate; public int DaylightBias; } /// <summary> /// Struct TraceLogfileHeader /// </summary> [StructLayout(LayoutKind.Sequential)] public struct TraceLogfileHeader { public uint BufferSize; public VersionDetailUnion VersionDetailUnion; public uint ProviderVersion; public uint NumberOfProcessors; public long EndTime; public uint TimerResolution; public uint MaximumFileSize; public uint LogFileMode; public uint BuffersWritten; public BufferUnion BufferUnion; public IntPtr LoggerName; public IntPtr LogFileName; public TimeZoneInformation TimeZone; public long BootTime; public long PerfFreq; public long StartTime; public uint ReservedFlags; public uint BuffersLost; } /// <summary> /// Struct VersionDetailUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct VersionDetailUnion { [FieldOffset(0)] public uint Version; [FieldOffset(0)] public byte VersionDetail_MajorVersion; [FieldOffset(1)] public byte VersionDetail_MinorVersion; [FieldOffset(2)] public byte VersionDetail_SubVersion; [FieldOffset(3)] public byte VersionDetail_SubMinorVersion; } /// <summary> /// Struct VersionUnion /// </summary> [StructLayout(LayoutKind.Explicit)] public struct VersionUnion { [FieldOffset(0)] public byte Type; [FieldOffset(1)] public byte Level; [FieldOffset(2)] public ushort Version; } /// <summary> /// Struct WNODE_HEADER /// </summary> [StructLayout(LayoutKind.Sequential)] public struct WnodeHeader { public uint BufferSize; public uint ProviderId; public ContextVersionUnion ContextVersion; public KernalTimestampUnion KernalTimestamp; public publicGuid Guid; public uint ClientContext; public WNodeFlags Flags; } #endregion Public Structs } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using FileHelpers.Options; namespace FileHelpers { /// <summary> /// Base class for all Field Types. /// Implements all the basic functionality of a field in a typed file. /// </summary> public abstract class FieldBase : ICloneable { #region " Private & Internal Fields " // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// type of object to be created, eg DateTime /// </summary> public Type FieldType { get; private set; } /// <summary> /// Provider to convert to and from text /// </summary> public ConverterBase Converter { get; private set; } /// <summary> /// Number of extra characters used, delimiters and quote characters /// </summary> internal int CharsToDiscard { get; set; } /// <summary> /// Field type of an array or it is just fieldType. /// What actual object will be created /// </summary> internal Type FieldTypeInternal { get; set; } /// <summary> /// Is this field an array? /// </summary> public bool IsArray { get; private set; } /// <summary> /// Array must have this many entries /// </summary> public int ArrayMinLength { get; set; } /// <summary> /// Array may have this many entries, if equal to ArrayMinLength then /// it is a fixed length array /// </summary> public int ArrayMaxLength { get; set; } /// <summary> /// Seems to be duplicate of FieldTypeInternal except it is ONLY set /// for an array /// </summary> internal Type ArrayType { get; set; } /// <summary> /// Am I the first field in an array list /// </summary> internal bool IsFirst { get; set; } /// <summary> /// Am I the last field in the array list /// </summary> internal bool IsLast { get; set; } /// <summary> /// Do we process this field but not store the value /// </summary> public bool Discarded { get; set; } /// <summary> /// Unused! /// </summary> internal bool TrailingArray { get; set; } /// <summary> /// Value to use if input is null or empty /// </summary> internal object NullValue { get; set; } /// <summary> /// Are we a simple string field we can just assign to /// </summary> internal bool IsStringField { get; set; } /// <summary> /// Details about the extraction criteria /// </summary> internal FieldInfo FieldInfo { get; set; } /// <summary> /// indicates whether we trim leading and/or trailing whitespace /// </summary> public TrimMode TrimMode { get; set; } /// <summary> /// Character to chop off front and / rear of the string /// </summary> internal char[] TrimChars { get; set; } /// <summary> /// The field may not be present on the input data (line not long enough) /// </summary> public bool IsOptional { get; set; } /// <summary> /// The next field along is optional, optimise processing next records /// </summary> internal bool NextIsOptional { get { if (Parent.FieldCount > ParentIndex + 1) return Parent.Fields[ParentIndex + 1].IsOptional; return false; } } /// <summary> /// Set from the FieldInNewLIneAtribute. This field begins on a new /// line of the file /// </summary> internal bool InNewLine { get; set; } /// <summary> /// Order of the field in the file layout /// </summary> internal int? FieldOrder { get; set; } /// <summary> /// Can null be assigned to this value type, for example not int or /// DateTime /// </summary> internal bool IsNullableType { get; private set; } /// <summary> /// Name of the field without extra characters (eg property) /// </summary> internal string FieldFriendlyName { get; set; } /// <summary> /// The field must be not be empty /// </summary> public bool IsNotEmpty { get; set; } // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// Fieldname of the field we are storing /// </summary> internal string FieldName { get { return FieldInfo.Name; } } /* private static readonly char[] mWhitespaceChars = new[] { '\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u3000', '\ufeff' */ #endregion #region " CreateField " /// <summary> /// Check the Attributes on the field and return a structure containing /// the settings for this file. /// </summary> /// <param name="fi">Information about this field</param> /// <param name="recordAttribute">Type of record we are reading</param> /// <returns>Null if not used</returns> public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute) { // If ignored, return null #pragma warning disable 612,618 // disable obsole warning if (fi.IsDefined(typeof (FieldNotInFileAttribute), true) || fi.IsDefined(typeof (FieldIgnoredAttribute), true) || fi.IsDefined(typeof (FieldHiddenAttribute), true)) #pragma warning restore 612,618 return null; FieldBase res = null; var attributes = (FieldAttribute[]) fi.GetCustomAttributes(typeof (FieldAttribute), true); // CHECK USAGE ERRORS !!! // Fixed length record and no attributes at all if (recordAttribute is FixedLengthRecordAttribute && attributes.Length == 0) { throw new BadUsageException("The field: '" + fi.Name + "' must be marked the FieldFixedLength attribute because the record class is marked with FixedLengthRecord."); } if (attributes.Length > 1) { throw new BadUsageException("The field: '" + fi.Name + "' has a FieldFixedLength and a FieldDelimiter attribute."); } if (recordAttribute is DelimitedRecordAttribute && fi.IsDefined(typeof (FieldAlignAttribute), false)) { throw new BadUsageException("The field: '" + fi.Name + "' can't be marked with FieldAlign attribute, it is only valid for fixed length records and are used only for write purpose."); } if (fi.FieldType.IsArray == false && fi.IsDefined(typeof (FieldArrayLengthAttribute), false)) { throw new BadUsageException("The field: '" + fi.Name + "' can't be marked with FieldArrayLength attribute is only valid for array fields."); } // PROCESS IN NORMAL CONDITIONS if (attributes.Length > 0) { FieldAttribute fieldAttb = attributes[0]; if (fieldAttb is FieldFixedLengthAttribute) { // Fixed Field if (recordAttribute is DelimitedRecordAttribute) { throw new BadUsageException("The field: '" + fi.Name + "' can't be marked with FieldFixedLength attribute, it is only for the FixedLengthRecords not for delimited ones."); } var attbFixedLength = (FieldFixedLengthAttribute) fieldAttb; var attbAlign = Attributes.GetFirst<FieldAlignAttribute>(fi); res = new FixedLengthField(fi, attbFixedLength.Length, attbAlign); ((FixedLengthField) res).FixedMode = ((FixedLengthRecordAttribute) recordAttribute).FixedMode; } else if (fieldAttb is FieldDelimiterAttribute) { // Delimited Field if (recordAttribute is FixedLengthRecordAttribute) { throw new BadUsageException("The field: '" + fi.Name + "' can't be marked with FieldDelimiter attribute, it is only for DelimitedRecords not for fixed ones."); } res = new DelimitedField(fi, ((FieldDelimiterAttribute) fieldAttb).Delimiter); } else { throw new BadUsageException( "Custom field attributes are not currently supported. Unknown attribute: " + fieldAttb.GetType().Name + " on field: " + fi.Name); } } else // attributes.Length == 0 { var delimitedRecordAttribute = recordAttribute as DelimitedRecordAttribute; if (delimitedRecordAttribute != null) res = new DelimitedField(fi, delimitedRecordAttribute.Separator); } if (res != null) { // FieldDiscarded res.Discarded = fi.IsDefined(typeof (FieldValueDiscardedAttribute), false); // FieldTrim Attributes.WorkWithFirst<FieldTrimAttribute>(fi, (x) => { res.TrimMode = x.TrimMode; res.TrimChars = x.TrimChars; }); // FieldQuoted Attributes.WorkWithFirst<FieldQuotedAttribute>(fi, (x) => { if (res is FixedLengthField) { throw new BadUsageException( "The field: '" + fi.Name + "' can't be marked with FieldQuoted attribute, it is only for the delimited records."); } ((DelimitedField) res).QuoteChar = x.QuoteChar; ((DelimitedField) res).QuoteMode = x.QuoteMode; ((DelimitedField) res).QuoteMultiline = x.QuoteMultiline; }); // FieldOrder Attributes.WorkWithFirst<FieldOrderAttribute>(fi, x => res.FieldOrder = x.Order); // FieldOptional res.IsOptional = fi.IsDefined(typeof(FieldOptionalAttribute), false); // FieldInNewLine res.InNewLine = fi.IsDefined(typeof(FieldInNewLineAttribute), false); // FieldNotEmpty res.IsNotEmpty = fi.IsDefined(typeof(FieldNotEmptyAttribute), false); // FieldArrayLength if (fi.FieldType.IsArray) { res.IsArray = true; res.ArrayType = fi.FieldType.GetElementType(); // MinValue indicates that there is no FieldArrayLength in the array res.ArrayMinLength = int.MinValue; res.ArrayMaxLength = int.MaxValue; Attributes.WorkWithFirst<FieldArrayLengthAttribute>(fi, (x) => { res.ArrayMinLength = x.MinLength; res.ArrayMaxLength = x.MaxLength; if (res.ArrayMaxLength < res.ArrayMinLength || res.ArrayMinLength < 0 || res.ArrayMaxLength <= 0) { throw new BadUsageException("The field: " + fi.Name + " has invalid length values in the [FieldArrayLength] attribute."); } }); } } if (fi.IsDefined(typeof (CompilerGeneratedAttribute), false)) { if (fi.Name.EndsWith("__BackingField") && fi.Name.StartsWith("<") && fi.Name.Contains(">")) res.FieldFriendlyName = fi.Name.Substring(1, fi.Name.IndexOf(">") - 1); res.IsAutoProperty = true; var prop = fi.DeclaringType.GetProperty(res.FieldFriendlyName); if (prop != null) { Attributes.WorkWithFirst<FieldOrderAttribute>(prop, x => res.FieldOrder = x.Order); } } if (string.IsNullOrEmpty(res.FieldFriendlyName)) res.FieldFriendlyName = res.FieldName; return res; } internal RecordOptions Parent { get; set; } internal int ParentIndex { get; set; } internal static string AutoPropertyName(FieldInfo fi) { if (fi.IsDefined(typeof(CompilerGeneratedAttribute), false)) { if (fi.Name.EndsWith("__BackingField") && fi.Name.StartsWith("<") && fi.Name.Contains(">")) return fi.Name.Substring(1, fi.Name.IndexOf(">") - 1); } return ""; } internal bool IsAutoProperty { get; set; } #endregion #region " Constructor " /// <summary> /// Create a field base without any configuration /// </summary> internal FieldBase() { IsNullableType = false; TrimMode = TrimMode.None; FieldOrder = null; InNewLine = false; //NextIsOptional = false; IsOptional = false; TrimChars = null; NullValue = null; TrailingArray = false; IsLast = false; IsFirst = false; IsArray = false; CharsToDiscard = 0; IsNotEmpty = false; } /// <summary> /// Create a field base from a fieldinfo object /// Verify the settings against the actual field to ensure it will work. /// </summary> /// <param name="fi">Field Info Object</param> internal FieldBase(FieldInfo fi) : this() { FieldInfo = fi; FieldType = FieldInfo.FieldType; if (FieldType.IsArray) FieldTypeInternal = FieldType.GetElementType(); else FieldTypeInternal = FieldType; IsStringField = FieldTypeInternal == typeof (string); object[] attribs = fi.GetCustomAttributes(typeof (FieldConverterAttribute), true); if (attribs.Length > 0) { var conv = (FieldConverterAttribute) attribs[0]; this.Converter = conv.Converter; conv.ValidateTypes(FieldInfo); } else this.Converter = ConvertHelpers.GetDefaultConverter(fi.Name, FieldType); if (this.Converter != null) this.Converter.mDestinationType = FieldTypeInternal; attribs = fi.GetCustomAttributes(typeof (FieldNullValueAttribute), true); if (attribs.Length > 0) { NullValue = ((FieldNullValueAttribute) attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (NullValue != null) { if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType())) { throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name + " that is not asignable to the field " + FieldInfo.Name + " of type: " + FieldTypeInternal.Name); } } } IsNullableType = FieldTypeInternal.IsValueType && FieldTypeInternal.IsGenericType && FieldTypeInternal.GetGenericTypeDefinition() == typeof (Nullable<>); } #endregion #region " MustOverride (String Handling) " /// <summary> /// Extract the string from the underlying data, removes quotes /// characters for example /// </summary> /// <param name="line">Line to parse data from</param> /// <returns>Slightly processed string from the data</returns> internal abstract ExtractedInfo ExtractFieldString(LineInfo line); /// <summary> /// Create a text block containing the field from definition /// </summary> /// <param name="sb">Append string to output</param> /// <param name="fieldValue">Field we are adding</param> /// <param name="isLast">Indicates if we are processing last field</param> internal abstract void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast); /// <summary> /// Convert a field value to a string representation /// </summary> /// <param name="fieldValue">Object containing data</param> /// <returns>String representation of field</returns> internal string CreateFieldString(object fieldValue) { if (this.Converter == null) { if (fieldValue == null) return string.Empty; else return fieldValue.ToString(); } else return this.Converter.FieldToString(fieldValue); } #endregion #region " ExtractValue " /// <summary> /// Get the data out of the records /// </summary> /// <param name="line">Line handler containing text</param> /// <returns></returns> internal object ExtractFieldValue(LineInfo line) { //-> extract only what I need if (InNewLine) { // Any trailing characters, terminate if (line.EmptyFromPos() == false) { throw new BadUsageException(line, "Text '" + line.CurrentString + "' found before the new line of the field: " + FieldInfo.Name + " (this is not allowed when you use [FieldInNewLine])"); } line.ReLoad(line.mReader.ReadNextLine()); if (line.mLineStr == null) { throw new BadUsageException(line, "End of stream found parsing the field " + FieldInfo.Name + ". Please check the class record."); } } if (IsArray == false) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; //total; if (Discarded) return GetDiscardedNullValue(); else return AssignFromString(info, line).Value; } else { if (ArrayMinLength <= 0) ArrayMinLength = 0; int i = 0; var res = new ArrayList(Math.Max(ArrayMinLength, 10)); while (line.mCurrentPos - CharsToDiscard < line.mLineStr.Length && i < ArrayMaxLength) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; try { var value = AssignFromString(info, line); if (value.NullValueUsed && i == 0 && line.IsEOL()) break; res.Add(value.Value); } catch (NullValueNotFoundException) { if (i == 0) break; else throw; } i++; } if (res.Count < ArrayMinLength) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has only {3} values, less than the minimum length of {4}", line.mReader.LineNumber.ToString(), line.mCurrentPos.ToString(), FieldInfo.Name, res.Count, ArrayMinLength)); } else if (IsLast && line.IsEOL() == false) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has more values than the maximum length of {3}", line.mReader.LineNumber, line.mCurrentPos, FieldInfo.Name, ArrayMaxLength)); } // TODO: is there a reason we go through all the array processing then discard it if (Discarded) return null; else return res.ToArray(ArrayType); } } #region " AssignFromString " private struct AssignResult { public object Value; public bool NullValueUsed; } /// <summary> /// Create field object after extracting the string from the underlying /// input data /// </summary> /// <param name="fieldString">Information extracted?</param> /// <param name="line">Underlying input data</param> /// <returns>Object to assign to field</returns> private AssignResult AssignFromString(ExtractedInfo fieldString, LineInfo line) { object val; var extractedString = fieldString.ExtractedString(); try { if (IsNotEmpty && String.IsNullOrEmpty(extractedString)) { throw new InvalidOperationException("The value is empty and must be populated."); } else if (this.Converter == null) { if (IsStringField) val = TrimString(extractedString); else { extractedString = extractedString.Trim(); if (extractedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else val = Convert.ChangeType(extractedString, FieldTypeInternal, null); } } else { var trimmedString = extractedString.Trim(); if (this.Converter.CustomNullHandling == false && trimmedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else { if (TrimMode == TrimMode.Both) val = this.Converter.StringToField(trimmedString); else val = this.Converter.StringToField(TrimString(extractedString)); if (val == null) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } } } return new AssignResult { Value = val }; } catch (ConvertException ex) { ex.FieldName = FieldInfo.Name; ex.LineNumber = line.mReader.LineNumber; ex.ColumnNumber = fieldString.ExtractedFrom + 1; throw; } catch (BadUsageException) { throw; } catch (Exception ex) { if (this.Converter == null || this.Converter.GetType().Assembly == typeof (FieldBase).Assembly) { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, ex.Message, ex); } else { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, "Your custom converter: " + this.Converter.GetType().Name + " throws an " + ex.GetType().Name + " with the message: " + ex.Message, ex); } } } private String TrimString(string extractedString) { switch (TrimMode) { case TrimMode.None: return extractedString; case TrimMode.Both: return extractedString.Trim(); case TrimMode.Left: return extractedString.TrimStart(); case TrimMode.Right: return extractedString.TrimEnd(); default: throw new Exception("Trim mode invalid in FieldBase.TrimString -> " + TrimMode.ToString()); } } /// <summary> /// Convert a null value into a representation, /// allows for a null value override /// </summary> /// <param name="line">input line to read, used for error messages</param> /// <returns>Null value for object</returns> private object GetNullValue(LineInfo line) { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "Not value found for the value type field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "'. " + Environment.NewLine + "You must use the [FieldNullValue] attribute because this is a value type and can't be null or use a Nullable Type instead of the current type."; throw new NullValueNotFoundException(line, msg); } else return null; } else return NullValue; } /// <summary> /// Get the null value that represent a discarded value /// </summary> /// <returns>null value of discard?</returns> private object GetDiscardedNullValue() { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "The field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "' is from a value type: " + FieldInfo.FieldType.Name + " and is discarded (null) you must provide a [FieldNullValue] attribute."; throw new BadUsageException(msg); } else return null; } else return NullValue; } #endregion #region " CreateValueForField " /// <summary> /// Convert a field value into a write able value /// </summary> /// <param name="fieldValue">object value to convert</param> /// <returns>converted value</returns> public object CreateValueForField(object fieldValue) { object val = null; if (fieldValue == null) { if (NullValue == null) { if (FieldTypeInternal.IsValueType && Nullable.GetUnderlyingType(FieldTypeInternal) == null) { throw new BadUsageException( "Null Value found. You must specify a FieldNullValueAttribute in the " + FieldInfo.Name + " field of type " + FieldTypeInternal.Name + ", because this is a ValueType."); } else val = null; } else val = NullValue; } else if (FieldTypeInternal == fieldValue.GetType()) val = fieldValue; else { if (this.Converter == null) val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); else { try { if (Nullable.GetUnderlyingType(FieldTypeInternal) != null && Nullable.GetUnderlyingType(FieldTypeInternal) == fieldValue.GetType()) val = fieldValue; else val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); } catch { val = Converter.StringToField(fieldValue.ToString()); } } } return val; } #endregion #endregion #region " AssignToString " /// <summary> /// convert field to string value and assign to a string builder /// buffer for output /// </summary> /// <param name="sb">buffer to collect record</param> /// <param name="fieldValue">value to convert</param> internal void AssignToString(StringBuilder sb, object fieldValue) { if (this.InNewLine == true) sb.Append(StringHelper.NewLine); if (IsArray) { if (fieldValue == null) { if (0 < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array is null, but the minimum length is {1}", FieldInfo.Name, ArrayMinLength)); } return; } var array = (IList) fieldValue; if (array.Count < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the minimum length is {2}", FieldInfo.Name, array.Count, ArrayMinLength)); } if (array.Count > this.ArrayMaxLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the maximum length is {2}", FieldInfo.Name, array.Count, ArrayMaxLength)); } for (int i = 0; i < array.Count; i++) { object val = array[i]; CreateFieldString(sb, val, IsLast && i == array.Count - 1); } } else CreateFieldString(sb, fieldValue, IsLast); } #endregion /// <summary> /// Copy the field object /// </summary> /// <returns>a complete copy of the Field object</returns> public object Clone() { var res = CreateClone(); res.FieldType = FieldType; res.CharsToDiscard = CharsToDiscard; res.Converter = this.Converter; res.FieldTypeInternal = FieldTypeInternal; res.IsArray = IsArray; res.ArrayType = ArrayType; res.ArrayMinLength = ArrayMinLength; res.ArrayMaxLength = ArrayMaxLength; res.IsFirst = IsFirst; res.IsLast = IsLast; res.TrailingArray = TrailingArray; res.NullValue = NullValue; res.IsStringField = IsStringField; res.FieldInfo = FieldInfo; res.TrimMode = TrimMode; res.TrimChars = TrimChars; res.IsOptional = IsOptional; //res.NextIsOptional = NextIsOptional; res.InNewLine = InNewLine; res.FieldOrder = FieldOrder; res.IsNullableType = IsNullableType; res.Discarded = Discarded; res.FieldFriendlyName = FieldFriendlyName; res.IsNotEmpty = IsNotEmpty; res.Parent = Parent; res.ParentIndex = ParentIndex; return res; } /// <summary> /// Add the extra details that derived classes create /// </summary> /// <returns>field clone of right type</returns> protected abstract FieldBase CreateClone(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace System.Linq.Expressions { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed class ExpressionStringBuilder : ExpressionVisitor { private StringBuilder _out; // Associate every unique label or anonymous parameter in the tree with an integer. // The label is displayed as Label_#. private Dictionary<object, int> _ids; private ExpressionStringBuilder() { _out = new StringBuilder(); } public override string ToString() { return _out.ToString(); } private void AddLabel(LabelTarget label) { if (_ids == null) { _ids = new Dictionary<object, int>(); _ids.Add(label, 0); } else { if (!_ids.ContainsKey(label)) { _ids.Add(label, _ids.Count); } } } private int GetLabelId(LabelTarget label) { if (_ids == null) { _ids = new Dictionary<object, int>(); AddLabel(label); return 0; } else { int id; if (!_ids.TryGetValue(label, out id)) { //label is met the first time id = _ids.Count; AddLabel(label); } return id; } } private void AddParam(ParameterExpression p) { if (_ids == null) { _ids = new Dictionary<object, int>(); _ids.Add(_ids, 0); } else { if (!_ids.ContainsKey(p)) { _ids.Add(p, _ids.Count); } } } private int GetParamId(ParameterExpression p) { if (_ids == null) { _ids = new Dictionary<object, int>(); AddParam(p); return 0; } else { int id; if (!_ids.TryGetValue(p, out id)) { // p is met the first time id = _ids.Count; AddParam(p); } return id; } } #region The printing code private void Out(string s) { _out.Append(s); } private void Out(char c) { _out.Append(c); } #endregion #region Output an expresstion tree to a string /// <summary> /// Output a given expression tree to a string. /// </summary> internal static string ExpressionToString(Expression node) { Debug.Assert(node != null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.Visit(node); return esb.ToString(); } internal static string CatchBlockToString(CatchBlock node) { Debug.Assert(node != null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitCatchBlock(node); return esb.ToString(); } internal static string SwitchCaseToString(SwitchCase node) { Debug.Assert(node != null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitSwitchCase(node); return esb.ToString(); } /// <summary> /// Output a given member binding to a string. /// </summary> internal static string MemberBindingToString(MemberBinding node) { Debug.Assert(node != null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitMemberBinding(node); return esb.ToString(); } /// <summary> /// Output a given ElementInit to a string. /// </summary> internal static string ElementInitBindingToString(ElementInit node) { Debug.Assert(node != null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitElementInit(node); return esb.ToString(); } private void VisitExpressions<T>(char open, IList<T> expressions, char close) where T : Expression { VisitExpressions(open, expressions, close, ", "); } private void VisitExpressions<T>(char open, IList<T> expressions, char close, string seperator) where T : Expression { Out(open); if (expressions != null) { bool isFirst = true; foreach (T e in expressions) { if (isFirst) { isFirst = false; } else { Out(seperator); } Visit(e); } } Out(close); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] protected internal override Expression VisitBinary(BinaryExpression node) { if (node.NodeType == ExpressionType.ArrayIndex) { Visit(node.Left); Out("["); Visit(node.Right); Out("]"); } else { string op; switch (node.NodeType) { // AndAlso and OrElse were unintentionally changed in // CLR 4. We changed them to "AndAlso" and "OrElse" to // be 3.5 compatible, but it turns out 3.5 shipped with // "&&" and "||". Oops. case ExpressionType.AndAlso: op = "AndAlso"; break; case ExpressionType.OrElse: op = "OrElse"; break; case ExpressionType.Assign: op = "="; break; case ExpressionType.Equal: op = "=="; break; case ExpressionType.NotEqual: op = "!="; break; case ExpressionType.GreaterThan: op = ">"; break; case ExpressionType.LessThan: op = "<"; break; case ExpressionType.GreaterThanOrEqual: op = ">="; break; case ExpressionType.LessThanOrEqual: op = "<="; break; case ExpressionType.Add: op = "+"; break; case ExpressionType.AddAssign: op = "+="; break; case ExpressionType.AddAssignChecked: op = "+="; break; case ExpressionType.AddChecked: op = "+"; break; case ExpressionType.Subtract: op = "-"; break; case ExpressionType.SubtractAssign: op = "-="; break; case ExpressionType.SubtractAssignChecked: op = "-="; break; case ExpressionType.SubtractChecked: op = "-"; break; case ExpressionType.Divide: op = "/"; break; case ExpressionType.DivideAssign: op = "/="; break; case ExpressionType.Modulo: op = "%"; break; case ExpressionType.ModuloAssign: op = "%="; break; case ExpressionType.Multiply: op = "*"; break; case ExpressionType.MultiplyAssign: op = "*="; break; case ExpressionType.MultiplyAssignChecked: op = "*="; break; case ExpressionType.MultiplyChecked: op = "*"; break; case ExpressionType.LeftShift: op = "<<"; break; case ExpressionType.LeftShiftAssign: op = "<<="; break; case ExpressionType.RightShift: op = ">>"; break; case ExpressionType.RightShiftAssign: op = ">>="; break; case ExpressionType.And: if (node.Type == typeof(bool) || node.Type == typeof(bool?)) { op = "And"; } else { op = "&"; } break; case ExpressionType.AndAssign: if (node.Type == typeof(bool) || node.Type == typeof(bool?)) { op = "&&="; } else { op = "&="; } break; case ExpressionType.Or: if (node.Type == typeof(bool) || node.Type == typeof(bool?)) { op = "Or"; } else { op = "|"; } break; case ExpressionType.OrAssign: if (node.Type == typeof(bool) || node.Type == typeof(bool?)) { op = "||="; } else { op = "|="; } break; case ExpressionType.ExclusiveOr: op = "^"; break; case ExpressionType.ExclusiveOrAssign: op = "^="; break; case ExpressionType.Power: op = "^"; break; case ExpressionType.PowerAssign: op = "**="; break; case ExpressionType.Coalesce: op = "??"; break; default: throw new InvalidOperationException(); } Out("("); Visit(node.Left); Out(' '); Out(op); Out(' '); Visit(node.Right); Out(")"); } return node; } protected internal override Expression VisitParameter(ParameterExpression node) { if (node.IsByRef) { Out("ref "); } string name = node.Name; if (String.IsNullOrEmpty(name)) { Out("Param_" + GetParamId(node)); } else { Out(name); } return node; } protected internal override Expression VisitLambda(LambdaExpression node) { if (node.Parameters.Count == 1) { // p => body Visit(node.Parameters[0]); } else { // (p1, p2, ..., pn) => body VisitExpressions('(', node.Parameters, ')'); } Out(" => "); Visit(node.Body); return node; } protected internal override Expression VisitListInit(ListInitExpression node) { Visit(node.NewExpression); Out(" {"); for (int i = 0, n = node.Initializers.Count; i < n; i++) { if (i > 0) { Out(", "); } Out(node.Initializers[i].ToString()); } Out("}"); return node; } protected internal override Expression VisitConditional(ConditionalExpression node) { Out("IIF("); Visit(node.Test); Out(", "); Visit(node.IfTrue); Out(", "); Visit(node.IfFalse); Out(")"); return node; } protected internal override Expression VisitConstant(ConstantExpression node) { if (node.Value != null) { string sValue = node.Value.ToString(); if (node.Value is string) { Out("\""); Out(sValue); Out("\""); } else if (sValue == node.Value.GetType().ToString()) { Out("value("); Out(sValue); Out(")"); } else { Out(sValue); } } else { Out("null"); } return node; } protected internal override Expression VisitDebugInfo(DebugInfoExpression node) { string s = String.Format( CultureInfo.CurrentCulture, "<DebugInfo({0}: {1}, {2}, {3}, {4})>", node.Document.FileName, node.StartLine, node.StartColumn, node.EndLine, node.EndColumn ); Out(s); return node; } protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { VisitExpressions('(', node.Variables, ')'); return node; } // Prints ".instanceField" or "declaringType.staticField" private void OutMember(Expression instance, MemberInfo member) { if (instance != null) { Visit(instance); Out("." + member.Name); } else { // For static members, include the type name Out(member.DeclaringType.Name + "." + member.Name); } } protected internal override Expression VisitMember(MemberExpression node) { OutMember(node.Expression, node.Member); return node; } protected internal override Expression VisitMemberInit(MemberInitExpression node) { if (node.NewExpression.Arguments.Count == 0 && node.NewExpression.Type.Name.Contains("<")) { // anonymous type constructor Out("new"); } else { Visit(node.NewExpression); } Out(" {"); for (int i = 0, n = node.Bindings.Count; i < n; i++) { MemberBinding b = node.Bindings[i]; if (i > 0) { Out(", "); } VisitMemberBinding(b); } Out("}"); return node; } protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Out(assignment.Member.Name); Out(" = "); Visit(assignment.Expression); return assignment; } protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) { Out(binding.Member.Name); Out(" = {"); for (int i = 0, n = binding.Initializers.Count; i < n; i++) { if (i > 0) { Out(", "); } VisitElementInit(binding.Initializers[i]); } Out("}"); return binding; } protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { Out(binding.Member.Name); Out(" = {"); for (int i = 0, n = binding.Bindings.Count; i < n; i++) { if (i > 0) { Out(", "); } VisitMemberBinding(binding.Bindings[i]); } Out("}"); return binding; } protected override ElementInit VisitElementInit(ElementInit initializer) { Out(initializer.AddMethod.ToString()); string sep = ", "; VisitExpressions('(', initializer.Arguments, ')', sep); return initializer; } protected internal override Expression VisitInvocation(InvocationExpression node) { Out("Invoke("); Visit(node.Expression); string sep = ", "; for (int i = 0, n = node.Arguments.Count; i < n; i++) { Out(sep); Visit(node.Arguments[i]); } Out(")"); return node; } protected internal override Expression VisitMethodCall(MethodCallExpression node) { int start = 0; Expression ob = node.Object; if (node.Method.GetCustomAttribute(typeof(ExtensionAttribute)) != null) { start = 1; ob = node.Arguments[0]; } if (ob != null) { Visit(ob); Out("."); } Out(node.Method.Name); Out("("); for (int i = start, n = node.Arguments.Count; i < n; i++) { if (i > start) Out(", "); Visit(node.Arguments[i]); } Out(")"); return node; } protected internal override Expression VisitNewArray(NewArrayExpression node) { switch (node.NodeType) { case ExpressionType.NewArrayBounds: // new MyType[](expr1, expr2) Out("new " + node.Type.ToString()); VisitExpressions('(', node.Expressions, ')'); break; case ExpressionType.NewArrayInit: // new [] {expr1, expr2} Out("new [] "); VisitExpressions('{', node.Expressions, '}'); break; } return node; } protected internal override Expression VisitNew(NewExpression node) { Out("new " + node.Type.Name); Out("("); var members = node.Members; for (int i = 0; i < node.Arguments.Count; i++) { if (i > 0) { Out(", "); } if (members != null) { string name = members[i].Name; Out(name); Out(" = "); } Visit(node.Arguments[i]); } Out(")"); return node; } protected internal override Expression VisitTypeBinary(TypeBinaryExpression node) { Out("("); Visit(node.Expression); switch (node.NodeType) { case ExpressionType.TypeIs: Out(" Is "); break; case ExpressionType.TypeEqual: Out(" TypeEqual "); break; } Out(node.TypeOperand.Name); Out(")"); return node; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] protected internal override Expression VisitUnary(UnaryExpression node) { switch (node.NodeType) { case ExpressionType.TypeAs: Out("("); break; case ExpressionType.Not: Out("Not("); break; case ExpressionType.Negate: case ExpressionType.NegateChecked: Out("-"); break; case ExpressionType.UnaryPlus: Out("+"); break; case ExpressionType.Quote: break; case ExpressionType.Throw: Out("throw("); break; case ExpressionType.Increment: Out("Increment("); break; case ExpressionType.Decrement: Out("Decrement("); break; case ExpressionType.PreIncrementAssign: Out("++"); break; case ExpressionType.PreDecrementAssign: Out("--"); break; case ExpressionType.OnesComplement: Out("~("); break; default: Out(node.NodeType.ToString()); Out("("); break; } Visit(node.Operand); switch (node.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.UnaryPlus: case ExpressionType.PreDecrementAssign: case ExpressionType.PreIncrementAssign: case ExpressionType.Quote: break; case ExpressionType.TypeAs: Out(" As "); Out(node.Type.Name); Out(")"); break; case ExpressionType.PostIncrementAssign: Out("++"); break; case ExpressionType.PostDecrementAssign: Out("--"); break; default: Out(")"); break; } return node; } protected internal override Expression VisitBlock(BlockExpression node) { Out("{"); foreach (var v in node.Variables) { Out("var "); Visit(v); Out(";"); } Out(" ... }"); return node; } protected internal override Expression VisitDefault(DefaultExpression node) { Out("default("); Out(node.Type.Name); Out(")"); return node; } protected internal override Expression VisitLabel(LabelExpression node) { Out("{ ... } "); DumpLabel(node.Target); Out(":"); return node; } protected internal override Expression VisitGoto(GotoExpression node) { Out(node.Kind.ToString().ToLower()); DumpLabel(node.Target); if (node.Value != null) { Out(" ("); Visit(node.Value); Out(") "); } return node; } protected internal override Expression VisitLoop(LoopExpression node) { Out("loop { ... }"); return node; } protected override SwitchCase VisitSwitchCase(SwitchCase node) { Out("case "); VisitExpressions('(', node.TestValues, ')'); Out(": ..."); return node; } protected internal override Expression VisitSwitch(SwitchExpression node) { Out("switch "); Out("("); Visit(node.SwitchValue); Out(") { ... }"); return node; } protected override CatchBlock VisitCatchBlock(CatchBlock node) { Out("catch (" + node.Test.Name); if (node.Variable != null) { Out(node.Variable.Name ?? ""); } Out(") { ... }"); return node; } protected internal override Expression VisitTry(TryExpression node) { Out("try { ... }"); return node; } protected internal override Expression VisitIndex(IndexExpression node) { if (node.Object != null) { Visit(node.Object); } else { Debug.Assert(node.Indexer != null); Out(node.Indexer.DeclaringType.Name); } if (node.Indexer != null) { Out("."); Out(node.Indexer.Name); } VisitExpressions('[', node.Arguments, ']'); return node; } protected internal override Expression VisitExtension(Expression node) { // Prefer an overridden ToString, if available. var toString = node.GetType().GetMethod("ToString", Array.Empty<Type>()); if (toString.DeclaringType != typeof(Expression) && !toString.IsStatic) { Out(node.ToString()); return node; } Out("["); // For 3.5 subclasses, print the NodeType. // For Extension nodes, print the class name. if (node.NodeType == ExpressionType.Extension) { Out(node.GetType().FullName); } else { Out(node.NodeType.ToString()); } Out("]"); return node; } private void DumpLabel(LabelTarget target) { if (!String.IsNullOrEmpty(target.Name)) { Out(target.Name); } else { int labelId = GetLabelId(target); Out("UnamedLabel_" + labelId); } } #endregion } }
using System; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// Indicates that a <see cref="GrainReference"/> was not bound to the runtime before being used. /// </summary> [Serializable] public class GrainReferenceNotBoundException : OrleansException { internal GrainReferenceNotBoundException(GrainReference grainReference) : base(CreateMessage(grainReference)) { } private static string CreateMessage(GrainReference grainReference) { return $"Attempted to use a GrainReference which has not been bound to the runtime: {grainReference.ToDetailedString()}." + $" Use the {nameof(IGrainFactory)}.{nameof(IGrainFactory.BindGrainReference)} method to bind this reference to the runtime."; } internal GrainReferenceNotBoundException(string msg) : base(msg) { } internal GrainReferenceNotBoundException(string message, Exception innerException) : base(message, innerException) { } protected GrainReferenceNotBoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; /// <summary> /// Invoke method options specific to this grain reference instance /// </summary> [NonSerialized] private readonly InvokeMethodOptions invokeMethodOptions; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } internal bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal IGrainReferenceRuntime Runtime { get { if (this.runtime == null) throw new GrainReferenceNotBoundException(this); return this.runtime; } } /// <summary> /// Gets a value indicating whether this instance is bound to a runtime and hence valid for making requests. /// </summary> internal bool IsBound => this.runtime != null; internal GrainId GrainId { get; private set; } /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; [NonSerialized] private IGrainReferenceRuntime runtime; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal string GenericArguments => this.genericArguments; /// <summary>Constructs a reference to the grain with the specified Id.</summary> /// <param name="grainId">The Id of the grain to refer to.</param> /// <param name="genericArgument">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> /// <param name="observerId">Observer ID in case of an observer reference.</param> /// <param name="runtime">The runtime which this grain reference is bound to.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId, IGrainReferenceRuntime runtime) { GrainId = grainId; this.genericArguments = genericArgument; this.SystemTargetSilo = systemTargetSilo; this.observerId = observerId; this.runtime = runtime; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId, other.runtime) { this.invokeMethodOptions = other.invokeMethodOptions; } protected internal GrainReference(GrainReference other, InvokeMethodOptions invokeMethodOptions) : this(other) { this.invokeMethodOptions = invokeMethodOptions; } /// <summary>Constructs a reference to the grain with the specified ID.</summary> /// <param name="grainId">The ID of the grain to refer to.</param> /// <param name="runtime">The runtime client</param> /// <param name="genericArguments">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> internal static GrainReference FromGrainId(GrainId grainId, IGrainReferenceRuntime runtime, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null, runtime); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId, IGrainReferenceRuntime runtime) { return new GrainReference(grainId, null, null, observerId, runtime); } /// <summary> /// Binds this instance to a runtime. /// </summary> /// <param name="runtime">The runtime.</param> internal void Bind(IGrainReferenceRuntime runtime) { this.runtime = runtime; } /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> public virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual ushort InterfaceVersion { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> public virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo); } /// <summary> /// Called from generated code. /// </summary> protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { return this.Runtime.InvokeMethodAsync<T>(this, methodId, arguments, options | invokeMethodOptions, silo); } private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string OBSERVER_ID_STR = "ObserverId"; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } internal static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key"); string trimmed = key.Trim(); string grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim(); string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length); if (String.IsNullOrEmpty(genericStr)) { genericStr = null; } return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, genericStr); } else if (observerIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim(); string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length); GuidId observerId = GuidId.FromParsableString(observerIdStr); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId, runtime); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, null, siloAddress); } else { grainIdStr = trimmed.Substring(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime); } } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; var serializerContext = context.Context as ISerializerContext; this.runtime = serializerContext?.ServiceProvider.GetService(typeof(IGrainReferenceRuntime)) as IGrainReferenceRuntime; } } }
namespace DotNetXri.Client.Xml { using System.Xml; public abstract class SEPElement : Cloneable, Serializable { //protected static org.apache.commons.logging.Log soLog = // org.apache.commons.logging.LogFactory.getLog( // typeof(XRD).Name); /** * Default value of the match attribute if it was omitted or its * value is null. This is an alias for <code>MATCH_ATTR_CONTENT</code> * as defined in xri-resolution-v2.0-wd-10-ed-08. */ public const string MATCH_ATTR_DEFAULT = "default"; public const string MATCH_ATTR_ANY = "any"; public const string MATCH_ATTR_NON_NULL = "non-null"; public const string MATCH_ATTR_NULL = "null"; /** * @deprecated */ public const string MATCH_ATTR_CONTENT = "content"; /** * @deprecated */ public const string MATCH_ATTR_NONE = "none"; public const string SELECT_ATTR_TRUE = "true"; public const string SELECT_ATTR_FALSE = "false"; /** * Default value of the select attribute is FALSE if it was omitted * in the parent element. */ public const string DEFAULT_SELECT_ATTR = SELECT_ATTR_FALSE; public const bool DEFAULT_SELECT_ATTR_BOOL = false; private string match; // null or one of the MATCH_ATTR_* constants private bool? select; private string value; // represents the value of this rule /** * Creates a default <code>SEPElement</code> obj */ public SEPElement(): this("", null, null) { } /** * Creates a <code>SEPElement with required attributes</code> obj with the given value */ public SEPElement( string value, string match, bool? select ) { setMatch(match); setSelect(select); setValue(value); } /** * Gets the "match" attribute of this Type/MediaType/Path rule */ public string getMatch() { return this.match; } /** * Sets the "match" attribute of this Type/MediaType/Path rule */ public void setMatch( string match ) { this.match = match; } /** * Gets the "select" attribute of this Type/MediaType/Path rule */ public bool getSelect() { if ( this.select.HasValue ) { return this.select.Value; } else { return DEFAULT_SELECT_ATTR_BOOL; } } /** * Sets the "select" attribute of this Type/MediaType/Path rule */ public void setSelect( bool? select ) { this.select = select; } /** * Sets the "select" attribute of this Type/MediaType/Path rule. * Interprets "true" (any case) or "1" as TRUE. Any other value * is considered FALSE. */ public void setSelect( string select ) { if (select == null) this.select = null; else if (select.Equals("true", System.StringComparison.OrdinalIgnoreCase) || select.Equals("1")) this.select = true; else this.select = true; } /** * Gets the value of this Type/MediaType/Path rule */ public string getValue() { return this.value; } /** * Sets the value of this Type/MediaType/Path rule */ public void setValue( string value ) { this.value = (value == null)? "" : value; } public XmlElement toXML( XmlDocument doc, string tag ) { XmlElement body = doc.CreateElement(tag); if( this.match != null ) { body.SetAttribute("match", this.match); } if( this.select != null ) { body.SetAttribute("select", this.select.ToString()); } if( this.value != null) { body.AppendChild(doc.CreateTextNode(this.value)); } return body; } public void setFromXML( XmlNode root ) { XmlElement el = (XmlElement)root; if (el.HasAttribute("match")) { setMatch(el.GetAttribute("match").Trim()); } if (el.HasAttribute("select")) { setSelect(el.GetAttribute("select").Trim()); } this.setValue(el.InnerText); } protected string ToString( string tag ) { XmlDocument doc = new XmlDocument(); XmlElement elm = this.toXML(doc, tag); doc.AppendChild(elm); return doc.OuterXml; } //public Object clone() //throws CloneNotSupportedException //{ // return base.clone(); //} public override bool Equals(object o) { SEPElement other = (SEPElement) o; if (other == null) return(false); if (other == this) return(true); if (this.match == null && other.match != null) return(false); if (this.match != null && ! (this.match.Equals(other.match))) return(false); if (this.select == null && other.select != null) return(false); if (this.select != null && ! (this.select.Equals(other.select))) return(false); if (this.value == null && other.value != null) return(false); if (this.value != null && ! (this.value.Equals(other.value))) return(false); return(true); } public int GetHashCode() { int h = 1; if (this.match != null) h *= this.match.GetHashCode(); if (this.select != null) h *= this.select.GetHashCode(); if (this.value != null) h *= this.value.GetHashCode(); return(h); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web.Script.Serialization; // Note: To enable JSON (JavaScriptSerializer) add following reference: System.Web.Extensions namespace ModifyOrder { public class hftRequest { public getAuthorizationChallengeRequest getAuthorizationChallenge { get; set; } public getAuthorizationTokenRequest getAuthorizationToken { get; set; } public modifyOrderRequest modifyOrder { get; set; } } public class hftResponse { public getAuthorizationChallengeResponse getAuthorizationChallengeResponse { get; set; } public getAuthorizationTokenResponse getAuthorizationTokenResponse { get; set; } public modifyOrderResponse modifyOrderResponse { get; set; } } public class getAuthorizationChallengeRequest { public string user { get; set; } public getAuthorizationChallengeRequest(String user) { this.user = user; } } public class getAuthorizationChallengeResponse { public string challenge { get; set; } public string timestamp { get; set; } } public class getAuthorizationTokenRequest { public string user { get; set; } public string challengeresp { get; set; } public getAuthorizationTokenRequest(String user, String challengeresp) { this.user = user; this.challengeresp = challengeresp; } } public class getAuthorizationTokenResponse { public string token { get; set; } public string timestamp { get; set; } } public class modifyOrderRequest { public string user { get; set; } public string token { get; set; } public List<modOrder> order { get; set; } public modifyOrderRequest(string user, string token, List<modOrder> order) { this.user = user; this.token = token; this.order = order; } } public class modifyOrderResponse { public List<modifyTick> order { get; set; } public string message { get; set; } public string timestamp { get; set; } } public class modOrder { public string fixid { get; set; } public double price { get; set; } public int quantity { get; set; } } public class modifyTick { public string fixid { get; set; } public string result { get; set; } } class ModifyOrder { private static bool ssl = true; private static String URL = "/modifyOrder"; private static String domain; //private static String url_stream; private static String url_polling; private static String url_challenge; private static String url_token; private static String user; private static String password; private static String authentication_port; private static String request_port; private static String ssl_cert; private static String challenge; private static String token; //private static int interval; public static void Exec() { // get properties from file getProperties(); HttpWebRequest httpWebRequest; JavaScriptSerializer serializer; HttpWebResponse httpResponse; X509Certificate certificate1 = null; if (ssl) { using (WebClient client = new WebClient()) { client.DownloadFile(ssl_cert, "ssl.cert"); } certificate1 = new X509Certificate("ssl.cert"); } // get challenge httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_challenge); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.getAuthorizationChallenge = new getAuthorizationChallengeRequest(user); streamWriter.WriteLine(serializer.Serialize(request)); } httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; try { response = serializer.Deserialize<hftResponse>(streamReader.ReadLine()); challenge = response.getAuthorizationChallengeResponse.challenge; } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } // create challenge response String res = challenge; char[] passwordArray = password.ToCharArray(); foreach (byte passwordLetter in passwordArray) { int value = Convert.ToInt32(passwordLetter); string hexOutput = String.Format("{0:X}", value); res = res + hexOutput; } int NumberChars = res.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) { bytes[i / 2] = Convert.ToByte(res.Substring(i, 2), 16); } SHA1 sha = new SHA1CryptoServiceProvider(); byte[] tokenArray = sha.ComputeHash(bytes); string challengeresp = BitConverter.ToString(tokenArray); challengeresp = challengeresp.Replace("-", ""); // get token with challenge response httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_token); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.getAuthorizationToken = new getAuthorizationTokenRequest(user, challengeresp); streamWriter.WriteLine(serializer.Serialize(request)); } httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; try { response = serializer.Deserialize<hftResponse>(streamReader.ReadLine()); token = response.getAuthorizationTokenResponse.token; } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } // ----------------------------------------- // Prepare and send a modifyOrder request for two pending orders // ----------------------------------------- modOrder order1 = new modOrder(); order1.fixid = "TRD_20151007112351168_0128"; order1.price = 1.11005; order1.quantity = 20000; modOrder order2 = new modOrder(); order2.fixid = "TRD_20151007112401904_0127"; order2.price = 1.11006; order2.quantity = 30000; httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + request_port + url_polling + URL); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.modifyOrder = new modifyOrderRequest(user, token, new List<modOrder> { order1, order2 }); streamWriter.WriteLine(serializer.Serialize(request)); } // -------------------------------------------------------------- // Wait for response from server (polling) // -------------------------------------------------------------- httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; String line; try { while ((line = streamReader.ReadLine()) != null) { response = serializer.Deserialize<hftResponse>(line); if (response.modifyOrderResponse != null) { if (response.modifyOrderResponse.order != null) { foreach (modifyTick tick in response.modifyOrderResponse.order) { Console.WriteLine("Result from server: " + tick.fixid + "-" + tick.result); } } if (response.modifyOrderResponse.message != null) { Console.WriteLine("Message from server: " + response.modifyOrderResponse.message); } } } } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } } private static void getProperties() { try { foreach (var row in File.ReadAllLines("config.properties")) { //Console.WriteLine(row); /* if ("url-stream".Equals(row.Split('=')[0])) { url_stream = row.Split('=')[1]; } */ if ("url-polling".Equals(row.Split('=')[0])) { url_polling = row.Split('=')[1]; } if ("url-challenge".Equals(row.Split('=')[0])) { url_challenge = row.Split('=')[1]; } if ("url-token".Equals(row.Split('=')[0])) { url_token = row.Split('=')[1]; } if ("user".Equals(row.Split('=')[0])) { user = row.Split('=')[1]; } if ("password".Equals(row.Split('=')[0])) { password = row.Split('=')[1]; } /* if ("interval".Equals(row.Split('=')[0])) { interval = Int32.Parse(row.Split('=')[1]); } */ if (ssl) { if ("ssl-domain".Equals(row.Split('=')[0])) { domain = row.Split('=')[1]; } if ("ssl-authentication-port".Equals(row.Split('=')[0])) { authentication_port = row.Split('=')[1]; } if ("ssl-request-port".Equals(row.Split('=')[0])) { request_port = row.Split('=')[1]; } if ("ssl-cert".Equals(row.Split('=')[0])) { ssl_cert = row.Split('=')[1]; } } else { if ("domain".Equals(row.Split('=')[0])) { domain = row.Split('=')[1]; } if ("authentication-port".Equals(row.Split('=')[0])) { authentication_port = row.Split('=')[1]; } if ("request-port".Equals(row.Split('=')[0])) { request_port = row.Split('=')[1]; } } } } catch (IOException ex) { Console.WriteLine(ex.Message); } } } }
namespace Rawr.ProtPaladin { partial class CalculationOptionsPanelProtPaladin { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label2 = new System.Windows.Forms.Label(); this.trackBarTargetArmor = new System.Windows.Forms.TrackBar(); this.labelTargetArmorDescription = new System.Windows.Forms.Label(); this.groupBoxPaladinSkills = new System.Windows.Forms.GroupBox(); this.radioButtonSoR = new System.Windows.Forms.RadioButton(); this.radioButtonSoV = new System.Windows.Forms.RadioButton(); this.labelBossAttack = new Rawr.CustomControls.ExtendedToolTipLabel(); this.trackBarBossAttackValue = new System.Windows.Forms.TrackBar(); this.labelBossAttackValue = new System.Windows.Forms.Label(); this.labelThreatScaleText = new Rawr.CustomControls.ExtendedToolTipLabel(); this.trackBarThreatScale = new System.Windows.Forms.TrackBar(); this.labelThreatScale = new System.Windows.Forms.Label(); this.trackBarMitigationScale = new System.Windows.Forms.TrackBar(); this.labelMitigationScale = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.labelCustomSurvivalSoftCap = new Rawr.CustomControls.ExtendedToolTipLabel(); this.labelSurvivalSoftCap = new Rawr.CustomControls.ExtendedToolTipLabel(); this.numericUpDownSurvivalSoftCap = new System.Windows.Forms.NumericUpDown(); this.comboBoxSurvivalSoftCap = new System.Windows.Forms.ComboBox(); this.extendedToolTipDamageTakenMode = new Rawr.CustomControls.ExtendedToolTipLabel(); this.extendedToolTipProtWarrMode = new Rawr.CustomControls.ExtendedToolTipLabel(); this.radioButtonDamageTakenMode = new System.Windows.Forms.RadioButton(); this.radioButtonProtWarrMode = new System.Windows.Forms.RadioButton(); this.extendedToolTipDamageOutput = new Rawr.CustomControls.ExtendedToolTipLabel(); this.radioButtonDamageOutput = new System.Windows.Forms.RadioButton(); this.extendedToolTipBurstTime = new Rawr.CustomControls.ExtendedToolTipLabel(); this.extendedToolTipMitigationScale = new Rawr.CustomControls.ExtendedToolTipLabel(); this.extendedToolTipTankPoints = new Rawr.CustomControls.ExtendedToolTipLabel(); this.radioButtonBurstTime = new System.Windows.Forms.RadioButton(); this.radioButtonTankPoints = new System.Windows.Forms.RadioButton(); this.radioButtonMitigationScale = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBoxTargetType = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.numericUpDownTargetLevel = new System.Windows.Forms.NumericUpDown(); this.extendedToolTipUseParryHaste = new Rawr.CustomControls.ExtendedToolTipLabel(); this.labelBossSpeed = new Rawr.CustomControls.ExtendedToolTipLabel(); this.checkBoxUseParryHaste = new System.Windows.Forms.CheckBox(); this.labelBossAttackSpeed = new System.Windows.Forms.Label(); this.trackBarBossAttackSpeed = new System.Windows.Forms.TrackBar(); this.groupBoxPaladinAbilities = new System.Windows.Forms.GroupBox(); this.checkBoxUseHolyShield = new System.Windows.Forms.CheckBox(); this.Glyphs = new System.Windows.Forms.TabControl(); this.tabPageTarget = new System.Windows.Forms.TabPage(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.comboBoxMagicDamageType = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.labelBossMagicSpeed = new System.Windows.Forms.Label(); this.labelBossMagicalDamage = new System.Windows.Forms.Label(); this.extendedToolTipLabel1 = new Rawr.CustomControls.ExtendedToolTipLabel(); this.trackBarBossAttackValueMagic = new System.Windows.Forms.TrackBar(); this.extendedToolTipLabel2 = new Rawr.CustomControls.ExtendedToolTipLabel(); this.trackBarBossAttackSpeedMagic = new System.Windows.Forms.TrackBar(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.tabPageRanking = new System.Windows.Forms.TabPage(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.extendedToolTipLabel3 = new Rawr.CustomControls.ExtendedToolTipLabel(); this.comboBoxTrinketOnUseHandling = new System.Windows.Forms.ComboBox(); this.tabPageAbilities = new System.Windows.Forms.TabPage(); this.CK_PTRMode = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize)(this.trackBarTargetArmor)).BeginInit(); this.groupBoxPaladinSkills.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackValue)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarThreatScale)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarMitigationScale)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownSurvivalSoftCap)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownTargetLevel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackSpeed)).BeginInit(); this.groupBoxPaladinAbilities.SuspendLayout(); this.Glyphs.SuspendLayout(); this.tabPageTarget.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackValueMagic)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackSpeedMagic)).BeginInit(); this.groupBox3.SuspendLayout(); this.tabPageRanking.SuspendLayout(); this.groupBox5.SuspendLayout(); this.tabPageAbilities.SuspendLayout(); this.SuspendLayout(); // // label2 // this.label2.Location = new System.Drawing.Point(3, 45); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(83, 60); this.label2.TabIndex = 4; this.label2.Text = "Target Armor: doubleclick (here)\r\nto reset"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.label2.DoubleClick += new System.EventHandler(this.numericUpDownTargetLevel_ValueChanged); // // trackBarTargetArmor // this.trackBarTargetArmor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarTargetArmor.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarTargetArmor.LargeChange = 1000; this.trackBarTargetArmor.Location = new System.Drawing.Point(86, 45); this.trackBarTargetArmor.Maximum = 20000; this.trackBarTargetArmor.Name = "trackBarTargetArmor"; this.trackBarTargetArmor.Size = new System.Drawing.Size(181, 42); this.trackBarTargetArmor.TabIndex = 5; this.trackBarTargetArmor.TickFrequency = 1000; this.trackBarTargetArmor.Value = 10643; this.trackBarTargetArmor.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // labelTargetArmorDescription // this.labelTargetArmorDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelTargetArmorDescription.Location = new System.Drawing.Point(92, 82); this.labelTargetArmorDescription.Name = "labelTargetArmorDescription"; this.labelTargetArmorDescription.Size = new System.Drawing.Size(172, 34); this.labelTargetArmorDescription.TabIndex = 6; this.labelTargetArmorDescription.Text = "10643: Tier 8 Bosses"; // // groupBoxPaladinSkills // this.groupBoxPaladinSkills.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBoxPaladinSkills.Controls.Add(this.radioButtonSoR); this.groupBoxPaladinSkills.Controls.Add(this.radioButtonSoV); this.groupBoxPaladinSkills.Location = new System.Drawing.Point(6, 6); this.groupBoxPaladinSkills.Name = "groupBoxPaladinSkills"; this.groupBoxPaladinSkills.Size = new System.Drawing.Size(270, 73); this.groupBoxPaladinSkills.TabIndex = 0; this.groupBoxPaladinSkills.TabStop = false; this.groupBoxPaladinSkills.Text = "Seal Choice"; // // radioButtonSoR // this.radioButtonSoR.Location = new System.Drawing.Point(6, 38); this.radioButtonSoR.Name = "radioButtonSoR"; this.radioButtonSoR.Size = new System.Drawing.Size(216, 24); this.radioButtonSoR.TabIndex = 1; this.radioButtonSoR.TabStop = true; this.radioButtonSoR.Text = "Seal of Righteousness"; this.radioButtonSoR.UseVisualStyleBackColor = true; this.radioButtonSoR.CheckedChanged += new System.EventHandler(this.radioButtonSealChoice_CheckedChanged); // // radioButtonSoV // this.radioButtonSoV.Checked = true; this.radioButtonSoV.Location = new System.Drawing.Point(6, 19); this.radioButtonSoV.Name = "radioButtonSoV"; this.radioButtonSoV.Size = new System.Drawing.Size(216, 24); this.radioButtonSoV.TabIndex = 0; this.radioButtonSoV.TabStop = true; this.radioButtonSoV.Text = "Seal of Vengeance"; this.radioButtonSoV.UseVisualStyleBackColor = true; this.radioButtonSoV.CheckedChanged += new System.EventHandler(this.radioButtonSealChoice_CheckedChanged); // // labelBossAttack // this.labelBossAttack.Location = new System.Drawing.Point(6, 17); this.labelBossAttack.Name = "labelBossAttack"; this.labelBossAttack.Size = new System.Drawing.Size(83, 45); this.labelBossAttack.TabIndex = 0; this.labelBossAttack.Text = "Base Attack: * (Default: 80000)"; this.labelBossAttack.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.labelBossAttack.ToolTipText = "Base attacker damage before armor."; // // trackBarBossAttackValue // this.trackBarBossAttackValue.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarBossAttackValue.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarBossAttackValue.LargeChange = 5000; this.trackBarBossAttackValue.Location = new System.Drawing.Point(89, 17); this.trackBarBossAttackValue.Maximum = 300000; this.trackBarBossAttackValue.Minimum = 500; this.trackBarBossAttackValue.Name = "trackBarBossAttackValue"; this.trackBarBossAttackValue.Size = new System.Drawing.Size(178, 42); this.trackBarBossAttackValue.SmallChange = 500; this.trackBarBossAttackValue.TabIndex = 1; this.trackBarBossAttackValue.TickFrequency = 5000; this.trackBarBossAttackValue.Value = 50000; this.trackBarBossAttackValue.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // labelBossAttackValue // this.labelBossAttackValue.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelBossAttackValue.AutoSize = true; this.labelBossAttackValue.Location = new System.Drawing.Point(95, 49); this.labelBossAttackValue.Name = "labelBossAttackValue"; this.labelBossAttackValue.Size = new System.Drawing.Size(37, 13); this.labelBossAttackValue.TabIndex = 2; this.labelBossAttackValue.Text = "50000"; // // labelThreatScaleText // this.labelThreatScaleText.Location = new System.Drawing.Point(6, 16); this.labelThreatScaleText.Name = "labelThreatScaleText"; this.labelThreatScaleText.Size = new System.Drawing.Size(80, 45); this.labelThreatScaleText.TabIndex = 0; this.labelThreatScaleText.Text = "Threat Scale: * (Default: 1.0)"; this.labelThreatScaleText.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.labelThreatScaleText.ToolTipText = "Threat scaling factor. PageUp/PageDown/Left Arrow/Right Arrow allows more accurat" + "e changes"; // // trackBarThreatScale // this.trackBarThreatScale.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarThreatScale.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarThreatScale.LargeChange = 50; this.trackBarThreatScale.Location = new System.Drawing.Point(86, 16); this.trackBarThreatScale.Maximum = 300; this.trackBarThreatScale.Name = "trackBarThreatScale"; this.trackBarThreatScale.Size = new System.Drawing.Size(178, 42); this.trackBarThreatScale.TabIndex = 1; this.trackBarThreatScale.TickFrequency = 10; this.trackBarThreatScale.Value = 100; this.trackBarThreatScale.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // labelThreatScale // this.labelThreatScale.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelThreatScale.AutoSize = true; this.labelThreatScale.Location = new System.Drawing.Point(92, 48); this.labelThreatScale.Name = "labelThreatScale"; this.labelThreatScale.Size = new System.Drawing.Size(22, 13); this.labelThreatScale.TabIndex = 2; this.labelThreatScale.Text = "1.0"; // // trackBarMitigationScale // this.trackBarMitigationScale.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarMitigationScale.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarMitigationScale.LargeChange = 50; this.trackBarMitigationScale.Location = new System.Drawing.Point(86, 67); this.trackBarMitigationScale.Maximum = 300; this.trackBarMitigationScale.Name = "trackBarMitigationScale"; this.trackBarMitigationScale.Size = new System.Drawing.Size(178, 42); this.trackBarMitigationScale.TabIndex = 3; this.trackBarMitigationScale.TickFrequency = 10; this.trackBarMitigationScale.Value = 100; this.trackBarMitigationScale.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // labelMitigationScale // this.labelMitigationScale.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelMitigationScale.AutoSize = true; this.labelMitigationScale.Location = new System.Drawing.Point(92, 99); this.labelMitigationScale.Name = "labelMitigationScale"; this.labelMitigationScale.Size = new System.Drawing.Size(22, 13); this.labelMitigationScale.TabIndex = 4; this.labelMitigationScale.Text = "1.0"; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.labelCustomSurvivalSoftCap); this.groupBox1.Controls.Add(this.labelSurvivalSoftCap); this.groupBox1.Controls.Add(this.numericUpDownSurvivalSoftCap); this.groupBox1.Controls.Add(this.comboBoxSurvivalSoftCap); this.groupBox1.Controls.Add(this.extendedToolTipDamageTakenMode); this.groupBox1.Controls.Add(this.extendedToolTipProtWarrMode); this.groupBox1.Controls.Add(this.radioButtonDamageTakenMode); this.groupBox1.Controls.Add(this.radioButtonProtWarrMode); this.groupBox1.Controls.Add(this.extendedToolTipDamageOutput); this.groupBox1.Controls.Add(this.radioButtonDamageOutput); this.groupBox1.Controls.Add(this.extendedToolTipBurstTime); this.groupBox1.Controls.Add(this.extendedToolTipMitigationScale); this.groupBox1.Controls.Add(this.extendedToolTipTankPoints); this.groupBox1.Controls.Add(this.radioButtonBurstTime); this.groupBox1.Controls.Add(this.radioButtonTankPoints); this.groupBox1.Controls.Add(this.labelThreatScale); this.groupBox1.Controls.Add(this.trackBarThreatScale); this.groupBox1.Controls.Add(this.labelMitigationScale); this.groupBox1.Controls.Add(this.labelThreatScaleText); this.groupBox1.Controls.Add(this.trackBarMitigationScale); this.groupBox1.Controls.Add(this.radioButtonMitigationScale); this.groupBox1.Location = new System.Drawing.Point(6, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(270, 290); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Ranking System"; // // labelCustomSurvivalSoftCap // this.labelCustomSurvivalSoftCap.AutoSize = true; this.labelCustomSurvivalSoftCap.Location = new System.Drawing.Point(6, 264); this.labelCustomSurvivalSoftCap.Name = "labelCustomSurvivalSoftCap"; this.labelCustomSurvivalSoftCap.Size = new System.Drawing.Size(137, 13); this.labelCustomSurvivalSoftCap.TabIndex = 19; this.labelCustomSurvivalSoftCap.Text = "Custom Survival Soft Cap: *"; this.labelCustomSurvivalSoftCap.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.labelCustomSurvivalSoftCap.ToolTipText = "The exact point at which Rawr applies Diminishing Returns on your Survival score." + ""; // // labelSurvivalSoftCap // this.labelSurvivalSoftCap.AutoSize = true; this.labelSurvivalSoftCap.Location = new System.Drawing.Point(6, 238); this.labelSurvivalSoftCap.Name = "labelSurvivalSoftCap"; this.labelSurvivalSoftCap.Size = new System.Drawing.Size(99, 13); this.labelSurvivalSoftCap.TabIndex = 17; this.labelSurvivalSoftCap.Text = "Survival Soft Cap: *"; this.labelSurvivalSoftCap.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.labelSurvivalSoftCap.ToolTipText = "Select the dungeon you wish to tank, and Rawr will automatically determine the po" + "int at which Diminishing Returns should apply to your Survival score."; // // numericUpDownSurvivalSoftCap // this.numericUpDownSurvivalSoftCap.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.numericUpDownSurvivalSoftCap.Increment = new decimal(new int[] { 1000, 0, 0, 0}); this.numericUpDownSurvivalSoftCap.Location = new System.Drawing.Point(147, 262); this.numericUpDownSurvivalSoftCap.Maximum = new decimal(new int[] { 999999, 0, 0, 0}); this.numericUpDownSurvivalSoftCap.Name = "numericUpDownSurvivalSoftCap"; this.numericUpDownSurvivalSoftCap.Size = new System.Drawing.Size(117, 20); this.numericUpDownSurvivalSoftCap.TabIndex = 20; this.numericUpDownSurvivalSoftCap.ThousandsSeparator = true; this.numericUpDownSurvivalSoftCap.Value = new decimal(new int[] { 160000, 0, 0, 0}); this.numericUpDownSurvivalSoftCap.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // comboBoxSurvivalSoftCap // this.comboBoxSurvivalSoftCap.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBoxSurvivalSoftCap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxSurvivalSoftCap.FormattingEnabled = true; this.comboBoxSurvivalSoftCap.Items.AddRange(new object[] { "Normal Dungeons", "Heroic Dungeons", "T7 Raids (10)", "T7 Raids (25)", "T8 Raids (10)", "T8 Raids (10, Hard)", "T8 Raids (25)", "T8 Raids (25, Hard)", "T9 Raids (10)", "T9 Raids (10, Heroic)", "T9 Raids (25)", "T9 Raids (25, Heroic)", "T10 Raids (10)", "T10 Raids (10, Heroic)", "T10 Raids (25)", "T10 Raids (25, Heroic)", "Lich King (10)", "Lich King (10, Heroic)", "Lich King (25)", "Lich King (25, Heroic)", "Custom..."}); this.comboBoxSurvivalSoftCap.Location = new System.Drawing.Point(147, 235); this.comboBoxSurvivalSoftCap.Name = "comboBoxSurvivalSoftCap"; this.comboBoxSurvivalSoftCap.Size = new System.Drawing.Size(117, 21); this.comboBoxSurvivalSoftCap.TabIndex = 18; this.comboBoxSurvivalSoftCap.SelectedIndexChanged += new System.EventHandler(this.comboBoxTargetDamage_SelectedIndexChanged); // // extendedToolTipDamageTakenMode // this.extendedToolTipDamageTakenMode.Location = new System.Drawing.Point(108, 214); this.extendedToolTipDamageTakenMode.Name = "extendedToolTipDamageTakenMode"; this.extendedToolTipDamageTakenMode.Size = new System.Drawing.Size(133, 18); this.extendedToolTipDamageTakenMode.TabIndex = 16; this.extendedToolTipDamageTakenMode.Text = "Damage Taken Mode *"; this.extendedToolTipDamageTakenMode.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipDamageTakenMode.ToolTipText = "Amount Damage taken in HP of Boss Attack Value (%DamageTaken * BossAttackValue) 1" + "0^scale Mitigation Points = 1 Damage Taken."; this.extendedToolTipDamageTakenMode.Click += new System.EventHandler(this.extendedToolTipDamageTakenMode_Click); // // extendedToolTipProtWarrMode // this.extendedToolTipProtWarrMode.Location = new System.Drawing.Point(108, 195); this.extendedToolTipProtWarrMode.Name = "extendedToolTipProtWarrMode"; this.extendedToolTipProtWarrMode.Size = new System.Drawing.Size(96, 18); this.extendedToolTipProtWarrMode.TabIndex = 14; this.extendedToolTipProtWarrMode.Text = "ProtWarr Mode *"; this.extendedToolTipProtWarrMode.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipProtWarrMode.ToolTipText = "Amount Damage mitigated of BossAttackValue (%Mitigation * BossAttackValue * scale" + " * 100 * 0.125)"; this.extendedToolTipProtWarrMode.Click += new System.EventHandler(this.extendedToolProtWarrMode_Click); // // radioButtonDamageTakenMode // this.radioButtonDamageTakenMode.AutoSize = true; this.radioButtonDamageTakenMode.Location = new System.Drawing.Point(95, 217); this.radioButtonDamageTakenMode.Name = "radioButtonDamageTakenMode"; this.radioButtonDamageTakenMode.Size = new System.Drawing.Size(14, 13); this.radioButtonDamageTakenMode.TabIndex = 15; this.radioButtonDamageTakenMode.UseVisualStyleBackColor = true; this.radioButtonDamageTakenMode.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // radioButtonProtWarrMode // this.radioButtonProtWarrMode.AutoSize = true; this.radioButtonProtWarrMode.Location = new System.Drawing.Point(95, 198); this.radioButtonProtWarrMode.Name = "radioButtonProtWarrMode"; this.radioButtonProtWarrMode.Size = new System.Drawing.Size(14, 13); this.radioButtonProtWarrMode.TabIndex = 13; this.radioButtonProtWarrMode.UseVisualStyleBackColor = true; this.radioButtonProtWarrMode.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // extendedToolTipDamageOutput // this.extendedToolTipDamageOutput.Location = new System.Drawing.Point(108, 176); this.extendedToolTipDamageOutput.Name = "extendedToolTipDamageOutput"; this.extendedToolTipDamageOutput.Size = new System.Drawing.Size(96, 18); this.extendedToolTipDamageOutput.TabIndex = 12; this.extendedToolTipDamageOutput.Text = "Damage Output *"; this.extendedToolTipDamageOutput.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipDamageOutput.ToolTipText = "Scale based only on potential DPS output."; this.extendedToolTipDamageOutput.Click += new System.EventHandler(this.extendedToolTipDamageOutput_Click); // // radioButtonDamageOutput // this.radioButtonDamageOutput.AutoSize = true; this.radioButtonDamageOutput.Location = new System.Drawing.Point(95, 179); this.radioButtonDamageOutput.Name = "radioButtonDamageOutput"; this.radioButtonDamageOutput.Size = new System.Drawing.Size(14, 13); this.radioButtonDamageOutput.TabIndex = 11; this.radioButtonDamageOutput.UseVisualStyleBackColor = true; this.radioButtonDamageOutput.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // extendedToolTipBurstTime // this.extendedToolTipBurstTime.Location = new System.Drawing.Point(108, 158); this.extendedToolTipBurstTime.Name = "extendedToolTipBurstTime"; this.extendedToolTipBurstTime.Size = new System.Drawing.Size(96, 16); this.extendedToolTipBurstTime.TabIndex = 10; this.extendedToolTipBurstTime.Text = "Burst Time *"; this.extendedToolTipBurstTime.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipBurstTime.ToolTipText = "Scale based on the average time an event will occur which has a chance to burst d" + "own the player."; this.extendedToolTipBurstTime.Click += new System.EventHandler(this.extendedToolTipBurstTime_Click); // // extendedToolTipMitigationScale // this.extendedToolTipMitigationScale.Location = new System.Drawing.Point(108, 120); this.extendedToolTipMitigationScale.Name = "extendedToolTipMitigationScale"; this.extendedToolTipMitigationScale.Size = new System.Drawing.Size(96, 15); this.extendedToolTipMitigationScale.TabIndex = 6; this.extendedToolTipMitigationScale.Text = "Mitigation Scale *"; this.extendedToolTipMitigationScale.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipMitigationScale.ToolTipText = "Customizable scale that allows you to weight mitigation vs. effective health. (De" + "fault) Mitigation Points = (17000 * scale) / %DamageTaken"; this.extendedToolTipMitigationScale.Click += new System.EventHandler(this.extendedToolTipMitigtionScale_Click); // // extendedToolTipTankPoints // this.extendedToolTipTankPoints.Location = new System.Drawing.Point(108, 141); this.extendedToolTipTankPoints.Name = "extendedToolTipTankPoints"; this.extendedToolTipTankPoints.Size = new System.Drawing.Size(96, 13); this.extendedToolTipTankPoints.TabIndex = 8; this.extendedToolTipTankPoints.Text = "TankPoints *"; this.extendedToolTipTankPoints.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipTankPoints.ToolTipText = "Scale based on the average amount of unmitigated base damage needed to kill the p" + "layer."; this.extendedToolTipTankPoints.Click += new System.EventHandler(this.extendedToolTipTankPoints_Click); // // radioButtonBurstTime // this.radioButtonBurstTime.AutoSize = true; this.radioButtonBurstTime.Location = new System.Drawing.Point(95, 160); this.radioButtonBurstTime.Name = "radioButtonBurstTime"; this.radioButtonBurstTime.Size = new System.Drawing.Size(14, 13); this.radioButtonBurstTime.TabIndex = 9; this.radioButtonBurstTime.UseVisualStyleBackColor = true; this.radioButtonBurstTime.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // radioButtonTankPoints // this.radioButtonTankPoints.AutoSize = true; this.radioButtonTankPoints.Location = new System.Drawing.Point(95, 141); this.radioButtonTankPoints.Name = "radioButtonTankPoints"; this.radioButtonTankPoints.Size = new System.Drawing.Size(14, 13); this.radioButtonTankPoints.TabIndex = 7; this.radioButtonTankPoints.UseVisualStyleBackColor = true; this.radioButtonTankPoints.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // radioButtonMitigationScale // this.radioButtonMitigationScale.AutoSize = true; this.radioButtonMitigationScale.Checked = true; this.radioButtonMitigationScale.Location = new System.Drawing.Point(95, 122); this.radioButtonMitigationScale.Name = "radioButtonMitigationScale"; this.radioButtonMitigationScale.Size = new System.Drawing.Size(14, 13); this.radioButtonMitigationScale.TabIndex = 5; this.radioButtonMitigationScale.TabStop = true; this.radioButtonMitigationScale.UseVisualStyleBackColor = true; this.radioButtonMitigationScale.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.comboBoxTargetType); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.numericUpDownTargetLevel); this.groupBox2.Controls.Add(this.labelTargetArmorDescription); this.groupBox2.Controls.Add(this.trackBarTargetArmor); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Location = new System.Drawing.Point(6, 6); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(270, 108); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "Target Statistics"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(135, 21); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(37, 13); this.label5.TabIndex = 2; this.label5.Text = "Type: "; // // comboBoxTargetType // this.comboBoxTargetType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBoxTargetType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxTargetType.FormattingEnabled = true; this.comboBoxTargetType.Items.AddRange(new object[] { "Unspecified", "Humanoid", "Undead", "Demon", "Elemental", "Giant", "Mechanical", "Beast", "Dragonkin"}); this.comboBoxTargetType.Location = new System.Drawing.Point(175, 18); this.comboBoxTargetType.Name = "comboBoxTargetType"; this.comboBoxTargetType.Size = new System.Drawing.Size(89, 21); this.comboBoxTargetType.TabIndex = 3; this.comboBoxTargetType.SelectedIndexChanged += new System.EventHandler(this.comboBoxTargetType_SelectedIndexChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 21); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(73, 13); this.label4.TabIndex = 0; this.label4.Text = "Target Level: "; // // numericUpDownTargetLevel // this.numericUpDownTargetLevel.Location = new System.Drawing.Point(80, 19); this.numericUpDownTargetLevel.Maximum = new decimal(new int[] { 83, 0, 0, 0}); this.numericUpDownTargetLevel.Minimum = new decimal(new int[] { 80, 0, 0, 0}); this.numericUpDownTargetLevel.Name = "numericUpDownTargetLevel"; this.numericUpDownTargetLevel.Size = new System.Drawing.Size(49, 20); this.numericUpDownTargetLevel.TabIndex = 1; this.numericUpDownTargetLevel.Value = new decimal(new int[] { 80, 0, 0, 0}); this.numericUpDownTargetLevel.ValueChanged += new System.EventHandler(this.numericUpDownTargetLevel_ValueChanged); // // extendedToolTipUseParryHaste // this.extendedToolTipUseParryHaste.Location = new System.Drawing.Point(114, 118); this.extendedToolTipUseParryHaste.Name = "extendedToolTipUseParryHaste"; this.extendedToolTipUseParryHaste.Size = new System.Drawing.Size(134, 14); this.extendedToolTipUseParryHaste.TabIndex = 7; this.extendedToolTipUseParryHaste.Text = "Use Boss Parry Haste *"; this.extendedToolTipUseParryHaste.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.extendedToolTipUseParryHaste.ToolTipText = "Calculates the adjusted attacker speed based on parry hasting. May not be applica" + "ble on all bosses. (e.g. Patchwerk does not parry haste.)"; // // labelBossSpeed // this.labelBossSpeed.Location = new System.Drawing.Point(6, 68); this.labelBossSpeed.Name = "labelBossSpeed"; this.labelBossSpeed.Size = new System.Drawing.Size(83, 45); this.labelBossSpeed.TabIndex = 3; this.labelBossSpeed.Text = "Attack Speed: * (Default: 2.00s)"; this.labelBossSpeed.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.labelBossSpeed.ToolTipText = "How often (in seconds) the boss attacks with the damage above."; // // checkBoxUseParryHaste // this.checkBoxUseParryHaste.AutoSize = true; this.checkBoxUseParryHaste.Location = new System.Drawing.Point(98, 119); this.checkBoxUseParryHaste.Name = "checkBoxUseParryHaste"; this.checkBoxUseParryHaste.RightToLeft = System.Windows.Forms.RightToLeft.No; this.checkBoxUseParryHaste.Size = new System.Drawing.Size(15, 14); this.checkBoxUseParryHaste.TabIndex = 6; this.checkBoxUseParryHaste.UseVisualStyleBackColor = true; this.checkBoxUseParryHaste.CheckedChanged += new System.EventHandler(this.checkBoxUseParryHaste_CheckedChanged); // // labelBossAttackSpeed // this.labelBossAttackSpeed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelBossAttackSpeed.AutoSize = true; this.labelBossAttackSpeed.Location = new System.Drawing.Point(95, 100); this.labelBossAttackSpeed.Name = "labelBossAttackSpeed"; this.labelBossAttackSpeed.Size = new System.Drawing.Size(28, 13); this.labelBossAttackSpeed.TabIndex = 5; this.labelBossAttackSpeed.Text = "2.00"; // // trackBarBossAttackSpeed // this.trackBarBossAttackSpeed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarBossAttackSpeed.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarBossAttackSpeed.LargeChange = 4; this.trackBarBossAttackSpeed.Location = new System.Drawing.Point(89, 68); this.trackBarBossAttackSpeed.Maximum = 20; this.trackBarBossAttackSpeed.Minimum = 1; this.trackBarBossAttackSpeed.Name = "trackBarBossAttackSpeed"; this.trackBarBossAttackSpeed.Size = new System.Drawing.Size(178, 42); this.trackBarBossAttackSpeed.TabIndex = 4; this.trackBarBossAttackSpeed.Value = 8; this.trackBarBossAttackSpeed.ValueChanged += new System.EventHandler(this.calculationOptionControl_Changed); // // groupBoxPaladinAbilities // this.groupBoxPaladinAbilities.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBoxPaladinAbilities.Controls.Add(this.checkBoxUseHolyShield); this.groupBoxPaladinAbilities.Location = new System.Drawing.Point(6, 85); this.groupBoxPaladinAbilities.Name = "groupBoxPaladinAbilities"; this.groupBoxPaladinAbilities.Size = new System.Drawing.Size(270, 50); this.groupBoxPaladinAbilities.TabIndex = 1; this.groupBoxPaladinAbilities.TabStop = false; this.groupBoxPaladinAbilities.Text = "Paladin Abilities"; // // checkBoxUseHolyShield // this.checkBoxUseHolyShield.AutoSize = true; this.checkBoxUseHolyShield.Checked = true; this.checkBoxUseHolyShield.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxUseHolyShield.Location = new System.Drawing.Point(6, 19); this.checkBoxUseHolyShield.Name = "checkBoxUseHolyShield"; this.checkBoxUseHolyShield.Size = new System.Drawing.Size(101, 17); this.checkBoxUseHolyShield.TabIndex = 0; this.checkBoxUseHolyShield.Text = "Use Holy Shield"; this.checkBoxUseHolyShield.UseVisualStyleBackColor = true; this.checkBoxUseHolyShield.CheckedChanged += new System.EventHandler(this.checkBoxUseHolyShield_CheckedChanged); // // Glyphs // this.Glyphs.Controls.Add(this.tabPageTarget); this.Glyphs.Controls.Add(this.tabPageRanking); this.Glyphs.Controls.Add(this.tabPageAbilities); this.Glyphs.Location = new System.Drawing.Point(6, 6); this.Glyphs.Name = "Glyphs"; this.Glyphs.SelectedIndex = 0; this.Glyphs.Size = new System.Drawing.Size(290, 545); this.Glyphs.TabIndex = 0; // // tabPageTarget // this.tabPageTarget.Controls.Add(this.groupBox4); this.tabPageTarget.Controls.Add(this.groupBox3); this.tabPageTarget.Controls.Add(this.groupBox2); this.tabPageTarget.Location = new System.Drawing.Point(4, 22); this.tabPageTarget.Name = "tabPageTarget"; this.tabPageTarget.Padding = new System.Windows.Forms.Padding(3); this.tabPageTarget.Size = new System.Drawing.Size(282, 519); this.tabPageTarget.TabIndex = 0; this.tabPageTarget.Text = "Target"; this.tabPageTarget.UseVisualStyleBackColor = true; // // groupBox4 // this.groupBox4.Controls.Add(this.comboBoxMagicDamageType); this.groupBox4.Controls.Add(this.label6); this.groupBox4.Controls.Add(this.labelBossMagicSpeed); this.groupBox4.Controls.Add(this.labelBossMagicalDamage); this.groupBox4.Controls.Add(this.extendedToolTipLabel1); this.groupBox4.Controls.Add(this.trackBarBossAttackValueMagic); this.groupBox4.Controls.Add(this.extendedToolTipLabel2); this.groupBox4.Controls.Add(this.trackBarBossAttackSpeedMagic); this.groupBox4.Location = new System.Drawing.Point(6, 273); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(270, 166); this.groupBox4.TabIndex = 2; this.groupBox4.TabStop = false; this.groupBox4.Text = "Attacker Statistics (Magical)"; this.groupBox4.Visible = false; // // comboBoxMagicDamageType // this.comboBoxMagicDamageType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBoxMagicDamageType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxMagicDamageType.FormattingEnabled = true; this.comboBoxMagicDamageType.Items.AddRange(new object[] { "None", "Physical", "Holy", "Fire", "Nature", "Frost", "Frostfire", "Shadow", "Arcane", "Spellfire", "Naturefire"}); this.comboBoxMagicDamageType.Location = new System.Drawing.Point(95, 16); this.comboBoxMagicDamageType.Name = "comboBoxMagicDamageType"; this.comboBoxMagicDamageType.Size = new System.Drawing.Size(169, 21); this.comboBoxMagicDamageType.TabIndex = 1; this.comboBoxMagicDamageType.SelectedIndexChanged += new System.EventHandler(this.comboBoxMagicDamageType_SelectedIndexChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(6, 19); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(75, 13); this.label6.TabIndex = 0; this.label6.Text = "Magic School:"; // // labelBossMagicSpeed // this.labelBossMagicSpeed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelBossMagicSpeed.AutoSize = true; this.labelBossMagicSpeed.Location = new System.Drawing.Point(92, 131); this.labelBossMagicSpeed.Name = "labelBossMagicSpeed"; this.labelBossMagicSpeed.Size = new System.Drawing.Size(28, 13); this.labelBossMagicSpeed.TabIndex = 7; this.labelBossMagicSpeed.Text = "2.00"; // // labelBossMagicalDamage // this.labelBossMagicalDamage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelBossMagicalDamage.AutoSize = true; this.labelBossMagicalDamage.Location = new System.Drawing.Point(92, 80); this.labelBossMagicalDamage.Name = "labelBossMagicalDamage"; this.labelBossMagicalDamage.Size = new System.Drawing.Size(31, 13); this.labelBossMagicalDamage.TabIndex = 4; this.labelBossMagicalDamage.Text = "8000"; // // extendedToolTipLabel1 // this.extendedToolTipLabel1.Location = new System.Drawing.Point(3, 99); this.extendedToolTipLabel1.Name = "extendedToolTipLabel1"; this.extendedToolTipLabel1.Size = new System.Drawing.Size(83, 45); this.extendedToolTipLabel1.TabIndex = 5; this.extendedToolTipLabel1.Text = "Frequency: * (Default: 1.00s)"; this.extendedToolTipLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.extendedToolTipLabel1.ToolTipText = "How often (in seconds) the boss attacks with the damage above."; // // trackBarBossAttackValueMagic // this.trackBarBossAttackValueMagic.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarBossAttackValueMagic.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarBossAttackValueMagic.LargeChange = 1000; this.trackBarBossAttackValueMagic.Location = new System.Drawing.Point(86, 48); this.trackBarBossAttackValueMagic.Maximum = 100000; this.trackBarBossAttackValueMagic.Minimum = 500; this.trackBarBossAttackValueMagic.Name = "trackBarBossAttackValueMagic"; this.trackBarBossAttackValueMagic.Size = new System.Drawing.Size(178, 42); this.trackBarBossAttackValueMagic.TabIndex = 3; this.trackBarBossAttackValueMagic.TickFrequency = 5000; this.trackBarBossAttackValueMagic.Value = 8000; this.trackBarBossAttackValueMagic.Scroll += new System.EventHandler(this.calculationOptionControl_Changed); // // extendedToolTipLabel2 // this.extendedToolTipLabel2.Location = new System.Drawing.Point(3, 48); this.extendedToolTipLabel2.Name = "extendedToolTipLabel2"; this.extendedToolTipLabel2.Size = new System.Drawing.Size(83, 45); this.extendedToolTipLabel2.TabIndex = 2; this.extendedToolTipLabel2.Text = "Damage: * (Default: 20000)"; this.extendedToolTipLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.extendedToolTipLabel2.ToolTipText = "Base attacker damage before armor."; // // trackBarBossAttackSpeedMagic // this.trackBarBossAttackSpeedMagic.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarBossAttackSpeedMagic.BackColor = System.Drawing.SystemColors.ControlLightLight; this.trackBarBossAttackSpeedMagic.LargeChange = 40; this.trackBarBossAttackSpeedMagic.Location = new System.Drawing.Point(86, 99); this.trackBarBossAttackSpeedMagic.Maximum = 240; this.trackBarBossAttackSpeedMagic.Minimum = 4; this.trackBarBossAttackSpeedMagic.Name = "trackBarBossAttackSpeedMagic"; this.trackBarBossAttackSpeedMagic.Size = new System.Drawing.Size(178, 42); this.trackBarBossAttackSpeedMagic.TabIndex = 6; this.trackBarBossAttackSpeedMagic.TickFrequency = 40; this.trackBarBossAttackSpeedMagic.Value = 40; this.trackBarBossAttackSpeedMagic.Scroll += new System.EventHandler(this.calculationOptionControl_Changed); // // groupBox3 // this.groupBox3.Controls.Add(this.labelBossAttackSpeed); this.groupBox3.Controls.Add(this.labelBossAttackValue); this.groupBox3.Controls.Add(this.extendedToolTipUseParryHaste); this.groupBox3.Controls.Add(this.labelBossSpeed); this.groupBox3.Controls.Add(this.trackBarBossAttackValue); this.groupBox3.Controls.Add(this.checkBoxUseParryHaste); this.groupBox3.Controls.Add(this.labelBossAttack); this.groupBox3.Controls.Add(this.trackBarBossAttackSpeed); this.groupBox3.Location = new System.Drawing.Point(6, 120); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(270, 147); this.groupBox3.TabIndex = 1; this.groupBox3.TabStop = false; this.groupBox3.Text = "Attacker Statistics (Physical)"; // // tabPageRanking // this.tabPageRanking.Controls.Add(this.groupBox5); this.tabPageRanking.Controls.Add(this.groupBox1); this.tabPageRanking.Location = new System.Drawing.Point(4, 22); this.tabPageRanking.Name = "tabPageRanking"; this.tabPageRanking.Padding = new System.Windows.Forms.Padding(3); this.tabPageRanking.Size = new System.Drawing.Size(282, 519); this.tabPageRanking.TabIndex = 1; this.tabPageRanking.Text = "Ranking"; this.tabPageRanking.UseVisualStyleBackColor = true; // // groupBox5 // this.groupBox5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox5.Controls.Add(this.extendedToolTipLabel3); this.groupBox5.Controls.Add(this.comboBoxTrinketOnUseHandling); this.groupBox5.Location = new System.Drawing.Point(6, 302); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(270, 56); this.groupBox5.TabIndex = 1; this.groupBox5.TabStop = false; this.groupBox5.Text = "Trinket Handling"; // // extendedToolTipLabel3 // this.extendedToolTipLabel3.Location = new System.Drawing.Point(6, 19); this.extendedToolTipLabel3.Name = "extendedToolTipLabel3"; this.extendedToolTipLabel3.Size = new System.Drawing.Size(122, 30); this.extendedToolTipLabel3.TabIndex = 0; this.extendedToolTipLabel3.Text = "On Use - Handling*\r\n(Default: Ignore)"; this.extendedToolTipLabel3.ToolTipText = "Sets how On Use trinket effects are handled. Health is never averaged."; // // comboBoxTrinketOnUseHandling // this.comboBoxTrinketOnUseHandling.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBoxTrinketOnUseHandling.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxTrinketOnUseHandling.FormattingEnabled = true; this.comboBoxTrinketOnUseHandling.Items.AddRange(new object[] { "Ignore", "Averaged Uptime", "Active"}); this.comboBoxTrinketOnUseHandling.Location = new System.Drawing.Point(147, 19); this.comboBoxTrinketOnUseHandling.Name = "comboBoxTrinketOnUseHandling"; this.comboBoxTrinketOnUseHandling.Size = new System.Drawing.Size(117, 21); this.comboBoxTrinketOnUseHandling.TabIndex = 1; this.comboBoxTrinketOnUseHandling.SelectedIndexChanged += new System.EventHandler(this.ComboBoxTrinketOnUseHandling_SelectedIndexChanged); // // tabPageAbilities // this.tabPageAbilities.Controls.Add(this.CK_PTRMode); this.tabPageAbilities.Controls.Add(this.groupBoxPaladinAbilities); this.tabPageAbilities.Controls.Add(this.groupBoxPaladinSkills); this.tabPageAbilities.Location = new System.Drawing.Point(4, 22); this.tabPageAbilities.Name = "tabPageAbilities"; this.tabPageAbilities.Padding = new System.Windows.Forms.Padding(3); this.tabPageAbilities.Size = new System.Drawing.Size(282, 519); this.tabPageAbilities.TabIndex = 2; this.tabPageAbilities.Text = "Abilities"; this.tabPageAbilities.UseVisualStyleBackColor = true; // // CK_PTRMode // this.CK_PTRMode.AutoSize = true; this.CK_PTRMode.Location = new System.Drawing.Point(6, 141); this.CK_PTRMode.Name = "CK_PTRMode"; this.CK_PTRMode.Size = new System.Drawing.Size(78, 17); this.CK_PTRMode.TabIndex = 2; this.CK_PTRMode.Text = "PTR Mode"; this.CK_PTRMode.UseVisualStyleBackColor = true; this.CK_PTRMode.Visible = false; this.CK_PTRMode.CheckedChanged += new System.EventHandler(this.CK_PTRMode_CheckedChanged); // // CalculationOptionsPanelProtPaladin // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.Controls.Add(this.Glyphs); this.Name = "CalculationOptionsPanelProtPaladin"; this.Size = new System.Drawing.Size(304, 560); ((System.ComponentModel.ISupportInitialize)(this.trackBarTargetArmor)).EndInit(); this.groupBoxPaladinSkills.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackValue)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarThreatScale)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarMitigationScale)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownSurvivalSoftCap)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownTargetLevel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackSpeed)).EndInit(); this.groupBoxPaladinAbilities.ResumeLayout(false); this.groupBoxPaladinAbilities.PerformLayout(); this.Glyphs.ResumeLayout(false); this.tabPageTarget.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackValueMagic)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarBossAttackSpeedMagic)).EndInit(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.tabPageRanking.ResumeLayout(false); this.groupBox5.ResumeLayout(false); this.tabPageAbilities.ResumeLayout(false); this.tabPageAbilities.PerformLayout(); this.ResumeLayout(false); } private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipMitigationScale; private System.Windows.Forms.ComboBox comboBoxTrinketOnUseHandling; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipLabel3; private System.Windows.Forms.GroupBox groupBox5; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipDamageTakenMode; private System.Windows.Forms.RadioButton radioButtonProtWarrMode; private System.Windows.Forms.RadioButton radioButtonDamageTakenMode; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipProtWarrMode; #endregion private System.Windows.Forms.Label label2; private System.Windows.Forms.TrackBar trackBarTargetArmor; private System.Windows.Forms.Label labelTargetArmorDescription; private System.Windows.Forms.GroupBox groupBoxPaladinSkills; private Rawr.CustomControls.ExtendedToolTipLabel labelBossAttack; private System.Windows.Forms.TrackBar trackBarBossAttackValue; private System.Windows.Forms.Label labelBossAttackValue; private Rawr.CustomControls.ExtendedToolTipLabel labelThreatScaleText; private System.Windows.Forms.TrackBar trackBarThreatScale; private System.Windows.Forms.Label labelThreatScale; private System.Windows.Forms.TrackBar trackBarMitigationScale; private System.Windows.Forms.Label labelMitigationScale; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private Rawr.CustomControls.ExtendedToolTipLabel labelBossSpeed; private System.Windows.Forms.Label labelBossAttackSpeed; private System.Windows.Forms.TrackBar trackBarBossAttackSpeed; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipUseParryHaste; private System.Windows.Forms.CheckBox checkBoxUseParryHaste; private System.Windows.Forms.RadioButton radioButtonMitigationScale; private System.Windows.Forms.RadioButton radioButtonBurstTime; private System.Windows.Forms.RadioButton radioButtonTankPoints; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipTankPoints; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipBurstTime; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipDamageOutput; private System.Windows.Forms.RadioButton radioButtonDamageOutput; private System.Windows.Forms.RadioButton radioButtonSoR; private System.Windows.Forms.RadioButton radioButtonSoV; private System.Windows.Forms.GroupBox groupBoxPaladinAbilities; private System.Windows.Forms.CheckBox checkBoxUseHolyShield; private System.Windows.Forms.TabControl Glyphs; private System.Windows.Forms.TabPage tabPageTarget; private System.Windows.Forms.TabPage tabPageRanking; private System.Windows.Forms.TabPage tabPageAbilities; private System.Windows.Forms.NumericUpDown numericUpDownTargetLevel; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox comboBoxTargetType; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox4; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipLabel1; private System.Windows.Forms.TrackBar trackBarBossAttackValueMagic; private System.Windows.Forms.Label labelBossMagicalDamage; private Rawr.CustomControls.ExtendedToolTipLabel extendedToolTipLabel2; private System.Windows.Forms.TrackBar trackBarBossAttackSpeedMagic; private System.Windows.Forms.Label labelBossMagicSpeed; private System.Windows.Forms.ComboBox comboBoxMagicDamageType; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox CK_PTRMode; private CustomControls.ExtendedToolTipLabel labelCustomSurvivalSoftCap; private CustomControls.ExtendedToolTipLabel labelSurvivalSoftCap; private System.Windows.Forms.NumericUpDown numericUpDownSurvivalSoftCap; private System.Windows.Forms.ComboBox comboBoxSurvivalSoftCap; } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace BuildIt.CognitiveServices { /// <summary> /// </summary> public partial interface IAcademicSearchAPI : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// The interpret REST API takes an end user query string (i.e., a /// query entered by a user of your application) and returns /// formatted interpretations of user intent based on the Academic /// Graph data and the Academic Grammar. /// To provide an interactive experience, you can call this method /// repeatedly after each character entered by the user. In that /// case, you should set the complete parameter to 1 to enable /// auto-complete suggestions. If your application does not want /// auto-completion, you should set the complete parameter to 0. /// </summary> /// <param name='query'> /// Query entered by user. If complete is set to 1, query will be /// interpreted as a prefix for generating query auto-completion /// suggestions. /// </param> /// <param name='complete'> /// 1 means that auto-completion suggestions are generated based on /// the grammar and graph data. /// </param> /// <param name='count'> /// Maximum number of interpretations to return. /// </param> /// <param name='offset'> /// Index of the first interpretation to return. For example, /// count=2&amp;offset=0 returns interpretations 0 and 1. /// count=2&amp;offset=2 returns interpretations 2 and 3. /// </param> /// <param name='timeout'> /// Timeout in milliseconds. Only interpretations found before the /// timeout has elapsed are returned. /// </param> /// <param name='model'> /// Name of the model that you wish to query. Currently, the value /// defaults to "latest". /// . Possible values include: 'beta-2015', 'latest' /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> InterpretWithHttpMessagesAsync(string query, bool? complete = false, double? count = 10, double? offset = default(double?), double? timeout = default(double?), string model = "latest", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// The evaluate REST API is used to return a set of academic entities /// based on a query expression. /// </summary> /// <param name='expr'> /// A query expression that specifies which entities should be /// returned. /// </param> /// <param name='model'> /// Name of the model that you wish to query. Currently, the value /// defaults to "latest". /// . Possible values include: 'beta-2015', 'latest' /// </param> /// <param name='count'> /// Number of results to return. /// </param> /// <param name='offset'> /// Index of the first result to return. /// </param> /// <param name='orderby'> /// Name of an attribute that is used for sorting the entities. /// Optionally, ascending/descending can be specified. The format is: /// name:asc or name:desc. /// </param> /// <param name='attributes'> /// A comma delimited list that specifies the attribute values that /// are included in the response. Attribute names are case-sensitive. /// Possible values include: 'Id' /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> EvaluateWithHttpMessagesAsync(string expr, string model = "latest", double? count = 10, double? offset = 0, string orderby = default(string), string attributes = "Id", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// The calchistogram REST API is used to calculate the distribution /// of attribute values for a set of paper entities. /// </summary> /// <param name='expr'> /// A query expression that specifies the entities over which to /// calculate histograms. /// </param> /// <param name='model'> /// Name of the model that you wish to query. Currently, the value /// defaults to "latest". /// . Possible values include: 'beta-2015', 'latest' /// </param> /// <param name='attributes'> /// A comma delimited list that specifies the attribute values that /// are included in the response. Attribute names are case-sensitive. /// </param> /// <param name='count'> /// Number of results to return. /// </param> /// <param name='offset'> /// Index of the first result to return. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CalcHistogramWithHttpMessagesAsync(string expr, string model = "latest", string attributes = default(string), double? count = 10, double? offset = 0, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Welcome to the Microsoft Cognitive Service Academic Search API, a /// web service for retrieving paths and subgraphs from Microsoft /// Academic Graph. The graph query interface powered by Graph Engine /// allows us to not only query entities that meet certain criteria /// (e.g. find a paper with a given title), but also perform pattern /// matching via graph exploration (e.g. detect co-authorship). /// </summary> /// <param name='mode'> /// Request type of query. Should be "json" or "lambda". Possible /// values include: 'json', 'lambda' /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> GraphSearchWithHttpMessagesAsync(string mode, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// The similarity REST API is used to calculate a floating point /// value based on 2 text inputs. /// </summary> /// <param name='s1'> /// String to be compared, input length is bounded by the limitation /// of the length of URL. When the strings are too long to be /// processed using GET, use POST instead. /// </param> /// <param name='s2'> /// String to be compared, input length is bounded by the limitation /// of the length of URL. When the strings are too long to be /// processed using GET, use POST instead. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SimilarityWithHttpMessagesAsync(string s1, string s2, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PostsimilarityWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
/* * Copyright (c) 2009, Stefan Simek * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections.Generic; using System.Text; namespace TriAxis.RunSharp.Examples { static class _11_OperatorOverloading { // example based on the MSDN Operator Overloading Sample (complex.cs) public static void GenComplex(AssemblyGen ag) { TypeGen Complex = ag.Public.Struct("Complex"); { FieldGen real = Complex.Public.Field(typeof(int), "real"); FieldGen imaginary = Complex.Public.Field(typeof(int), "imaginary"); CodeGen g = Complex.Public.Constructor() .Parameter(typeof(int), "real") .Parameter(typeof(int), "imaginary") ; { g.Assign(real, g.Arg("real")); g.Assign(imaginary, g.Arg("imaginary")); } // Declare which operator to overload (+), the types // that can be added (two Complex objects), and the // return type (Complex): g = Complex.Operator(Operator.Add, Complex, Complex, "c1", Complex, "c2"); { Operand c1 = g.Arg("c1"), c2 = g.Arg("c2"); g.Return(Exp.New(Complex, c1.Field("real") + c2.Field("real"), c1.Field("imaginary") + c2.Field("imaginary"))); } // Override the ToString method to display an complex number in the suitable format: g = Complex.Public.Override.Method(typeof(string), "ToString"); { g.Return(Static.Invoke(typeof(string), "Format", "{0} + {1}i", real, imaginary)); } g = Complex.Public.Static.Method(typeof(void), "Main"); { Operand num1 = g.Local(Exp.New(Complex, 2, 3)); Operand num2 = g.Local(Exp.New(Complex, 3, 4)); // Add two Complex objects (num1 and num2) through the // overloaded plus operator: Operand sum = g.Local(num1 + num2); // Print the numbers and the sum using the overriden ToString method: g.WriteLine("First complex number: {0}", num1); g.WriteLine("Second complex number: {0}", num2); g.WriteLine("The sum of the two numbers: {0}", sum); } } } // example based on the MSDN Operator Overloading Sample (dbbool.cs) public static void GenDbBool(AssemblyGen ag) { TypeGen DBBool = ag.Public.Struct("DBBool"); { // Private field that stores -1, 0, 1 for dbFalse, dbNull, dbTrue: FieldGen value = DBBool.Field(typeof(int), "value"); // Private constructor. The value parameter must be -1, 0, or 1: CodeGen g = DBBool.Constructor().Parameter(typeof(int), "value"); { g.Assign(value, g.Arg("value")); } // The three possible DBBool values: FieldGen dbNull = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbNull", Exp.New(DBBool, 0)); FieldGen dbFalse = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbFalse", Exp.New(DBBool, -1)); FieldGen dbTrue = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbTrue", Exp.New(DBBool, 1)); // Implicit conversion from bool to DBBool. Maps true to // DBBool.dbTrue and false to DBBool.dbFalse: g = DBBool.ImplicitConversionFrom(typeof(bool), "x"); { Operand x = g.Arg("x"); g.Return(x.Conditional(dbTrue, dbFalse)); } // Explicit conversion from DBBool to bool. Throws an // exception if the given DBBool is dbNull, otherwise returns // true or false: g = DBBool.ExplicitConversionTo(typeof(bool), "x"); { Operand x = g.Arg("x"); g.If(x.Field("value") == 0); { g.Throw(Exp.New(typeof(InvalidOperationException))); } g.End(); g.Return(x.Field("value") > 0); } // Equality operator. Returns dbNull if either operand is dbNull, // otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Equality, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") == y.Field("value")).Conditional(dbTrue, dbFalse)); } // Inequality operator. Returns dbNull if either operand is // dbNull, otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Inequality, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") != y.Field("value")).Conditional(dbTrue, dbFalse)); } // Logical negation operator. Returns dbTrue if the operand is // dbFalse, dbNull if the operand is dbNull, or dbFalse if the // operand is dbTrue: g = DBBool.Operator(Operator.LogicalNot, DBBool, DBBool, "x"); { Operand x = g.Arg("x"); g.Return(Exp.New(DBBool, -x.Field("value"))); } // Logical AND operator. Returns dbFalse if either operand is // dbFalse, dbNull if either operand is dbNull, otherwise dbTrue: g = DBBool.Operator(Operator.And, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.Return(Exp.New(DBBool, (x.Field("value") < y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Logical OR operator. Returns dbTrue if either operand is // dbTrue, dbNull if either operand is dbNull, otherwise dbFalse: g = DBBool.Operator(Operator.Or, DBBool, DBBool, "x", DBBool, "y"); { Operand x = g.Arg("x"), y = g.Arg("y"); g.Return(Exp.New(DBBool, (x.Field("value") > y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Definitely true operator. Returns true if the operand is // dbTrue, false otherwise: g = DBBool.Operator(Operator.True, typeof(bool), DBBool, "x"); { Operand x = g.Arg("x"); g.Return(x.Field("value") > 0); } // Definitely false operator. Returns true if the operand is // dbFalse, false otherwise: g = DBBool.Operator(Operator.False, typeof(bool), DBBool, "x"); { Operand x = g.Arg("x"); g.Return(x.Field("value") < 0); } // Overload the conversion from DBBool to string: g = DBBool.ImplicitConversionTo(typeof(string), "x"); { Operand x = g.Arg("x"); g.Return((x.Field("value") > 0).Conditional("dbTrue", (x.Field("value") < 0).Conditional("dbFalse", "dbNull"))); } // Override the Object.Equals(object o) method: g = DBBool.Public.Override.Method(typeof(bool), "Equals").Parameter(typeof(object), "o"); { g.Try(); { g.Return((g.This() == g.Arg("o").Cast(DBBool)).Cast(typeof(bool))); } g.CatchAll(); { g.Return(false); } g.End(); } // Override the Object.GetHashCode() method: g = DBBool.Public.Override.Method(typeof(int), "GetHashCode"); { g.Return(value); } // Override the ToString method to convert DBBool to a string: g = DBBool.Public.Override.Method(typeof(string), "ToString"); { g.Switch(value); { g.Case(-1); g.Return("DBBool.False"); g.Case(0); g.Return("DBBool.Null"); g.Case(1); g.Return("DBBool.True"); g.DefaultCase(); g.Throw(Exp.New(typeof(InvalidOperationException))); } g.End(); } } TypeGen Test = ag.Class("Test"); { CodeGen g = Test.Static.Method(typeof(void), "Main"); { Operand a = g.Local(DBBool), b = g.Local(DBBool); g.Assign(a, Static.Field(DBBool, "dbTrue")); g.Assign(b, Static.Field(DBBool, "dbNull")); g.WriteLine("!{0} = {1}", a, !a); g.WriteLine("!{0} = {1}", b, !b); g.WriteLine("{0} & {1} = {2}", a, b, a & b); g.WriteLine("{0} | {1} = {2}", a, b, a | b); // Invoke the true operator to determine the Boolean // value of the DBBool variable: g.If(b); { g.WriteLine("b is definitely true"); } g.Else(); { g.WriteLine("b is not definitely true"); } g.End(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { // Gregorian Calendars use Era Info internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) internal string? eraName; // The era name internal string? abbrevEraName; // Abbreviated Era Name internal string? englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, string eraName, string abbrevEraName, string englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear => m_maxYear; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; internal int m_maxYear; internal int m_minYear; internal Calendar m_Cal; internal EraInfo[] m_EraInfo; internal int[]? m_eras = null; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear; } // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue; // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1) private int GetYearOffset(int year, int era, bool throwOnError) { if (year < 0) { if (throwOnError) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } return -1; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year >= m_EraInfo[i].minEraYear) { if (year <= m_EraInfo[i].maxEraYear) { return m_EraInfo[i].yearOffset; } else if (!LocalAppContextSwitches.EnforceJapaneseEraYearRanges) { // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year // can exist in one of these eras. otherwise, we'll throw. // Note, we always return the offset associated with the requested era. // // Here is some example: // if we are getting the era number 4 (Heisei) and getting the year number 32. if the era 4 has year range from 1 to 31 // then year 32 exceeded the range of era 4 and we'll try to find out if the years difference (32 - 31 = 1) would lay in // the subsequent eras (e.g era 5 and up) int remainingYears = year - m_EraInfo[i].maxEraYear; for (int j = i - 1; j >= 0; j--) { if (remainingYears <= m_EraInfo[j].maxEraYear) { return m_EraInfo[i].yearOffset; } remainingYears -= m_EraInfo[j].maxEraYear; } } } if (throwOnError) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format( SR.ArgumentOutOfRange_Range, m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } break; // no need to iterate more on eras. } } if (throwOnError) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } return -1; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { return GetYearOffset(year, era, throwOnError: true) + year; } internal bool IsValidYear(int year, int era) { return GetYearOffset(year, era, throwOnError: false) >= 0; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1; } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return n + 1; } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return m; // Return 1-based day-of-month return n - days[m - 1] + 1; } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return absoluteDate; } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return GetAbsoluteDate(year, month, day) * TicksPerDay; } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { // TimeSpan.TimeToTicks is a family access function which does no error checking, so // we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), SR.Format( SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", SR.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), SR.Format( SR.ArgumentOutOfRange_Range, -120000, 120000)); } CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y += i / 12; } else { m = 12 + (i + 1) % 12; y += (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return new DateTime(ticks); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, DatePartDay); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return (DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return GetDatePart(time.Ticks, DatePartDayOfYear); } // Returns the number of days in the month given by the year and // month arguments. // public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return days[month] - days[month - 1]; } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365; } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return m_EraInfo[i].era; } } throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return (int[])m_eras.Clone(); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return GetDatePart(time.Ticks, DatePartMonth); } // Returns the number of months in the specified year and era. // Always return 12. public int GetMonthsInYear(int year, int era) { ValidateYearInEra(year, era); return 12; } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return year - m_EraInfo[i].yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return year - m_EraInfo[i].yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( nameof(day), SR.Format( SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } if (!IsLeapYear(year, era)) { return false; } if (month == 2 && day == 29) { return true; } return false; } // Giving the calendar year and era, ValidateYearInEra will validate the existence of the input year in the input era. // This method will throw if the year or the era is invalid. public void ValidateYearInEra(int year, int era) => GetYearOffset(year, era, throwOnError: true); // Returns the leap month in a calendar year of the specified era. // This method always returns 0 as all calendars using this method don't have leap months. public int GetLeapMonth(int year, int era) { ValidateYearInEra(year, era); return 0; } // Checks whether a given month in the specified era is a leap month. // This method always returns false as all calendars using this method don't have leap months. public bool IsLeapMonth(int year, int month, int era) { ValidateYearInEra(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( nameof(month), SR.Format( SR.ArgumentOutOfRange_Range, 1, 12)); } return false; } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return new DateTime(ticks); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } if (year < 100) { int y = year % 100; return (twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y; } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return year; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; namespace Amazon.CloudFormation { /// <summary> /// Interface for accessing AmazonCloudFormation. /// /// AWS CloudFormation <para>AWS CloudFormation enables you to create and manage AWS infrastructure deployments predictably and repeatedly. AWS /// CloudFormation helps you leverage AWS products such as Amazon EC2, EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable, highly /// scalable, cost effective applications without worrying about creating and configuring the underlying the AWS infrastructure.</para> /// <para>With AWS CloudFormation, you declare all of your resources and dependencies in a template file. The template defines a collection of /// resources as a single unit called a stack. AWS CloudFormation creates and deletes all member resources of the stack together and manages all /// dependencies between the resources for you.</para> <para>For more information about this product, go to the CloudFormation Product /// Page.</para> <para>Amazon CloudFormation makes use of other AWS products. If you need additional technical information about a specific AWS /// product, you can find the product's technical documentation at http://aws.amazon.com/documentation/.</para> /// </summary> public interface AmazonCloudFormation : IDisposable { #region ValidateTemplate /// <summary> /// <para>Validates a specified template.</para> /// </summary> /// /// <param name="validateTemplateRequest">Container for the necessary parameters to execute the ValidateTemplate service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the ValidateTemplate service method, as returned by AmazonCloudFormation.</returns> /// ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest validateTemplateRequest); /// <summary> /// Initiates the asynchronous execution of the ValidateTemplate operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ValidateTemplate"/> /// </summary> /// /// <param name="validateTemplateRequest">Container for the necessary parameters to execute the ValidateTemplate operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndValidateTemplate /// operation.</returns> IAsyncResult BeginValidateTemplate(ValidateTemplateRequest validateTemplateRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ValidateTemplate operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ValidateTemplate"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginValidateTemplate.</param> /// /// <returns>Returns a ValidateTemplateResult from AmazonCloudFormation.</returns> ValidateTemplateResponse EndValidateTemplate(IAsyncResult asyncResult); /// <summary> /// <para>Validates a specified template.</para> /// </summary> /// /// <returns>The response from the ValidateTemplate service method, as returned by AmazonCloudFormation.</returns> /// ValidateTemplateResponse ValidateTemplate(); #endregion #region DescribeStacks /// <summary> /// <para>Returns the description for the specified stack; if no stack name was specified, then it returns the description for all the stacks /// created.</para> /// </summary> /// /// <param name="describeStacksRequest">Container for the necessary parameters to execute the DescribeStacks service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the DescribeStacks service method, as returned by AmazonCloudFormation.</returns> /// DescribeStacksResponse DescribeStacks(DescribeStacksRequest describeStacksRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeStacks operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStacks"/> /// </summary> /// /// <param name="describeStacksRequest">Container for the necessary parameters to execute the DescribeStacks operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeStacks /// operation.</returns> IAsyncResult BeginDescribeStacks(DescribeStacksRequest describeStacksRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeStacks operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStacks"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeStacks.</param> /// /// <returns>Returns a DescribeStacksResult from AmazonCloudFormation.</returns> DescribeStacksResponse EndDescribeStacks(IAsyncResult asyncResult); /// <summary> /// <para>Returns the description for the specified stack; if no stack name was specified, then it returns the description for all the stacks /// created.</para> /// </summary> /// /// <returns>The response from the DescribeStacks service method, as returned by AmazonCloudFormation.</returns> /// DescribeStacksResponse DescribeStacks(); #endregion #region GetTemplate /// <summary> /// <para>Returns the template body for a specified stack name. You can get the template for running or deleted stacks.</para> <para>For deleted /// stacks, GetTemplate returns the template for up to 90 days after the stack has been deleted.</para> <para><b>NOTE:</b> If the template does /// not exist, a ValidationError is returned. </para> /// </summary> /// /// <param name="getTemplateRequest">Container for the necessary parameters to execute the GetTemplate service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the GetTemplate service method, as returned by AmazonCloudFormation.</returns> /// GetTemplateResponse GetTemplate(GetTemplateRequest getTemplateRequest); /// <summary> /// Initiates the asynchronous execution of the GetTemplate operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.GetTemplate"/> /// </summary> /// /// <param name="getTemplateRequest">Container for the necessary parameters to execute the GetTemplate operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetTemplate /// operation.</returns> IAsyncResult BeginGetTemplate(GetTemplateRequest getTemplateRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetTemplate operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.GetTemplate"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetTemplate.</param> /// /// <returns>Returns a GetTemplateResult from AmazonCloudFormation.</returns> GetTemplateResponse EndGetTemplate(IAsyncResult asyncResult); #endregion #region ListStacks /// <summary> /// <para>Returns the summary information for stacks whose status matches the specified StackStatusFilter. Summary information for stacks that /// have been deleted is kept for 90 days after the stack is deleted. If no StackStatusFilter is specified, summary information for all stacks /// is returned (including existing stacks and stacks that have been deleted).</para> /// </summary> /// /// <param name="listStacksRequest">Container for the necessary parameters to execute the ListStacks service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the ListStacks service method, as returned by AmazonCloudFormation.</returns> /// ListStacksResponse ListStacks(ListStacksRequest listStacksRequest); /// <summary> /// Initiates the asynchronous execution of the ListStacks operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ListStacks"/> /// </summary> /// /// <param name="listStacksRequest">Container for the necessary parameters to execute the ListStacks operation on AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListStacks /// operation.</returns> IAsyncResult BeginListStacks(ListStacksRequest listStacksRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListStacks operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ListStacks"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListStacks.</param> /// /// <returns>Returns a ListStacksResult from AmazonCloudFormation.</returns> ListStacksResponse EndListStacks(IAsyncResult asyncResult); /// <summary> /// <para>Returns the summary information for stacks whose status matches the specified StackStatusFilter. Summary information for stacks that /// have been deleted is kept for 90 days after the stack is deleted. If no StackStatusFilter is specified, summary information for all stacks /// is returned (including existing stacks and stacks that have been deleted).</para> /// </summary> /// /// <returns>The response from the ListStacks service method, as returned by AmazonCloudFormation.</returns> /// ListStacksResponse ListStacks(); #endregion #region CreateStack /// <summary> /// <para>Creates a stack as specified in the template. After the call completes successfully, the stack creation starts. You can check the /// status of the stack via the DescribeStacks API.</para> <para><b>NOTE:</b> Currently, the limit for stacks is 20 stacks per account per /// region. </para> /// </summary> /// /// <param name="createStackRequest">Container for the necessary parameters to execute the CreateStack service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the CreateStack service method, as returned by AmazonCloudFormation.</returns> /// /// <exception cref="AlreadyExistsException"/> /// <exception cref="LimitExceededException"/> /// <exception cref="InsufficientCapabilitiesException"/> CreateStackResponse CreateStack(CreateStackRequest createStackRequest); /// <summary> /// Initiates the asynchronous execution of the CreateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.CreateStack"/> /// </summary> /// /// <param name="createStackRequest">Container for the necessary parameters to execute the CreateStack operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateStack /// operation.</returns> IAsyncResult BeginCreateStack(CreateStackRequest createStackRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.CreateStack"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateStack.</param> /// /// <returns>Returns a CreateStackResult from AmazonCloudFormation.</returns> CreateStackResponse EndCreateStack(IAsyncResult asyncResult); #endregion #region EstimateTemplateCost /// <summary> /// <para>Returns the estimated monthly cost of a template. The return value is an AWS Simple Monthly Calculator URL with a query string that /// describes the resources required to run the template.</para> /// </summary> /// /// <param name="estimateTemplateCostRequest">Container for the necessary parameters to execute the EstimateTemplateCost service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the EstimateTemplateCost service method, as returned by AmazonCloudFormation.</returns> /// EstimateTemplateCostResponse EstimateTemplateCost(EstimateTemplateCostRequest estimateTemplateCostRequest); /// <summary> /// Initiates the asynchronous execution of the EstimateTemplateCost operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.EstimateTemplateCost"/> /// </summary> /// /// <param name="estimateTemplateCostRequest">Container for the necessary parameters to execute the EstimateTemplateCost operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndEstimateTemplateCost operation.</returns> IAsyncResult BeginEstimateTemplateCost(EstimateTemplateCostRequest estimateTemplateCostRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the EstimateTemplateCost operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.EstimateTemplateCost"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEstimateTemplateCost.</param> /// /// <returns>Returns a EstimateTemplateCostResult from AmazonCloudFormation.</returns> EstimateTemplateCostResponse EndEstimateTemplateCost(IAsyncResult asyncResult); #endregion #region DescribeStackEvents /// <summary> /// <para>Returns all the stack related events for the AWS account. If <c>StackName</c> is specified, returns events related to all the stacks /// with the given name. If <c>StackName</c> is not specified, returns all the events for the account. For more information about a stack's /// event history, go to the AWS CloudFormation User Guide.</para> <para><b>NOTE:</b>Events are returned, even if the stack never existed or has /// been successfully deleted.</para> /// </summary> /// /// <param name="describeStackEventsRequest">Container for the necessary parameters to execute the DescribeStackEvents service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the DescribeStackEvents service method, as returned by AmazonCloudFormation.</returns> /// DescribeStackEventsResponse DescribeStackEvents(DescribeStackEventsRequest describeStackEventsRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeStackEvents operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackEvents"/> /// </summary> /// /// <param name="describeStackEventsRequest">Container for the necessary parameters to execute the DescribeStackEvents operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeStackEvents operation.</returns> IAsyncResult BeginDescribeStackEvents(DescribeStackEventsRequest describeStackEventsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeStackEvents operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackEvents"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeStackEvents.</param> /// /// <returns>Returns a DescribeStackEventsResult from AmazonCloudFormation.</returns> DescribeStackEventsResponse EndDescribeStackEvents(IAsyncResult asyncResult); /// <summary> /// <para>Returns all the stack related events for the AWS account. If <c>StackName</c> is specified, returns events related to all the stacks /// with the given name. If <c>StackName</c> is not specified, returns all the events for the account. For more information about a stack's /// event history, go to the AWS CloudFormation User Guide.</para> <para><b>NOTE:</b>Events are returned, even if the stack never existed or has /// been successfully deleted.</para> /// </summary> /// /// <returns>The response from the DescribeStackEvents service method, as returned by AmazonCloudFormation.</returns> /// DescribeStackEventsResponse DescribeStackEvents(); #endregion #region DescribeStackResource /// <summary> /// <para>Returns a description of the specified resource in the specified stack.</para> <para>For deleted stacks, DescribeStackResource returns /// resource information for up to 90 days after the stack has been deleted.</para> /// </summary> /// /// <param name="describeStackResourceRequest">Container for the necessary parameters to execute the DescribeStackResource service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the DescribeStackResource service method, as returned by AmazonCloudFormation.</returns> /// DescribeStackResourceResponse DescribeStackResource(DescribeStackResourceRequest describeStackResourceRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeStackResource operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackResource"/> /// </summary> /// /// <param name="describeStackResourceRequest">Container for the necessary parameters to execute the DescribeStackResource operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeStackResource operation.</returns> IAsyncResult BeginDescribeStackResource(DescribeStackResourceRequest describeStackResourceRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeStackResource operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackResource"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeStackResource.</param> /// /// <returns>Returns a DescribeStackResourceResult from AmazonCloudFormation.</returns> DescribeStackResourceResponse EndDescribeStackResource(IAsyncResult asyncResult); #endregion #region CancelUpdateStack /// <summary> /// <para>Cancels an update on the specified stack. If the call completes successfully, the stack will roll back the update and revert to the /// previous stack configuration.</para> <para><b>NOTE:</b>Only stacks that are in the UPDATE_IN_PROGRESS state can be canceled.</para> /// </summary> /// /// <param name="cancelUpdateStackRequest">Container for the necessary parameters to execute the CancelUpdateStack service method on /// AmazonCloudFormation.</param> /// CancelUpdateStackResponse CancelUpdateStack(CancelUpdateStackRequest cancelUpdateStackRequest); /// <summary> /// Initiates the asynchronous execution of the CancelUpdateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.CancelUpdateStack"/> /// </summary> /// /// <param name="cancelUpdateStackRequest">Container for the necessary parameters to execute the CancelUpdateStack operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginCancelUpdateStack(CancelUpdateStackRequest cancelUpdateStackRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CancelUpdateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.CancelUpdateStack"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCancelUpdateStack.</param> CancelUpdateStackResponse EndCancelUpdateStack(IAsyncResult asyncResult); #endregion #region DeleteStack /// <summary> /// <para>Deletes a specified stack. Once the call completes successfully, stack deletion starts. Deleted stacks do not show up in the /// DescribeStacks API if the deletion has been completed successfully.</para> /// </summary> /// /// <param name="deleteStackRequest">Container for the necessary parameters to execute the DeleteStack service method on /// AmazonCloudFormation.</param> /// DeleteStackResponse DeleteStack(DeleteStackRequest deleteStackRequest); /// <summary> /// Initiates the asynchronous execution of the DeleteStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DeleteStack"/> /// </summary> /// /// <param name="deleteStackRequest">Container for the necessary parameters to execute the DeleteStack operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginDeleteStack(DeleteStackRequest deleteStackRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DeleteStack"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteStack.</param> DeleteStackResponse EndDeleteStack(IAsyncResult asyncResult); #endregion #region ListStackResources /// <summary> /// <para>Returns descriptions of all resources of the specified stack.</para> <para>For deleted stacks, ListStackResources returns resource /// information for up to 90 days after the stack has been deleted.</para> /// </summary> /// /// <param name="listStackResourcesRequest">Container for the necessary parameters to execute the ListStackResources service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the ListStackResources service method, as returned by AmazonCloudFormation.</returns> /// ListStackResourcesResponse ListStackResources(ListStackResourcesRequest listStackResourcesRequest); /// <summary> /// Initiates the asynchronous execution of the ListStackResources operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ListStackResources"/> /// </summary> /// /// <param name="listStackResourcesRequest">Container for the necessary parameters to execute the ListStackResources operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndListStackResources operation.</returns> IAsyncResult BeginListStackResources(ListStackResourcesRequest listStackResourcesRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListStackResources operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.ListStackResources"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListStackResources.</param> /// /// <returns>Returns a ListStackResourcesResult from AmazonCloudFormation.</returns> ListStackResourcesResponse EndListStackResources(IAsyncResult asyncResult); #endregion #region DescribeStackResources /// <summary> /// <para>Returns AWS resource descriptions for running and deleted stacks. If <c>StackName</c> is specified, all the associated resources that /// are part of the stack are returned. If <c>PhysicalResourceId</c> is specified, the associated resources of the stack that the resource /// belongs to are returned.</para> <para><b>NOTE:</b>Only the first 100 resources will be returned. If your stack has more resources than this, /// you should use ListStackResources instead.</para> <para>For deleted stacks, <c>DescribeStackResources</c> returns resource information for /// up to 90 days after the stack has been deleted.</para> <para>You must specify either <c>StackName</c> or <c>PhysicalResourceId</c> , but not /// both. In addition, you can specify <c>LogicalResourceId</c> to filter the returned result. For more information about resources, the /// <c>LogicalResourceId</c> and <c>PhysicalResourceId</c> , go to the AWS CloudFormation User Guide.</para> <para><b>NOTE:</b>A ValidationError /// is returned if you specify both StackName and PhysicalResourceId in the same request.</para> /// </summary> /// /// <param name="describeStackResourcesRequest">Container for the necessary parameters to execute the DescribeStackResources service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the DescribeStackResources service method, as returned by AmazonCloudFormation.</returns> /// DescribeStackResourcesResponse DescribeStackResources(DescribeStackResourcesRequest describeStackResourcesRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeStackResources operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackResources"/> /// </summary> /// /// <param name="describeStackResourcesRequest">Container for the necessary parameters to execute the DescribeStackResources operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeStackResources operation.</returns> IAsyncResult BeginDescribeStackResources(DescribeStackResourcesRequest describeStackResourcesRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeStackResources operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.DescribeStackResources"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeStackResources.</param> /// /// <returns>Returns a DescribeStackResourcesResult from AmazonCloudFormation.</returns> DescribeStackResourcesResponse EndDescribeStackResources(IAsyncResult asyncResult); /// <summary> /// <para>Returns AWS resource descriptions for running and deleted stacks. If <c>StackName</c> is specified, all the associated resources that /// are part of the stack are returned. If <c>PhysicalResourceId</c> is specified, the associated resources of the stack that the resource /// belongs to are returned.</para> <para><b>NOTE:</b>Only the first 100 resources will be returned. If your stack has more resources than this, /// you should use ListStackResources instead.</para> <para>For deleted stacks, <c>DescribeStackResources</c> returns resource information for /// up to 90 days after the stack has been deleted.</para> <para>You must specify either <c>StackName</c> or <c>PhysicalResourceId</c> , but not /// both. In addition, you can specify <c>LogicalResourceId</c> to filter the returned result. For more information about resources, the /// <c>LogicalResourceId</c> and <c>PhysicalResourceId</c> , go to the AWS CloudFormation User Guide.</para> <para><b>NOTE:</b>A ValidationError /// is returned if you specify both StackName and PhysicalResourceId in the same request.</para> /// </summary> /// /// <returns>The response from the DescribeStackResources service method, as returned by AmazonCloudFormation.</returns> /// DescribeStackResourcesResponse DescribeStackResources(); #endregion #region UpdateStack /// <summary> /// <para>Updates a stack as specified in the template. After the call completes successfully, the stack update starts. You can check the status /// of the stack via the DescribeStacks action.</para> <para>To get a copy of the template for an existing stack, you can use the GetTemplate /// action.</para> <para>Tags that were associated with this stack during creation time will still be associated with the stack after an /// <c>UpdateStack</c> operation.</para> <para>For more information about creating an update template, updating a stack, and monitoring the /// progress of the update, see Updating a Stack.</para> /// </summary> /// /// <param name="updateStackRequest">Container for the necessary parameters to execute the UpdateStack service method on /// AmazonCloudFormation.</param> /// /// <returns>The response from the UpdateStack service method, as returned by AmazonCloudFormation.</returns> /// /// <exception cref="InsufficientCapabilitiesException"/> UpdateStackResponse UpdateStack(UpdateStackRequest updateStackRequest); /// <summary> /// Initiates the asynchronous execution of the UpdateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.UpdateStack"/> /// </summary> /// /// <param name="updateStackRequest">Container for the necessary parameters to execute the UpdateStack operation on /// AmazonCloudFormation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateStack /// operation.</returns> IAsyncResult BeginUpdateStack(UpdateStackRequest updateStackRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateStack operation. /// <seealso cref="Amazon.CloudFormation.AmazonCloudFormation.UpdateStack"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateStack.</param> /// /// <returns>Returns a UpdateStackResult from AmazonCloudFormation.</returns> UpdateStackResponse EndUpdateStack(IAsyncResult asyncResult); #endregion } }
/* * CID0022.cs - uk culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "uk.txt". namespace I18N.Other { using System; using System.Globalization; using I18N.Common; public class CID0022 : RootCulture { public CID0022() : base(0x0022) {} public CID0022(int culture) : base(culture) {} public override String Name { get { return "uk"; } } public override String ThreeLetterISOLanguageName { get { return "ukr"; } } public override String ThreeLetterWindowsLanguageName { get { return "UKR"; } } public override String TwoLetterISOLanguageName { get { return "uk"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"\u041D\u0434", "\u041F\u043D", "\u0412\u0442", "\u0421\u0440", "\u0427\u0442", "\u041F\u0442", "\u0421\u0431"}; dfi.DayNames = new String[] {"\u041D\u0435\u0434\u0456\u043B\u044F", "\u041F\u043E\u043D\u0435\u0434\u0456\u043B\u043E\u043A", "\u0412\u0456\u0432\u0442\u043E\u0440\u043E\u043A", "\u0421\u0435\u0440\u0435\u0434\u0430", "\u0427\u0435\u0442\u0432\u0435\u0440", "\u041F\u044F\u0442\u043D\u0438\u0446\u044F", "\u0421\u0443\u0431\u043E\u0442\u0430"}; dfi.AbbreviatedMonthNames = new String[] {"\u0421\u0456\u0447", "\u041B\u044E\u0442", "\u0411\u0435\u0440", "\u041A\u0432\u0456\u0442", "\u0422\u0440\u0430\u0432", "\u0427\u0435\u0440\u0432", "\u041B\u0438\u043F", "\u0421\u0435\u0440\u043F", "\u0412\u0435\u0440", "\u0416\u043E\u0432\u0442", "\u041B\u0438\u0441\u0442", "\u0413\u0440\u0443\u0434", ""}; dfi.MonthNames = new String[] {"\u0421\u0456\u0447\u043D\u044F", "\u041B\u044E\u0442\u043E\u0433\u043E", "\u0411\u0435\u0440\u0435\u0436\u043D\u044F", "\u041A\u0432\u0456\u0442\u043D\u044F", "\u0422\u0440\u0430\u0432\u043D\u044F", "\u0427\u0435\u0440\u0432\u043D\u044F", "\u041B\u0438\u043F\u043D\u044F", "\u0421\u0435\u0440\u043F\u043D\u044F", "\u0412\u0435\u0440\u0435\u0441\u043D\u044F", "\u0416\u043E\u0432\u0442\u043D\u044F", "\u041B\u0438\u0441\u0442\u043E\u043F\u0430\u0434\u0430", "\u0413\u0440\u0443\u0434\u043D\u044F", ""}; dfi.DateSeparator = "/"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "dddd, d, MMMM yyyy"; dfi.LongTimePattern = "HH:mm:ss z"; dfi.ShortDatePattern = "d/M/yy"; dfi.ShortTimePattern = "HH:mm"; dfi.FullDateTimePattern = "dddd, d, MMMM yyyy HH:mm:ss z"; dfi.I18NSetDateTimePatterns(new String[] { "d:d/M/yy", "D:dddd, d, MMMM yyyy", "f:dddd, d, MMMM yyyy HH:mm:ss z", "f:dddd, d, MMMM yyyy HH:mm:ss z", "f:dddd, d, MMMM yyyy HH:mm:ss", "f:dddd, d, MMMM yyyy HH:mm", "F:dddd, d, MMMM yyyy HH:mm:ss", "g:d/M/yy HH:mm:ss z", "g:d/M/yy HH:mm:ss z", "g:d/M/yy HH:mm:ss", "g:d/M/yy HH:mm", "G:d/M/yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:HH:mm:ss z", "t:HH:mm:ss z", "t:HH:mm:ss", "t:HH:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "."; nfi.NumberGroupSeparator = "."; nfi.PercentGroupSeparator = "."; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "uk": return "\u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "UA": return "\u0423\u043A\u0440\u0430\u0457\u043D\u0430"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1251; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 10017; } } public override int OEMCodePage { get { return 866; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0022 public class CNuk : CID0022 { public CNuk() : base() {} }; // class CNuk }; // namespace I18N.Other
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Xml.Serialization; using System.Xml.Schema; using System.Security; using System.Linq; using XmlSchemaType = System.Object; #if NET_NATIVE public delegate IXmlSerializable CreateXmlSerializableDelegate(); public sealed class XmlDataContract : DataContract #else internal delegate IXmlSerializable CreateXmlSerializableDelegate(); internal sealed class XmlDataContract : DataContract #endif { [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private XmlDataContractCriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] public XmlDataContract() : base(new XmlDataContractCriticalHelper()) { _helper = base.Helper as XmlDataContractCriticalHelper; } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type)) { _helper = base.Helper as XmlDataContractCriticalHelper; } public override DataContractDictionary KnownDataContracts { /// <SecurityNote> /// Critical - fetches the critical KnownDataContracts property /// Safe - KnownDataContracts only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.KnownDataContracts; } /// <SecurityNote> /// Critical - sets the critical KnownDataContracts property /// </SecurityNote> [SecurityCritical] set { _helper.KnownDataContracts = value; } } internal bool IsAnonymous { /// <SecurityNote> /// Critical - fetches the critical IsAnonymous property /// Safe - IsAnonymous only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.IsAnonymous; } } public override bool HasRoot { /// <SecurityNote> /// Critical - fetches the critical HasRoot property /// Safe - HasRoot only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.HasRoot; } /// <SecurityNote> /// Critical - sets the critical HasRoot property /// </SecurityNote> [SecurityCritical] set { _helper.HasRoot = value; } } public override XmlDictionaryString TopLevelElementName { /// <SecurityNote> /// Critical - fetches the critical TopLevelElementName property /// Safe - TopLevelElementName only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.TopLevelElementName; } /// <SecurityNote> /// Critical - sets the critical TopLevelElementName property /// </SecurityNote> [SecurityCritical] set { _helper.TopLevelElementName = value; } } public override XmlDictionaryString TopLevelElementNamespace { /// <SecurityNote> /// Critical - fetches the critical TopLevelElementNamespace property /// Safe - TopLevelElementNamespace only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.TopLevelElementNamespace; } /// <SecurityNote> /// Critical - sets the critical TopLevelElementNamespace property /// </SecurityNote> [SecurityCritical] set { _helper.TopLevelElementNamespace = value; } } #if !NET_NATIVE internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { /// <SecurityNote> /// Critical - fetches the critical CreateXmlSerializableDelegate property /// Safe - CreateXmlSerializableDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.CreateXmlSerializableDelegate == null) { lock (this) { if (_helper.CreateXmlSerializableDelegate == null) { CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate(); Interlocked.MemoryBarrier(); _helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable; } } } return _helper.CreateXmlSerializableDelegate; } } #else public CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get; set; } #endif internal override bool CanContainReferences { get { return false; } } public override bool IsBuiltInDataContract { get { return UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray; } } [SecurityCritical] /// <SecurityNote> /// Critical - holds all state used for for (de)serializing XML types. /// since the data is cached statically, we lock down access to it. /// </SecurityNote> private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; private XmlDictionaryString _topLevelElementName; private XmlDictionaryString _topLevelElementNamespace; private bool _hasRoot; private CreateXmlSerializableDelegate _createXmlSerializable; internal XmlDataContractCriticalHelper() { } internal XmlDataContractCriticalHelper(Type type) : base(type) { if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type)))); XmlSchemaType xsdType; bool hasRoot; XmlQualifiedName stableName; SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot); this.StableName = stableName; this.HasRoot = hasRoot; XmlDictionary dictionary = new XmlDictionary(); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetTypeInfo().GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); if (xmlRootAttributes == null || xmlRootAttributes.Length == 0) { if (hasRoot) { _topLevelElementName = Name; _topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace; } } else { if (hasRoot) { XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0]; string elementName = xmlRootAttribute.ElementName; _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); string elementNs = xmlRootAttribute.Namespace; _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType)))); } } } internal override DataContractDictionary KnownDataContracts { [SecurityCritical] get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } [SecurityCritical] set { _knownDataContracts = value; } } internal bool IsAnonymous { get { return false; } } internal override bool HasRoot { [SecurityCritical] get { return _hasRoot; } [SecurityCritical] set { _hasRoot = value; } } internal override XmlDictionaryString TopLevelElementName { [SecurityCritical] get { return _topLevelElementName; } [SecurityCritical] set { _topLevelElementName = value; } } internal override XmlDictionaryString TopLevelElementNamespace { [SecurityCritical] get { return _topLevelElementNamespace; } [SecurityCritical] set { _topLevelElementNamespace = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get { return _createXmlSerializable; } set { _createXmlSerializable = value; } } } private ConstructorInfo GetConstructor() { Type type = UnderlyingType; if (type.GetTypeInfo().IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } #if !NET_NATIVE /// <SecurityNote> /// Critical - calls CodeGenerator.BeginMethod which is SecurityCritical /// Safe - self-contained: returns the delegate to the generated IL but otherwise all IL generation is self-contained here /// </SecurityNote> [SecuritySafeCritical] internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() { Type type = this.UnderlyingType; CodeGenerator ilg = new CodeGenerator(); bool memberAccessFlag = RequiresMemberAccessForCreate(null) && !(type.FullName == "System.Xml.Linq.XElement"); try { ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { RequiresMemberAccessForCreate(securityException); } else { throw; } } if (type.GetTypeInfo().IsValueType) { System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value"); ilg.Ldloca(local); ilg.InitObj(type); ilg.Ldloc(local); } else { // Special case XElement // codegen the same as 'internal XElement : this("default") { }' ConstructorInfo ctor = GetConstructor(); if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement") { Type xName = type.GetTypeInfo().Assembly.GetType("System.Xml.Linq.XName"); if (xName != null) { MethodInfo XName_op_Implicit = xName.GetMethod( "op_Implicit", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { typeof(String) } ); ConstructorInfo XElement_ctor = type.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { xName } ); if (XName_op_Implicit != null && XElement_ctor != null) { ilg.Ldstr("default"); ilg.Call(XName_op_Implicit); ctor = XElement_ctor; } } } ilg.New(ctor); } ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable); ilg.Ret(); return (CreateXmlSerializableDelegate)ilg.EndMethod(); } /// <SecurityNote> /// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private bool RequiresMemberAccessForCreate(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(GetConstructor())) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } return false; } #endif public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (context == null) XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); else context.WriteIXmlSerializable(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object o; if (context == null) { o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/); } else { o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/); context.AddNewObject(o); } xmlReader.ReadEndElement(); return o; } } }
#region License /* * TcpListenerWebSocketContext.cs * * The MIT License * * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; namespace WebSocketSharp.Net.WebSockets { /// <summary> /// Provides the properties used to access the information in a WebSocket connection request /// received by the <see cref="TcpListener"/>. /// </summary> /// <remarks> /// </remarks> public class TcpListenerWebSocketContext : WebSocketContext { #region Private Fields private TcpClient _client; private CookieCollection _cookies; private NameValueCollection _queryString; private HandshakeRequest _request; private bool _secure; private WebSocketStream _stream; private Uri _uri; private IPrincipal _user; private WebSocket _websocket; #endregion #region Internal Constructors internal TcpListenerWebSocketContext ( TcpClient client, string protocol, bool secure, X509Certificate cert, Logger logger) { _client = client; _secure = secure; _stream = WebSocketStream.CreateServerStream (client, secure, cert); _request = _stream.ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 90000); _uri = HttpUtility.CreateRequestUrl ( _request.RequestUri, _request.Headers ["Host"], _request.IsWebSocketRequest, secure); _websocket = new WebSocket (this, protocol, logger); } #endregion #region Internal Properties internal WebSocketStream Stream { get { return _stream; } } #endregion #region Public Properties /// <summary> /// Gets the HTTP cookies included in the request. /// </summary> /// <value> /// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains the cookies. /// </value> public override CookieCollection CookieCollection { get { return _cookies ?? (_cookies = _request.Cookies); } } /// <summary> /// Gets the HTTP headers included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public override NameValueCollection Headers { get { return _request.Headers; } } /// <summary> /// Gets the value of the Host header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Host header. /// </value> public override string Host { get { return _request.Headers ["Host"]; } } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public override bool IsAuthenticated { get { return _user != null && _user.Identity.IsAuthenticated; } } /// <summary> /// Gets a value indicating whether the client connected from the local computer. /// </summary> /// <value> /// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>. /// </value> public override bool IsLocal { get { return UserEndPoint.Address.IsLocal (); } } /// <summary> /// Gets a value indicating whether the WebSocket connection is secured. /// </summary> /// <value> /// <c>true</c> if the connection is secured; otherwise, <c>false</c>. /// </value> public override bool IsSecureConnection { get { return _secure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket connection request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>. /// </value> public override bool IsWebSocketRequest { get { return _request.IsWebSocketRequest; } } /// <summary> /// Gets the value of the Origin header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Origin header. /// </value> public override string Origin { get { return _request.Headers ["Origin"]; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the query string parameters. /// </value> public override NameValueCollection QueryString { get { return _queryString ?? (_queryString = HttpUtility.ParseQueryStringInternally ( _uri != null ? _uri.Query : null, Encoding.UTF8)); } } /// <summary> /// Gets the URI requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the requested URI. /// </value> public override Uri RequestUri { get { return _uri; } } /// <summary> /// Gets the value of the Sec-WebSocket-Key header included in the request. /// </summary> /// <remarks> /// This property provides a part of the information used by the server to prove that it /// received a valid WebSocket connection request. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key header. /// </value> public override string SecWebSocketKey { get { return _request.Headers ["Sec-WebSocket-Key"]; } } /// <summary> /// Gets the values of the Sec-WebSocket-Protocol header included in the request. /// </summary> /// <remarks> /// This property represents the subprotocols requested by the client. /// </remarks> /// <value> /// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> instance that provides /// an enumerator which supports the iteration over the values of the Sec-WebSocket-Protocol /// header. /// </value> public override IEnumerable<string> SecWebSocketProtocols { get { var protocols = _request.Headers ["Sec-WebSocket-Protocol"]; if (protocols != null) foreach (var protocol in protocols.Split (',')) yield return protocol.Trim (); } } /// <summary> /// Gets the value of the Sec-WebSocket-Version header included in the request. /// </summary> /// <remarks> /// This property represents the WebSocket protocol version. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Version header. /// </value> public override string SecWebSocketVersion { get { return _request.Headers ["Sec-WebSocket-Version"]; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint. /// </value> public override System.Net.IPEndPoint ServerEndPoint { get { return (System.Net.IPEndPoint) _client.Client.LocalEndPoint; } } /// <summary> /// Gets the client information (identity, authentication, and security roles). /// </summary> /// <value> /// A <see cref="IPrincipal"/> that represents the client information. /// </value> public override IPrincipal User { get { return _user; } } /// <summary> /// Gets the client endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint. /// </value> public override System.Net.IPEndPoint UserEndPoint { get { return (System.Net.IPEndPoint) _client.Client.RemoteEndPoint; } } /// <summary> /// Gets the <see cref="WebSocketSharp.WebSocket"/> instance used for two-way communication /// between client and server. /// </summary> /// <value> /// A <see cref="WebSocketSharp.WebSocket"/>. /// </value> public override WebSocket WebSocket { get { return _websocket; } } #endregion #region Internal Methods internal void Close () { _stream.Close (); _client.Close (); } internal void Close (HttpStatusCode code) { _websocket.Close (HandshakeResponse.CreateCloseResponse (code)); } internal void SendAuthChallenge (string challenge) { var res = new HandshakeResponse (HttpStatusCode.Unauthorized); res.Headers ["WWW-Authenticate"] = challenge; _stream.WriteHandshake (res); _request = _stream.ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 15000); } internal void SetUser ( AuthenticationSchemes scheme, string realm, Func<IIdentity, NetworkCredential> credentialsFinder) { var authRes = _request.AuthResponse; if (authRes == null) return; var id = authRes.ToIdentity (); if (id == null) return; NetworkCredential cred = null; try { cred = credentialsFinder (id); } catch { } if (cred == null) return; var valid = scheme == AuthenticationSchemes.Basic ? ((HttpBasicIdentity) id).Password == cred.Password : scheme == AuthenticationSchemes.Digest ? ((HttpDigestIdentity) id).IsValid ( cred.Password, realm, _request.HttpMethod, null) : false; if (valid) _user = new GenericPrincipal (id, cred.Roles); } #endregion #region Public Methods /// <summary> /// Returns a <see cref="string"/> that represents the current /// <see cref="TcpListenerWebSocketContext"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the current /// <see cref="TcpListenerWebSocketContext"/>. /// </returns> public override string ToString () { return _request.ToString (); } #endregion } }
// 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! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedWebhooksClientSnippets { /// <summary>Snippet for ListWebhooks</summary> public void ListWebhooksRequestObject() { // Snippet: ListWebhooks(ListWebhooksRequest, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) ListWebhooksRequest request = new ListWebhooksRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request PagedEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooks(request); // Iterate over all response items, lazily performing RPCs as required foreach (Webhook item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWebhooksResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWebhooksAsync</summary> public async Task ListWebhooksRequestObjectAsync() { // Snippet: ListWebhooksAsync(ListWebhooksRequest, CallSettings) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) ListWebhooksRequest request = new ListWebhooksRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request PagedAsyncEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooksAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Webhook item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWebhooksResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWebhooks</summary> public void ListWebhooks() { // Snippet: ListWebhooks(string, string, int?, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request PagedEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooks(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Webhook item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWebhooksResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWebhooksAsync</summary> public async Task ListWebhooksAsync() { // Snippet: ListWebhooksAsync(string, string, int?, CallSettings) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request PagedAsyncEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooksAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Webhook item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWebhooksResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWebhooks</summary> public void ListWebhooksResourceNames() { // Snippet: ListWebhooks(AgentName, string, int?, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request PagedEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooks(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Webhook item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWebhooksResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWebhooksAsync</summary> public async Task ListWebhooksResourceNamesAsync() { // Snippet: ListWebhooksAsync(AgentName, string, int?, CallSettings) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request PagedAsyncEnumerable<ListWebhooksResponse, Webhook> response = webhooksClient.ListWebhooksAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Webhook item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWebhooksResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Webhook item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Webhook> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Webhook item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetWebhook</summary> public void GetWebhookRequestObject() { // Snippet: GetWebhook(GetWebhookRequest, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) GetWebhookRequest request = new GetWebhookRequest { WebhookName = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"), }; // Make the request Webhook response = webhooksClient.GetWebhook(request); // End snippet } /// <summary>Snippet for GetWebhookAsync</summary> public async Task GetWebhookRequestObjectAsync() { // Snippet: GetWebhookAsync(GetWebhookRequest, CallSettings) // Additional: GetWebhookAsync(GetWebhookRequest, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) GetWebhookRequest request = new GetWebhookRequest { WebhookName = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"), }; // Make the request Webhook response = await webhooksClient.GetWebhookAsync(request); // End snippet } /// <summary>Snippet for GetWebhook</summary> public void GetWebhook() { // Snippet: GetWebhook(string, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/webhooks/[WEBHOOK]"; // Make the request Webhook response = webhooksClient.GetWebhook(name); // End snippet } /// <summary>Snippet for GetWebhookAsync</summary> public async Task GetWebhookAsync() { // Snippet: GetWebhookAsync(string, CallSettings) // Additional: GetWebhookAsync(string, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/webhooks/[WEBHOOK]"; // Make the request Webhook response = await webhooksClient.GetWebhookAsync(name); // End snippet } /// <summary>Snippet for GetWebhook</summary> public void GetWebhookResourceNames() { // Snippet: GetWebhook(WebhookName, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) WebhookName name = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"); // Make the request Webhook response = webhooksClient.GetWebhook(name); // End snippet } /// <summary>Snippet for GetWebhookAsync</summary> public async Task GetWebhookResourceNamesAsync() { // Snippet: GetWebhookAsync(WebhookName, CallSettings) // Additional: GetWebhookAsync(WebhookName, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) WebhookName name = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"); // Make the request Webhook response = await webhooksClient.GetWebhookAsync(name); // End snippet } /// <summary>Snippet for CreateWebhook</summary> public void CreateWebhookRequestObject() { // Snippet: CreateWebhook(CreateWebhookRequest, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) CreateWebhookRequest request = new CreateWebhookRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Webhook = new Webhook(), }; // Make the request Webhook response = webhooksClient.CreateWebhook(request); // End snippet } /// <summary>Snippet for CreateWebhookAsync</summary> public async Task CreateWebhookRequestObjectAsync() { // Snippet: CreateWebhookAsync(CreateWebhookRequest, CallSettings) // Additional: CreateWebhookAsync(CreateWebhookRequest, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) CreateWebhookRequest request = new CreateWebhookRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Webhook = new Webhook(), }; // Make the request Webhook response = await webhooksClient.CreateWebhookAsync(request); // End snippet } /// <summary>Snippet for CreateWebhook</summary> public void CreateWebhook() { // Snippet: CreateWebhook(string, Webhook, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; Webhook webhook = new Webhook(); // Make the request Webhook response = webhooksClient.CreateWebhook(parent, webhook); // End snippet } /// <summary>Snippet for CreateWebhookAsync</summary> public async Task CreateWebhookAsync() { // Snippet: CreateWebhookAsync(string, Webhook, CallSettings) // Additional: CreateWebhookAsync(string, Webhook, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; Webhook webhook = new Webhook(); // Make the request Webhook response = await webhooksClient.CreateWebhookAsync(parent, webhook); // End snippet } /// <summary>Snippet for CreateWebhook</summary> public void CreateWebhookResourceNames() { // Snippet: CreateWebhook(AgentName, Webhook, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); Webhook webhook = new Webhook(); // Make the request Webhook response = webhooksClient.CreateWebhook(parent, webhook); // End snippet } /// <summary>Snippet for CreateWebhookAsync</summary> public async Task CreateWebhookResourceNamesAsync() { // Snippet: CreateWebhookAsync(AgentName, Webhook, CallSettings) // Additional: CreateWebhookAsync(AgentName, Webhook, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); Webhook webhook = new Webhook(); // Make the request Webhook response = await webhooksClient.CreateWebhookAsync(parent, webhook); // End snippet } /// <summary>Snippet for UpdateWebhook</summary> public void UpdateWebhookRequestObject() { // Snippet: UpdateWebhook(UpdateWebhookRequest, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) UpdateWebhookRequest request = new UpdateWebhookRequest { Webhook = new Webhook(), UpdateMask = new FieldMask(), }; // Make the request Webhook response = webhooksClient.UpdateWebhook(request); // End snippet } /// <summary>Snippet for UpdateWebhookAsync</summary> public async Task UpdateWebhookRequestObjectAsync() { // Snippet: UpdateWebhookAsync(UpdateWebhookRequest, CallSettings) // Additional: UpdateWebhookAsync(UpdateWebhookRequest, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) UpdateWebhookRequest request = new UpdateWebhookRequest { Webhook = new Webhook(), UpdateMask = new FieldMask(), }; // Make the request Webhook response = await webhooksClient.UpdateWebhookAsync(request); // End snippet } /// <summary>Snippet for UpdateWebhook</summary> public void UpdateWebhook() { // Snippet: UpdateWebhook(Webhook, FieldMask, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) Webhook webhook = new Webhook(); FieldMask updateMask = new FieldMask(); // Make the request Webhook response = webhooksClient.UpdateWebhook(webhook, updateMask); // End snippet } /// <summary>Snippet for UpdateWebhookAsync</summary> public async Task UpdateWebhookAsync() { // Snippet: UpdateWebhookAsync(Webhook, FieldMask, CallSettings) // Additional: UpdateWebhookAsync(Webhook, FieldMask, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) Webhook webhook = new Webhook(); FieldMask updateMask = new FieldMask(); // Make the request Webhook response = await webhooksClient.UpdateWebhookAsync(webhook, updateMask); // End snippet } /// <summary>Snippet for DeleteWebhook</summary> public void DeleteWebhookRequestObject() { // Snippet: DeleteWebhook(DeleteWebhookRequest, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) DeleteWebhookRequest request = new DeleteWebhookRequest { WebhookName = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"), Force = false, }; // Make the request webhooksClient.DeleteWebhook(request); // End snippet } /// <summary>Snippet for DeleteWebhookAsync</summary> public async Task DeleteWebhookRequestObjectAsync() { // Snippet: DeleteWebhookAsync(DeleteWebhookRequest, CallSettings) // Additional: DeleteWebhookAsync(DeleteWebhookRequest, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) DeleteWebhookRequest request = new DeleteWebhookRequest { WebhookName = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"), Force = false, }; // Make the request await webhooksClient.DeleteWebhookAsync(request); // End snippet } /// <summary>Snippet for DeleteWebhook</summary> public void DeleteWebhook() { // Snippet: DeleteWebhook(string, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/webhooks/[WEBHOOK]"; // Make the request webhooksClient.DeleteWebhook(name); // End snippet } /// <summary>Snippet for DeleteWebhookAsync</summary> public async Task DeleteWebhookAsync() { // Snippet: DeleteWebhookAsync(string, CallSettings) // Additional: DeleteWebhookAsync(string, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/webhooks/[WEBHOOK]"; // Make the request await webhooksClient.DeleteWebhookAsync(name); // End snippet } /// <summary>Snippet for DeleteWebhook</summary> public void DeleteWebhookResourceNames() { // Snippet: DeleteWebhook(WebhookName, CallSettings) // Create client WebhooksClient webhooksClient = WebhooksClient.Create(); // Initialize request argument(s) WebhookName name = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"); // Make the request webhooksClient.DeleteWebhook(name); // End snippet } /// <summary>Snippet for DeleteWebhookAsync</summary> public async Task DeleteWebhookResourceNamesAsync() { // Snippet: DeleteWebhookAsync(WebhookName, CallSettings) // Additional: DeleteWebhookAsync(WebhookName, CancellationToken) // Create client WebhooksClient webhooksClient = await WebhooksClient.CreateAsync(); // Initialize request argument(s) WebhookName name = WebhookName.FromProjectLocationAgentWebhook("[PROJECT]", "[LOCATION]", "[AGENT]", "[WEBHOOK]"); // Make the request await webhooksClient.DeleteWebhookAsync(name); // End snippet } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; namespace Umbraco.Extensions { public static class UrlProviderExtensions { /// <summary> /// Gets the URLs of the content item. /// </summary> /// <remarks> /// <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para> /// <para>Contains all the URLs that we can figure out (based upon domains, etc).</para> /// </remarks> public static async Task<IEnumerable<UrlInfo>> GetContentUrlsAsync( this IContent content, IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, ILocalizationService localizationService, ILocalizedTextService textService, IContentService contentService, IVariationContextAccessor variationContextAccessor, ILogger<IContent> logger, UriUtility uriUtility, IPublishedUrlProvider publishedUrlProvider) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (publishedRouter == null) { throw new ArgumentNullException(nameof(publishedRouter)); } if (umbracoContext == null) { throw new ArgumentNullException(nameof(umbracoContext)); } if (localizationService == null) { throw new ArgumentNullException(nameof(localizationService)); } if (textService == null) { throw new ArgumentNullException(nameof(textService)); } if (contentService == null) { throw new ArgumentNullException(nameof(contentService)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (publishedUrlProvider == null) { throw new ArgumentNullException(nameof(publishedUrlProvider)); } if (uriUtility == null) { throw new ArgumentNullException(nameof(uriUtility)); } if (variationContextAccessor == null) { throw new ArgumentNullException(nameof(variationContextAccessor)); } var result = new List<UrlInfo>(); if (content.Published == false) { result.Add(UrlInfo.Message(textService.Localize("content", "itemNotPublished"))); return result; } // build a list of URLs, for the back-office // which will contain // - the 'main' URLs, which is what .Url would return, for each culture // - the 'other' URLs we know (based upon domains, etc) // // need to work through each installed culture: // on invariant nodes, each culture returns the same URL segment but, // we don't know if the branch to this content is invariant, so we need to ask // for URLs for all cultures. // and, not only for those assigned to domains in the branch, because we want // to show what GetUrl() would return, for every culture. var urls = new HashSet<UrlInfo>(); var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList(); // get all URLs for all cultures // in a HashSet, so de-duplicates too foreach (UrlInfo cultureUrl in await GetContentUrlsByCultureAsync(content, cultures, publishedRouter, umbracoContext, contentService, textService, variationContextAccessor, logger, uriUtility, publishedUrlProvider)) { urls.Add(cultureUrl); } // return the real URLs first, then the messages foreach (IGrouping<bool, UrlInfo> urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key)) { // in some cases there will be the same URL for multiple cultures: // * The entire branch is invariant // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed if (urlGroup.Key) { result.AddRange(urlGroup.DistinctBy(x => x.Text.ToUpperInvariant()) .OrderBy(x => x.Text).ThenBy(x => x.Culture)); } else { result.AddRange(urlGroup); } } // get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless. // for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them. foreach (UrlInfo otherUrl in publishedUrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text) .ThenBy(x => x.Culture)) { // avoid duplicates if (urls.Add(otherUrl)) { result.Add(otherUrl); } } return result; } /// <summary> /// Tries to return a <see cref="UrlInfo" /> for each culture for the content while detecting collisions/errors /// </summary> private static async Task<IEnumerable<UrlInfo>> GetContentUrlsByCultureAsync( IContent content, IEnumerable<string> cultures, IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, IContentService contentService, ILocalizedTextService textService, IVariationContextAccessor variationContextAccessor, ILogger logger, UriUtility uriUtility, IPublishedUrlProvider publishedUrlProvider) { var result = new List<UrlInfo>(); foreach (var culture in cultures) { // if content is variant, and culture is not published, skip if (content.ContentType.VariesByCulture() && !content.IsCulturePublished(culture)) { continue; } // if it's variant and culture is published, or if it's invariant, proceed string url; try { url = publishedUrlProvider.GetUrl(content.Id, culture: culture); } catch (Exception ex) { logger.LogError(ex, "GetUrl exception."); url = "#ex"; } switch (url) { // deal with 'could not get the URL' case "#": result.Add(HandleCouldNotGetUrl(content, culture, contentService, textService)); break; // deal with exceptions case "#ex": result.Add(UrlInfo.Message(textService.Localize("content", "getUrlException"), culture)); break; // got a URL, deal with collisions, add URL default: // detect collisions, etc Attempt<UrlInfo> hasCollision = await DetectCollisionAsync(logger, content, url, culture, umbracoContext, publishedRouter, textService, variationContextAccessor, uriUtility); if (hasCollision) { result.Add(hasCollision.Result); } else { result.Add(UrlInfo.Url(url, culture)); } break; } } return result; } private static UrlInfo HandleCouldNotGetUrl(IContent content, string culture, IContentService contentService, ILocalizedTextService textService) { // document has a published version yet its URL is "#" => a parent must be // unpublished, walk up the tree until we find it, and report. IContent parent = content; do { parent = parent.ParentId > 0 ? contentService.GetParent(parent) : null; } while (parent != null && parent.Published && (!parent.ContentType.VariesByCulture() || parent.IsCulturePublished(culture))); if (parent == null) { // oops, internal error return UrlInfo.Message(textService.Localize("content", "parentNotPublishedAnomaly"), culture); } if (!parent.Published) { // totally not published return UrlInfo.Message(textService.Localize("content", "parentNotPublished", new[] { parent.Name }), culture); } // culture not published return UrlInfo.Message(textService.Localize("content", "parentCultureNotPublished", new[] { parent.Name }), culture); } private static async Task<Attempt<UrlInfo>> DetectCollisionAsync(ILogger logger, IContent content, string url, string culture, IUmbracoContext umbracoContext, IPublishedRouter publishedRouter, ILocalizedTextService textService, IVariationContextAccessor variationContextAccessor, UriUtility uriUtility) { // test for collisions on the 'main' URL var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri == false) { uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl); } uri = uriUtility.UriToUmbraco(uri); IPublishedRequestBuilder builder = await publishedRouter.CreateRequestAsync(uri); IPublishedRequest pcr = await publishedRouter.RouteRequestAsync(builder, new RouteRequestOptions(RouteDirection.Outbound)); if (!pcr.HasPublishedContent()) { var logMsg = nameof(DetectCollisionAsync) + " did not resolve a content item for original url: {Url}, translated to {TranslatedUrl} and culture: {Culture}"; if (pcr.IgnorePublishedContentCollisions) { logger.LogDebug(logMsg, url, uri, culture); } else { logger.LogDebug(logMsg, url, uri, culture); } var urlInfo = UrlInfo.Message(textService.Localize("content", "routeErrorCannotRoute"), culture); return Attempt.Succeed(urlInfo); } if (pcr.IgnorePublishedContentCollisions) { return Attempt<UrlInfo>.Fail(); } if (pcr.PublishedContent.Id != content.Id) { IPublishedContent o = pcr.PublishedContent; var l = new List<string>(); while (o != null) { l.Add(o.Name(variationContextAccessor)); o = o.Parent; } l.Reverse(); var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent.Id + ")"; var urlInfo = UrlInfo.Message(textService.Localize("content", "routeError", new[] { s }), culture); return Attempt.Succeed(urlInfo); } // no collision return Attempt<UrlInfo>.Fail(); } } }
namespace LanfeustBridge.Services; /// <summary> /// Implementation of the IUserStore part of UserStoreService, along with the optional parts. /// </summary> public sealed partial class UserStoreService : IUserStore<User>, IUserPasswordStore<User>, IUserEmailStore<User>, IUserPhoneNumberStore<User>, IUserLoginStore<User>, IUserTwoFactorStore<User>, IUserAuthenticatorKeyStore<User>, IUserTwoFactorRecoveryCodeStore<User>, IQueryableUserStore<User> { private readonly ILogger _logger; private readonly ILiteCollection<User> _users; private readonly ILiteCollection<Role> _roles; public UserStoreService(ILogger<UserStoreService> logger, DbService dbService) { _logger = logger; _users = dbService.Db.GetCollection<User>(); _users.EnsureIndex(u => u.NormalizedUserName); _users.EnsureIndex(u => u.NormalizedEmail); _users.EnsureIndex(u => u.ExternalLogins); _roles = dbService.Db.GetCollection<Role>(); _roles.EnsureIndex(u => u.NormalizedName); } public IQueryable<User> Users => _users.FindAll().AsQueryable(); public void Dispose() { } public Task<IdentityResult> CreateAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (string.IsNullOrWhiteSpace(user.DisplayName)) user.DisplayName = user.UserName; _users.Insert(user); _logger.LogInformation("User {UserEmail} created", user.Email); return Task.FromResult(IdentityResult.Success); } public Task<IdentityResult> UpdateAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); _users.Update(user.Id, user); return Task.FromResult(IdentityResult.Success); } public Task<IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); _users.Delete(user.Id); return Task.FromResult(IdentityResult.Success); } public Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (userId == null) throw new ArgumentNullException(nameof(userId)); var user = _users.FindById(userId); return Task.FromResult(user); } public Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (normalizedUserName == null) throw new ArgumentNullException(nameof(normalizedUserName)); var user = _users.FindOne(u => u.NormalizedUserName == normalizedUserName); return Task.FromResult(user); } public Task<User> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (normalizedEmail == null) throw new ArgumentNullException(nameof(normalizedEmail)); var user = _users.FindOne(u => u.NormalizedEmail == normalizedEmail); return Task.FromResult(user); } public Task<string> GetUserIdAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Id); } public Task<string> GetUserNameAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.UserName); } public Task SetUserNameAsync(User user, string userName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.UserName = userName ?? throw new ArgumentNullException(nameof(userName)); return Task.CompletedTask; } public Task<string> GetNormalizedUserNameAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.NormalizedUserName); } public Task SetNormalizedUserNameAsync(User user, string normalizedName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.NormalizedUserName = normalizedName ?? throw new ArgumentNullException(nameof(normalizedName)); return Task.CompletedTask; } public Task<string> GetPasswordHashAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.PasswordHash); } public Task<bool> HasPasswordAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(!string.IsNullOrEmpty(user.PasswordHash)); } public Task SetPasswordHashAsync(User user, string passwordHash, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.PasswordHash = passwordHash ?? throw new ArgumentNullException(nameof(passwordHash)); return Task.CompletedTask; } public Task<string> GetEmailAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Email); } public Task SetEmailAsync(User user, string email, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.Email = email ?? throw new ArgumentNullException(nameof(email)); return Task.CompletedTask; } public Task<string> GetNormalizedEmailAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.NormalizedEmail); } public Task SetNormalizedEmailAsync(User user, string normalizedEmail, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.NormalizedEmail = normalizedEmail ?? throw new ArgumentNullException(nameof(normalizedEmail)); return Task.CompletedTask; } public Task<bool> GetEmailConfirmedAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.EmailConfirmed); } public Task SetEmailConfirmedAsync(User user, bool confirmed, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.EmailConfirmed = confirmed; return Task.CompletedTask; } public Task<string> GetPhoneNumberAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.PhoneNumber); } public Task SetPhoneNumberAsync(User user, string phoneNumber, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); return Task.CompletedTask; } public Task<bool> GetPhoneNumberConfirmedAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.PhoneNumberConfirmed); } public Task SetPhoneNumberConfirmedAsync(User user, bool confirmed, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.PhoneNumberConfirmed = confirmed; return Task.CompletedTask; } public Task AddLoginAsync(User user, UserLoginInfo login, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (login == null) throw new ArgumentNullException(nameof(login)); var loginString = $"{login.LoginProvider}|{login.ProviderKey}"; if (!user.ExternalLogins.Contains(loginString)) user.ExternalLogins.Add(loginString); return Task.CompletedTask; } public Task RemoveLoginAsync(User user, string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (loginProvider == null) throw new ArgumentNullException(nameof(loginProvider)); if (providerKey == null) throw new ArgumentNullException(nameof(providerKey)); user.ExternalLogins.Remove($"{loginProvider}|{providerKey}"); return Task.CompletedTask; } public Task<IList<UserLoginInfo>> GetLoginsAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); var result = user.ExternalLogins.Select(l => { var parts = l.Split('|'); return new UserLoginInfo(parts[0], parts[1], parts[0]); }).ToArray(); return Task.FromResult<IList<UserLoginInfo>>(result); } public Task<User> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (loginProvider == null) throw new ArgumentNullException(nameof(loginProvider)); if (providerKey == null) throw new ArgumentNullException(nameof(providerKey)); var loginString = $"{loginProvider}|{providerKey}"; var user = _users.FindOne(u => u.ExternalLogins.Contains(loginString)); return Task.FromResult(user); } public Task<bool> GetTwoFactorEnabledAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.IsTwoFactorEnabled); } public Task SetTwoFactorEnabledAsync(User user, bool enabled, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.IsTwoFactorEnabled = enabled; return Task.CompletedTask; } public Task<string?> GetAuthenticatorKeyAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.AuthenticatorKey); } public Task SetAuthenticatorKeyAsync(User user, string key, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); user.AuthenticatorKey = key ?? throw new ArgumentNullException(nameof(key)); return Task.CompletedTask; } public Task ReplaceCodesAsync(User user, IEnumerable<string> recoveryCodes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (recoveryCodes == null) throw new ArgumentNullException(nameof(recoveryCodes)); user.RecoveryCodes.Clear(); user.RecoveryCodes.AddRange(recoveryCodes); return Task.CompletedTask; } public Task<bool> RedeemCodeAsync(User user, string code, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (code == null) throw new ArgumentNullException(nameof(code)); // allow if code was successfully found *and* removed return Task.FromResult(user.RecoveryCodes.Remove(code)); } public Task<int> CountCodesAsync(User user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.RecoveryCodes.Count); } }
//------------------------------------------------------------------------------ // <copyright file="Int64Storage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Xml; using System.Data.SqlTypes; using System.Collections; internal sealed class Int64Storage : DataStorage { private const Int64 defaultValue = 0; private Int64[] values; internal Int64Storage(DataColumn column) : base(column, typeof(Int64), defaultValue, StorageType.Int64) { } override public Object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: Int64 sum = defaultValue; foreach (int record in records) { if (HasValue(record)) { checked { sum += values[record];} hasData = true; } } if (hasData) { return sum; } return NullValue; case AggregateType.Mean: Decimal meanSum = (Decimal)defaultValue; int meanCount = 0; foreach (int record in records) { if (HasValue(record)) { checked { meanSum += (Decimal)values[record];} meanCount++; hasData = true; } } if (hasData) { Int64 mean; checked {mean = (Int64)(Decimal)(meanSum / (Decimal) meanCount);} return mean; } return NullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = 0.0f; double prec = 0.0f; double dsum = 0.0f; double sqrsum = 0.0f; foreach (int record in records) { if (HasValue(record)) { dsum += (double)values[record]; sqrsum += (double)values[record]*(double)values[record]; count++; } } if (count > 1) { var = ((double)count * sqrsum - (dsum * dsum)); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var <0)) var = 0; else var = var / (count * (count -1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return NullValue; case AggregateType.Min: Int64 min = Int64.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min=Math.Min(values[record], min); hasData = true; } } if (hasData) { return min; } return NullValue; case AggregateType.Max: Int64 max = Int64.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max=Math.Max(values[record], max); hasData = true; } } if (hasData) { return max; } return NullValue; case AggregateType.First: if (records.Length > 0) { return values[records[0]]; } return null; case AggregateType.Count: return base.Aggregate(records, kind); } } catch (OverflowException) { throw ExprException.Overflow(typeof(Int64)); } throw ExceptionBuilder.AggregateException(kind, DataType); } override public int Compare(int recordNo1, int recordNo2) { Int64 valueNo1 = values[recordNo1]; Int64 valueNo2 = values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } //return valueNo1.CompareTo(valueNo2); return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int64.CompareTo(Int64) } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { return (HasValue(recordNo) ? 1 : 0); } Int64 valueNo1 = values[recordNo]; if ((defaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return valueNo1.CompareTo((Int64)value); //return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int64.CompareTo(Int64) } public override object ConvertValue(object value) { if (NullValue != value) { if (null != value) { value = ((IConvertible)value).ToInt64(FormatProvider); } else { value = NullValue; } } return value; } override public void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); values[recordNo2] = values[recordNo1]; } override public Object Get(int record) { Int64 value = values[record]; if (value != defaultValue) { return value; } return GetBits(record); } override public void Set(int record, Object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { values[record] = defaultValue; SetNullBit(record, true); } else { values[record] = ((IConvertible)value).ToInt64(FormatProvider); SetNullBit(record, false); } } override public void SetCapacity(int capacity) { Int64[] newValues = new Int64[capacity]; if (null != values) { Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length)); } values = newValues; base.SetCapacity(capacity); } override public object ConvertXmlToObject(string s) { return XmlConvert.ToInt64(s); } override public string ConvertObjectToXml(object value) { return XmlConvert.ToString((Int64)value); } override protected object GetEmptyStorage(int recordCount) { return new Int64[recordCount]; } override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { Int64[] typedStore = (Int64[]) store; typedStore[storeIndex] = values[record]; nullbits.Set(storeIndex, !HasValue(record)); } override protected void SetStorage(object store, BitArray nullbits) { values = (Int64[]) store; SetNullStorage(nullbits); } } }
/* Copyright 2014 Clarius Consulting SA 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 */ namespace TracerHub.Diagnostics { using System; using System.Diagnostics; using System.Globalization; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; /// <summary> /// Extensions to <see cref="ITracer"/> for activity tracing. /// </summary> static partial class StartActivityExtension { /// <summary> /// Starts a new activity scope. /// </summary> public static IDisposable StartActivity(this ITracer tracer, string format, params object[] args) { return new TraceActivity(tracer, format, args); } /// <summary> /// Starts a new activity scope. /// </summary> public static IDisposable StartActivity(this ITracer tracer, string displayName) { return new TraceActivity(tracer, displayName); } /// <devdoc> /// In order for activity tracing to happen, the trace source needs to /// have <see cref="SourceLevels.ActivityTracing"/> enabled. /// </devdoc> partial class TraceActivity : IDisposable { string displayName; bool disposed; ITracer tracer; Guid oldId; Guid newId; public TraceActivity(ITracer tracer, string displayName) : this(tracer, displayName, null) { } public TraceActivity(ITracer tracer, string displayName, params object[] args) { this.tracer = tracer; this.displayName = displayName; if (args != null && args.Length > 0) this.displayName = string.Format(displayName, args, CultureInfo.CurrentCulture); newId = Guid.NewGuid(); oldId = Trace.CorrelationManager.ActivityId; tracer.Trace(TraceEventType.Transfer, this.newId); Trace.CorrelationManager.ActivityId = newId; // The XmlWriterTraceListener expects Start/Stop events to receive an XPathNavigator // with XML in a specific format so that the Service Trace Viewer can properly render // the activity graph. tracer.Trace(TraceEventType.Start, new ActivityData(this.displayName, true)); } public void Dispose() { if (!this.disposed) { tracer.Trace(TraceEventType.Stop, new ActivityData(displayName, false)); tracer.Trace(TraceEventType.Transfer, oldId); Trace.CorrelationManager.ActivityId = oldId; } this.disposed = true; } class ActivityData : XPathNavigator { string displayName; XPathNavigator xml; public ActivityData(string displayName, bool isStart) { this.displayName = displayName; // The particular XML format expected by the Service Trace Viewer was // inferred from the actual tool behavior and usage. this.xml = XDocument.Parse(string.Format(@" <TraceRecord xmlns='http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord' Severity='{0}'> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ActivityBoundary.aspx</TraceIdentifier> <Description>Activity boundary.</Description> <AppDomain>client.vshost.exe</AppDomain> <ExtendedData xmlns='http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord'> <ActivityName>{1}</ActivityName> <ActivityType>ActivityTracing</ActivityType> </ExtendedData> </TraceRecord>", isStart ? "Start" : "Stop", displayName)).CreateNavigator(); } public override string BaseURI { get { return xml.BaseURI; } } public override XPathNavigator Clone() { return xml.Clone(); } public override bool IsEmptyElement { get { return xml.IsEmptyElement; } } public override bool IsSamePosition(XPathNavigator other) { return xml.IsSamePosition(other); } public override string LocalName { get { return xml.LocalName; } } public override bool MoveTo(XPathNavigator other) { return xml.MoveTo(other); } public override bool MoveToFirstAttribute() { return xml.MoveToFirstAttribute(); } public override bool MoveToFirstChild() { return xml.MoveToFirstChild(); } public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { return xml.MoveToFirstNamespace(namespaceScope); } public override bool MoveToId(string id) { return xml.MoveToId(id); } public override bool MoveToNext() { return xml.MoveToNext(); } public override bool MoveToNextAttribute() { return xml.MoveToNextAttribute(); } public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { return xml.MoveToNextNamespace(namespaceScope); } public override bool MoveToParent() { return xml.MoveToParent(); } public override bool MoveToPrevious() { return xml.MoveToPrevious(); } public override string Name { get { return xml.Name; } } public override XmlNameTable NameTable { get { return xml.NameTable; } } public override string NamespaceURI { get { return xml.NamespaceURI; } } public override XPathNodeType NodeType { get { return xml.NodeType; } } public override string Prefix { get { return xml.Prefix; } } public override string Value { get { return xml.Value; } } public override string ToString() { return displayName; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); }); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); }); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108135")] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); }); } [WorkItem(1117084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1117084")] [Fact] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var compilation = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var compilation = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")), runtime => { string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", ImmutableArray<Alias>.Empty, (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); }); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Reflection; namespace OpenTK { /// <summary>Provides information about the underlying OS and runtime.</summary> public static class Configuration { static bool runningOnWindows, runningOnUnix, runningOnX11, runningOnMacOS, runningOnLinux, runningOnMono; volatile static bool initialized; readonly static object InitLock = new object(); #region Constructors // Detects the underlying OS and runtime. static Configuration() { Toolkit.Init(); } #endregion #region Public Methods #region public static bool RunningOnWindows /// <summary>Gets a System.Boolean indicating whether OpenTK is running on a Windows platform.</summary> public static bool RunningOnWindows { get { return runningOnWindows; } } #endregion #region public static bool RunningOnX11 /// <summary>Gets a System.Boolean indicating whether OpenTK is running on an X11 platform.</summary> public static bool RunningOnX11 { get { return runningOnX11; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether OpenTK is running on a Unix platform. /// </summary> public static bool RunningOnUnix { get { return runningOnUnix; } } #endregion #region public static bool RunningOnLinux /// <summary>Gets a System.Boolean indicating whether OpenTK is running on an X11 platform.</summary> public static bool RunningOnLinux { get { return runningOnLinux; } } #endregion #region public static bool RunningOnMacOS /// <summary>Gets a System.Boolean indicating whether OpenTK is running on a MacOS platform.</summary> public static bool RunningOnMacOS { get { return runningOnMacOS; } } #endregion #region public static bool RunningOnMono /// <summary> /// Gets a System.Boolean indicating whether OpenTK is running on the Mono runtime. /// </summary> public static bool RunningOnMono { get { return runningOnMono; } } #endregion #region --- Private Methods --- #region private static string DetectUnixKernel() [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] struct utsname { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string machine; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public string extraJustInCase; } /// <summary> /// Detects the unix kernel by p/invoking uname (libc). /// </summary> /// <returns></returns> private static string DetectUnixKernel() { Debug.Print("Size: {0}", Marshal.SizeOf(typeof(utsname)).ToString()); Debug.Flush(); utsname uts = new utsname(); uname(out uts); Debug.WriteLine("System:"); Debug.Indent(); Debug.WriteLine(uts.sysname); Debug.WriteLine(uts.nodename); Debug.WriteLine(uts.release); Debug.WriteLine(uts.version); Debug.WriteLine(uts.machine); Debug.Unindent(); return uts.sysname.ToString(); } [DllImport("libc")] private static extern void uname(out utsname uname_struct); #endregion #endregion #endregion #region Internal Methods internal static void Init() { lock (InitLock) { if (!initialized) { initialized = true; if (System.Environment.OSVersion.Platform == PlatformID.Win32NT || System.Environment.OSVersion.Platform == PlatformID.Win32S || System.Environment.OSVersion.Platform == PlatformID.Win32Windows || System.Environment.OSVersion.Platform == PlatformID.WinCE) { runningOnWindows = true; } else if (System.Environment.OSVersion.Platform == PlatformID.Unix || System.Environment.OSVersion.Platform == (PlatformID)4) { // Distinguish between Linux, Mac OS X and other Unix operating systems. string kernel_name = DetectUnixKernel(); switch (kernel_name) { case null: case "": throw new PlatformNotSupportedException( "Unknown platform. Please file a bug report at http://www.opentk.com/node/add/project-issue/opentk"); case "Linux": runningOnLinux = runningOnUnix = true; break; case "Darwin": runningOnMacOS = runningOnUnix = true; break; default: runningOnUnix = true; break; } } else throw new PlatformNotSupportedException("Unknown platform. Please report this error at http://www.opentk.com."); // Detect whether X is present. // Hack: it seems that this check will cause X to initialize itself on Mac OS X Leopard and newer. // We don't want that (we'll be using the native interfaces anyway), so we'll avoid this check // when we detect Mac OS X. if (!RunningOnMacOS) { try { runningOnX11 = OpenTK.Platform.X11.API.DefaultDisplay != IntPtr.Zero; } catch { } } // Detect the Mono runtime (code taken from http://mono.wikia.com/wiki/Detecting_if_program_is_running_in_Mono). Type t = Type.GetType("Mono.Runtime"); if (t != null) runningOnMono = true; Debug.Print("Detected configuration: {0} / {1}", RunningOnWindows ? "Windows" : RunningOnLinux ? "Linux" : RunningOnMacOS ? "MacOS" : runningOnUnix ? "Unix" : RunningOnX11 ? "X11" : "Unknown Platform", RunningOnMono ? "Mono" : ".Net"); } } } #endregion } }
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; using System.Drawing.Design; using System.Globalization; using System.Security.Permissions; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Workflow; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Design; using System.Collections.Generic; using EnvDTE; using System.Reflection; using Microsoft.VisualStudio.Shell.Design; using Microsoft.VisualStudio.Shell.Interop; using System.Collections; using Microsoft.VisualStudio.Shell; using WmcSoft.VisualStudio; namespace WmcSoft.ComponentModel.Design { public class FilteredTypeBrowser : UITypeEditor { /// <summary> /// Configuration attribute with the name "Filter", to set an <see cref="ITypeFilterProvider"/> type /// to use to filter the browse dialog. /// </summary> public const string FilterAttribute = "Filter"; Type filterType; TypeBrowserEditor editor = new TypeBrowserEditor(); ContextProxy flyweight; /// <summary> /// Edits the specified object's value using the editor style indicated by the <see cref="M:System.Drawing.Design.UITypeEditor.GetEditStyle"></see> method. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that can be used to gain additional context information.</param> /// <param name="provider">An <see cref="T:System.IServiceProvider"></see> that this editor can use to obtain services.</param> /// <param name="value">The object to edit.</param> /// <returns> /// The new value of the object. If the value of the object has not changed, this should return the same object it was passed. /// </returns> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { // Use flyweight pattern to improve performance. It's guaranteed that no more than one instance of // this editor can ever be used at the same time. (it's modal) DetermineFilterType(context); if (flyweight == null) { flyweight = new ContextProxy(context, filterType); } else { flyweight.SetContext(context); } //value = editor.EditValue(flyweight, provider, value); value = editor.EditValue(flyweight, flyweight, value); return value; } /// <summary> /// Gets the edit style. /// </summary> /// <param name="context">The type descriptor context.</param> /// <returns></returns> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return editor.GetEditStyle(context); } #region Private Implementation private void DetermineFilterType(ITypeDescriptorContext context) { if (filterType == null) { // Look for the attribute in the argument type itself. TypeFilterProviderAttribute filterProvider = context.PropertyDescriptor.Attributes[typeof(TypeFilterProviderAttribute)] as TypeFilterProviderAttribute; if (filterProvider != null) { filterType = GetValidFilterType(filterProvider.TypeFilterProviderTypeName); } } if (filterType == null) { filterType = typeof(PublicTypeFilter); } } private Type GetValidFilterType(string filterTypeName) { Type ft = Type.GetType(filterTypeName, false, true); if (ft == null || !typeof(ITypeFilterProvider).IsAssignableFrom(ft)) { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, WmcSoft.Properties.Resources.InvaInvalidTypeFilter, ft, typeof(ITypeFilterProvider))); } return ft; } #endregion #region ContextProxy class /// <summary> /// This proxy provides the additional ITypeProvider service required by the workflow type browser. /// </summary> private class ContextProxy : ITypeDescriptorContext, IServiceProvider { ITypeFilterProvider filterProvider; ITypeProvider typeProvider; ITypeDescriptorContext context; public ContextProxy(ITypeDescriptorContext context, Type filterType) { this.context = context; this.filterProvider = (ITypeFilterProvider)Activator.CreateInstance(filterType); } /// <summary> /// Allows resetting the context for the flyweight pattern. /// </summary> internal void SetContext(ITypeDescriptorContext context) { this.context = context; } #region ITypeDescriptorContext Members public IContainer Container { get { return context.Container; } } public object Instance { get { return context.Instance; } } public void OnComponentChanged() { context.OnComponentChanged(); } public bool OnComponentChanging() { return context.OnComponentChanging(); } /// <summary> /// Provides custom descriptor if a filter was specified, so that /// the browser can use the filter. /// </summary> public PropertyDescriptor PropertyDescriptor { get { return new TypeFilterPropertyDescriptor(context.PropertyDescriptor, filterProvider); } } #endregion #region IServiceProvider Members /// <summary> /// Provides the <see cref="ITypeProvider"/> service. /// </summary> /// <param name="serviceType"></param> /// <returns></returns> public object GetService(Type serviceType) { if (serviceType == typeof(ITypeProvider)) { if (typeProvider == null) typeProvider = new CustomTypeProvider(this); return typeProvider; } else if (serviceType == typeof(IDesignerHost)) { return new DummyDesignerHost(); } else if (serviceType == typeof(WorkflowDesignerLoader)) { return new DummyWorkflowDesignerLoader(); } else if (serviceType == typeof(IDictionaryService)) { return new DummyDictionaryService(); } return context.GetService(serviceType); } #endregion } #endregion #region CustomTypeProvider class /// <summary> /// Custom <see cref="ITypeProvider"/> that returns the types in the current project and /// its references, using the <see cref="ITypeDiscoveryService"/> service acquired via the /// <see cref="DynamicTypeService"/>. /// </summary> private class CustomTypeProvider : ITypeProvider { Dictionary<string, Type> availableTypes; /// <summary> /// Initializes a new instance of the <see cref="T:CustomTypeProvider"/> class. /// </summary> /// <param name="provider">The provider.</param> public CustomTypeProvider(IServiceProvider provider) { DynamicTypeService typeService = (DynamicTypeService)provider.GetService(typeof(DynamicTypeService)); System.Diagnostics.Debug.Assert(typeService != null, "No dynamic type service registered."); IVsHierarchy hier = VsHelper.GetCurrentHierarchy(provider); System.Diagnostics.Debug.Assert(hier != null, "No active hierarchy is selected."); ITypeDiscoveryService discovery = typeService.GetTypeDiscoveryService(hier); Project dteProject = VsHelper.ToDteProject(hier); availableTypes = new Dictionary<string, Type>(); foreach (Type type in discovery.GetTypes(typeof(object), false)) { if (!availableTypes.ContainsKey(type.FullName)) { if (type.Assembly.GetName().Name != (string)dteProject.Properties.Item("AssemblyName").Value) { availableTypes.Add(type.FullName, type); } else { availableTypes.Add(type.FullName, new ProjectType(type)); } } } LoadTypes(availableTypes, discovery.GetTypes(typeof(object), false), dteProject); //// If we don't get any type loaded, try with the rest of the projects in the current sln //if (availableTypes.Count == 0) //{ // IVsSolution solution = provider.GetService(typeof(SVsSolution)) as IVsSolution; // if (solution != null) // { // List<EnvDTE.Project> projectList = new List<Project>(); // TODO: fix //HierarchyNode solutionHierarchy = new HierarchyNode(solution); //solutionHierarchy.RecursiveForEach(delegate(HierarchyNode child) // { // // recurse if this node is a Solution Folder // if (child.TypeGuid != Microsoft.Practices.VisualStudio.Helper.Constants.SolutionFolderGuid) // { // // If this is a project add it to the list // EnvDTE.Project childProject = child.ExtObject as EnvDTE.Project; // if (childProject != null) // projectList.Add(childProject); // } // } //); // LoadTypesFromProjects(projectList, availableTypes, provider, dteProject); //} //} // If we still got no types, load the core types if (availableTypes.Count == 0) { LoadCoreTypes(availableTypes); } if (availableTypes.Count > 0 && TypesChanged != null) { TypesChanged(this, new EventArgs()); } } private void LoadCoreTypes(Dictionary<string, Type> availableTypes) { foreach (Type type in typeof(object).Assembly.GetExportedTypes()) { availableTypes.Add(type.FullName, type); } } private void LoadTypes(Dictionary<string, Type> availableTypes, ICollection types, Project dteProject) { bool isWebProject = false; // TODO: fix DteHelper.IsWebProject(dteProject); string projectAssemblyName = GetAssemblyName(dteProject); foreach (Type type in types) { // Filtering of non-public types must be done with a type filter provider. // By default, if none is specified, the PublicTypeFilter will do just that. if (!availableTypes.ContainsKey(type.FullName)) { // Web projects do not have if (!isWebProject && type.Assembly.GetName().Name != projectAssemblyName) { availableTypes.Add(type.FullName, type); } else { availableTypes.Add(type.FullName, new ProjectType(type)); } } } } private void LoadTypesFromProjects(List<EnvDTE.Project> projects, Dictionary<string, Type> availableTypes, IServiceProvider provider, Project currentProject) { DynamicTypeService typeService = (DynamicTypeService)provider.GetService(typeof(DynamicTypeService)); foreach (Project project in projects) { if (project.UniqueName != currentProject.UniqueName) { IVsHierarchy hier = VsHelper.GetCurrentHierarchy(provider); // TODO: fix DteHelper.GetVsHierarchy(provider, project); System.Diagnostics.Debug.Assert(hier != null, "No active hierarchy is selected."); ITypeDiscoveryService discovery = typeService.GetTypeDiscoveryService(hier); LoadTypes(availableTypes, discovery.GetTypes(typeof(object), false), project); } } } private string GetAssemblyName(Project project) { foreach (Property property in project.Properties) { if (property.Name == "AssemblyName") { return property.Value as string; } } return null; } #region ITypeProvider Members /// <summary/> public event EventHandler TypeLoadErrorsChanged; /// <summary/> public event EventHandler TypesChanged; /// <summary> /// Gets a collection of all assemblies referenced by the <see cref="T:System.Type"></see>. /// </summary> /// <value></value> /// <returns>A collection of all assemblies referenced by the <see cref="T:System.Type"></see>.</returns> public ICollection<Assembly> ReferencedAssemblies { get { throw new NotImplementedException(); } } /// <summary> /// Gets the <see cref="T:System.Type"></see> of the named entity. /// </summary> /// <param name="name">A string that contains the name of the entity.</param> /// <param name="throwOnError">A value that indicates whether to throw an exception if name is not resolvable.</param> /// <returns> /// The <see cref="T:System.Type"></see> of the named entity. /// </returns> public Type GetType(string name, bool throwOnError) { if (String.IsNullOrEmpty(name)) { return null; } if (availableTypes.ContainsKey(name)) { Type type = availableTypes[name]; if (type is TypeDelegator) { return ((TypeDelegator)type).UnderlyingSystemType; } else { return type; } } else { if (throwOnError) { if (TypeLoadErrorsChanged != null) { TypeLoadErrorsChanged(this, new EventArgs()); } throw new TypeLoadException(); } else { return null; } } } public Type GetType(string name) { return GetType(name, false); } public Type[] GetTypes() { Type[] result = new Type[availableTypes.Count]; availableTypes.Values.CopyTo(result, 0); return result; } public System.Reflection.Assembly LocalAssembly { get { return this.GetType().Assembly; } } public System.Collections.Generic.IDictionary<object, Exception> TypeLoadErrors { get { return new Dictionary<object, Exception>(); } } #endregion #region ProjectType private class ProjectType : TypeDelegator { public ProjectType(Type delegatingType) : base(delegatingType) { } public override Assembly Assembly { get { return null; } } } #endregion } #endregion #region IAttributesConfigurable Members /// <summary> /// Configures the component using the dictionary of attributes specified /// in the configuration file. /// </summary> /// <param name="attributes">The attributes in the configuration element.</param> /// // FXCOP: false positive. [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public void Configure(System.Collections.Specialized.StringDictionary attributes) { } #endregion #region Dummy services for type browser initialization private class DummyDictionaryService : IDictionaryService { private Dictionary<object, object> dict = new Dictionary<object, object>(); #region IDictionaryService Members public object GetKey(object value) { throw new NotImplementedException(); } public object GetValue(object key) { if (dict.ContainsKey(key)) { return dict[key]; } return null; } public void SetValue(object key, object value) { if (dict.ContainsKey(key)) { dict[key] = value; } else { dict.Add(key, value); } } #endregion } private class DummyDesignerHost : IDesignerHost { #region IDesignerHost Members public void Activate() { throw new NotImplementedException(); } #pragma warning disable 67 public event EventHandler Activated; #pragma warning restore 67 public IContainer Container { get { return new Container(); } } public IComponent CreateComponent(Type componentClass, string name) { throw new NotImplementedException(); } public IComponent CreateComponent(Type componentClass) { throw new NotImplementedException(); } public DesignerTransaction CreateTransaction(string description) { throw new NotImplementedException(); } public DesignerTransaction CreateTransaction() { throw new NotImplementedException(); } #pragma warning disable 67 public event EventHandler Deactivated; #pragma warning restore 67 public void DestroyComponent(IComponent component) { throw new NotImplementedException(); } public IDesigner GetDesigner(IComponent component) { return null; } public Type GetType(string typeName) { throw new NotImplementedException(); } public bool InTransaction { get { throw new NotImplementedException(); } } #pragma warning disable 67 public event EventHandler LoadComplete; #pragma warning restore 67 public bool Loading { get { throw new NotImplementedException(); } } public IComponent RootComponent { get { return new Component(); } } public string RootComponentClassName { get { throw new NotImplementedException(); } } #pragma warning disable 67 public event DesignerTransactionCloseEventHandler TransactionClosed; public event DesignerTransactionCloseEventHandler TransactionClosing; #pragma warning restore 67 public string TransactionDescription { get { throw new NotImplementedException(); } } #pragma warning disable 67 public event EventHandler TransactionOpened; public event EventHandler TransactionOpening; #pragma warning restore 67 #endregion #region IServiceContainer Members public void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote) { throw new NotImplementedException(); } public void AddService(Type serviceType, ServiceCreatorCallback callback) { throw new NotImplementedException(); } public void AddService(Type serviceType, object serviceInstance, bool promote) { throw new NotImplementedException(); } public void AddService(Type serviceType, object serviceInstance) { throw new NotImplementedException(); } public void RemoveService(Type serviceType, bool promote) { throw new NotImplementedException(); } public void RemoveService(Type serviceType) { throw new NotImplementedException(); } #endregion #region IServiceProvider Members public object GetService(Type serviceType) { return null; } #endregion } private class DummyWorkflowDesignerLoader : WorkflowDesignerLoader { public override string FileName { get { throw new NotImplementedException(); } } public override System.IO.TextReader GetFileReader(string filePath) { throw new NotImplementedException(); } public override System.IO.TextWriter GetFileWriter(string filePath) { throw new NotImplementedException(); } } #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.Engine.Network.Activation; using Encog.MathUtil.Error; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Neural.Error; using Encog.Neural.Flat; using Encog.Util; using Encog.Util.Concurrency; namespace Encog.Neural.Networks.Training.Propagation { /// <summary> /// Worker class for the mulithreaded training of flat networks. /// </summary> /// public class GradientWorker { /// <summary> /// The actual values from the neural network. /// </summary> /// private readonly double[] _actual; /// <summary> /// The error calculation method. /// </summary> /// private readonly ErrorCalculation _errorCalculation; /// <summary> /// The gradients. /// </summary> /// private readonly double[] _gradients; /// <summary> /// The low end of the training. /// </summary> /// private readonly int _high; /// <summary> /// The neuron counts, per layer. /// </summary> /// private readonly int[] _layerCounts; /// <summary> /// The deltas for each layer. /// </summary> /// private readonly double[] _layerDelta; /// <summary> /// The feed counts, per layer. /// </summary> /// private readonly int[] _layerFeedCounts; /// <summary> /// The layer indexes. /// </summary> /// private readonly int[] _layerIndex; /// <summary> /// The output from each layer. /// </summary> /// private readonly double[] _layerOutput; /// <summary> /// The sum from each layer. /// </summary> /// private readonly double[] _layerSums; /// <summary> /// The high end of the training data. /// </summary> /// private readonly int _low; /// <summary> /// The network to train. /// </summary> /// private readonly FlatNetwork _network; /// <summary> /// The owner. /// </summary> /// private readonly Propagation _owner; /// <summary> /// The training data. /// </summary> /// private readonly IMLDataSet _training; /// <summary> /// The index to each layer's weights and thresholds. /// </summary> /// private readonly int[] _weightIndex; /// <summary> /// The weights and thresholds. /// </summary> /// private readonly double[] _weights; /// <summary> /// Derivative add constant. Used to combat flat spot. /// </summary> private readonly double[] _flatSpot; /// <summary> /// The error function. /// </summary> private readonly IErrorFunction _ef; /// <summary> /// Construct a gradient worker. /// </summary> /// /// <param name="theNetwork">The network to train.</param> /// <param name="theOwner">The owner that is doing the training.</param> /// <param name="theTraining">The training data.</param> /// <param name="theLow">The low index to use in the training data.</param> /// <param name="theHigh">The high index to use in the training data.</param> /// <param name="theFlatSpots">Holds an array of flat spot constants.</param> public GradientWorker(FlatNetwork theNetwork, Propagation theOwner, IMLDataSet theTraining, int theLow, int theHigh, double[] theFlatSpots, IErrorFunction ef) { _errorCalculation = new ErrorCalculation(); _network = theNetwork; _training = theTraining; _low = theLow; _high = theHigh; _owner = theOwner; _flatSpot = theFlatSpots; _layerDelta = new double[_network.LayerOutput.Length]; _gradients = new double[_network.Weights.Length]; _actual = new double[_network.OutputCount]; _weights = _network.Weights; _layerIndex = _network.LayerIndex; _layerCounts = _network.LayerCounts; _weightIndex = _network.WeightIndex; _layerOutput = _network.LayerOutput; _layerSums = _network.LayerSums; _layerFeedCounts = _network.LayerFeedCounts; _ef = ef; } #region FlatGradientWorker Members /// <inheritdoc/> public FlatNetwork Network { get { return _network; } } /// <value>The weights for this network.</value> public double[] Weights { get { return _weights; } } /// <summary> /// Perform the gradient calculation for the specified index range. /// </summary> /// public void Run() { try { _errorCalculation.Reset(); for (int i = _low; i <= _high; i++) { var pair = _training[i]; Process(pair); } double error = _errorCalculation.Calculate(); _owner.Report(_gradients, error, null); EngineArray.Fill(_gradients, 0); } catch (Exception ex) { _owner.Report(null, 0, ex); } } #endregion /// <summary> /// Process one training set element. /// </summary> /// /// <param name="input">The network input.</param> /// <param name="ideal">The ideal values.</param> /// <param name="s">The significance of this error.</param> private void Process(IMLDataPair pair) { _network.Compute(pair.Input, _actual); _errorCalculation.UpdateError(_actual, pair.Ideal, pair.Significance); _ef.CalculateError(pair.Ideal,_actual,_layerDelta); for (int i = 0; i < _actual.Length; i++) { _layerDelta[i] = (_network.ActivationFunctions[0] .DerivativeFunction(_layerSums[i],_layerOutput[i])+_flatSpot[0]) *_layerDelta[i] * pair.Significance; } for (int i = _network.BeginTraining; i < _network.EndTraining; i++) { ProcessLevel(i); } } /// <summary> /// The error calculation to use. /// </summary> public ErrorCalculation CalculateError { get { return _errorCalculation; }} public void Run(int index) { IMLDataPair pair = _training[index]; Process(pair); _owner.Report(_gradients, 0, null); EngineArray.Fill(_gradients, 0); } /// <summary> /// Process one level. /// </summary> /// /// <param name="currentLevel">The level.</param> private void ProcessLevel(int currentLevel) { int fromLayerIndex = _layerIndex[currentLevel + 1]; int toLayerIndex = _layerIndex[currentLevel]; int fromLayerSize = _layerCounts[currentLevel + 1]; int toLayerSize = _layerFeedCounts[currentLevel]; int index = _weightIndex[currentLevel]; IActivationFunction activation = _network.ActivationFunctions[currentLevel + 1]; double currentFlatSpot = _flatSpot[currentLevel + 1]; // handle weights int yi = fromLayerIndex; for (int y = 0; y < fromLayerSize; y++) { double output = _layerOutput[yi]; double sum = 0; int xi = toLayerIndex; int wi = index + y; for (int x = 0; x < toLayerSize; x++) { _gradients[wi] += output*_layerDelta[xi]; sum += _weights[wi]*_layerDelta[xi]; wi += fromLayerSize; xi++; } _layerDelta[yi] = sum *(activation.DerivativeFunction(_layerSums[yi],_layerOutput[yi])+currentFlatSpot); yi++; } } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Transports { using System; using System.Threading; using System.Threading.Tasks; using Context; using Pipeline; using Util; public class PublishEndpoint : IPublishEndpoint { readonly IPublishEndpointProvider _endpointProvider; readonly IPublishObserver _publishObserver; readonly IPublishPipe _publishPipe; readonly Guid? _correlationId; readonly Guid? _conversationId; readonly Uri _sourceAddress; public PublishEndpoint(Uri sourceAddress, IPublishEndpointProvider endpointProvider, IPublishObserver publishObserver, IPublishPipe publishPipe, Guid? correlationId, Guid? conversationId) { _sourceAddress = sourceAddress; _endpointProvider = endpointProvider; _publishObserver = publishObserver; _publishPipe = publishPipe; _correlationId = correlationId; _conversationId = conversationId; } async Task IPublishEndpoint.Publish<T>(T message, CancellationToken cancellationToken) { var adapter = new PublishPipeContextAdapter<T>(_publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } async Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) { var adapter = new PublishPipeContextAdapter<T>(publishPipe, _publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } async Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { var adapter = new PublishPipeContextAdapter<T>(publishPipe, _publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } Task IPublishEndpoint.Publish(object message, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); Type messageType = message.GetType(); return PublishEndpointConverterCache.Publish(this, message, messageType, cancellationToken); } Task IPublishEndpoint.Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); Type messageType = message.GetType(); return PublishEndpointConverterCache.Publish(this, message, messageType, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish(object message, Type messageType, CancellationToken cancellationToken) { return PublishEndpointConverterCache.Publish(this, message, messageType, cancellationToken); } Task IPublishEndpoint.Publish(object message, Type messageType, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { return PublishEndpointConverterCache.Publish(this, message, messageType, publishPipe, cancellationToken); } async Task IPublishEndpoint.Publish<T>(object values, CancellationToken cancellationToken) { if (values == null) throw new ArgumentNullException(nameof(values)); var message = TypeMetadataCache<T>.InitializeFromObject(values); var adapter = new PublishPipeContextAdapter<T>(_publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } async Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) { if (values == null) throw new ArgumentNullException(nameof(values)); var message = TypeMetadataCache<T>.InitializeFromObject(values); var adapter = new PublishPipeContextAdapter<T>(publishPipe, _publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } async Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { if (values == null) throw new ArgumentNullException(nameof(values)); var message = TypeMetadataCache<T>.InitializeFromObject(values); var adapter = new PublishPipeContextAdapter<T>(publishPipe, _publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message); try { var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false); await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false); await adapter.PostPublish().ConfigureAwait(false); } catch (Exception ex) { await adapter.PublishFaulted(ex).ConfigureAwait(false); throw; } } public ConnectHandle ConnectPublishObserver(IPublishObserver observer) { return _endpointProvider.ConnectPublishObserver(observer); } } }
// 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.ComponentModel; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Identity { /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role.</typeparam> /// <typeparam name="TKey">The type of the primary key for a role.</typeparam> /// <typeparam name="TUserRole">The type of the class representing a user role.</typeparam> /// <typeparam name="TRoleClaim">The type of the class representing a role claim.</typeparam> public abstract class RoleStoreBase<TRole, TKey, TUserRole, TRoleClaim> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> where TUserRole : IdentityUserRole<TKey>, new() where TRoleClaim : IdentityRoleClaim<TKey>, new() { /// <summary> /// Constructs a new instance of <see cref="RoleStoreBase{TRole, TKey, TUserRole, TRoleClaim}"/>. /// </summary> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStoreBase(IdentityErrorDescriber describer) { if (describer == null) { throw new ArgumentNullException(nameof(describer)); } ErrorDescriber = describer; } private bool _disposed; /// <summary> /// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation. /// </summary> public IdentityErrorDescriber ErrorDescriber { get; set; } /// <summary> /// Creates a new role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to create in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to update in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role to delete from the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the ID for a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose ID should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the ID of the role.</returns> public virtual Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(ConvertIdToString(role.Id)); } /// <summary> /// Gets the name of a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.Name); } /// <summary> /// Sets the name of a role in the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be set.</param> /// <param name="roleName">The name of the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.Name = roleName; return Task.CompletedTask; } /// <summary> /// Converts the provided <paramref name="id"/> to a strongly typed key object. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An instance of <typeparamref name="TKey"/> representing the provided <paramref name="id"/>.</returns> public virtual TKey ConvertIdFromString(string id) { if (id == null) { return default(TKey); } return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id); } /// <summary> /// Converts the provided <paramref name="id"/> to its string representation. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An <see cref="string"/> representation of the provided <paramref name="id"/>.</returns> public virtual string ConvertIdToString(TKey id) { if (id.Equals(default(TKey))) { return null; } return id.ToString(); } /// <summary> /// Finds the role who has the specified ID as an asynchronous operation. /// </summary> /// <param name="id">The role ID to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public abstract Task<TRole> FindByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds the role who has the specified normalized name as an asynchronous operation. /// </summary> /// <param name="normalizedName">The normalized role name to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public abstract Task<TRole> FindByNameAsync(string normalizedName, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetNormalizedRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.NormalizedName); } /// <summary> /// Set a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be set.</param> /// <param name="normalizedName">The normalized name to set</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetNormalizedRoleNameAsync(TRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.NormalizedName = normalizedName; return Task.CompletedTask; } /// <summary> /// Throws if this class has been disposed. /// </summary> protected void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } /// <summary> /// Dispose the stores /// </summary> public void Dispose() => _disposed = true; /// <summary> /// Get the claims associated with the specified <paramref name="role"/> as an asynchronous operation. /// </summary> /// <param name="role">The role whose claims should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a role.</returns> public abstract Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to add the claim to.</param> /// <param name="claim">The claim to add to the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public abstract Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to remove the claim from.</param> /// <param name="claim">The claim to remove from the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public abstract Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A navigation property for the roles the store contains. /// </summary> public abstract IQueryable<TRole> Roles { get; } /// <summary> /// Creates a entity representing a role claim. /// </summary> /// <param name="role">The associated role.</param> /// <param name="claim">The associated claim.</param> /// <returns>The role claim entity.</returns> protected virtual TRoleClaim CreateRoleClaim(TRole role, Claim claim) => new TRoleClaim { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; } }
// // XmlDsigXPathTransformTest.cs - Test Cases for XmlDsigXPathTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigXPathTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigXPathTransform : XmlDsigXPathTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigXPathTransformTest { protected UnprotectedXmlDsigXPathTransform transform; public XmlDsigXPathTransformTest() { transform = new UnprotectedXmlDsigXPathTransform(); } [Fact] public void Properties() { Assert.Equal("http://www.w3.org/TR/1999/REC-xpath-19991116", transform.Algorithm); Type[] input = transform.InputTypes; Assert.True((input.Length == 3), "Input #"); // check presence of every supported input types bool istream = false; bool ixmldoc = false; bool ixmlnl = false; foreach (Type t in input) { if (t.ToString() == "System.IO.Stream") istream = true; if (t.ToString() == "System.Xml.XmlDocument") ixmldoc = true; if (t.ToString() == "System.Xml.XmlNodeList") ixmlnl = true; } Assert.True(istream, "Input Stream"); Assert.True(ixmldoc, "Input XmlDocument"); Assert.True(ixmlnl, "Input XmlNodeList"); Type[] output = transform.OutputTypes; Assert.True((output.Length == 1), "Output #"); // check presence of every supported output types bool oxmlnl = false; foreach (Type t in output) { if (t.ToString() == "System.Xml.XmlNodeList") oxmlnl = true; } Assert.True(oxmlnl, "Output XmlNodeList"); } protected void AreEqual(string msg, XmlNodeList expected, XmlNodeList actual) { for (int i = 0; i < expected.Count; i++) { Assert.Equal(expected[i].OuterXml, actual[i].OuterXml); } Assert.Equal(expected.Count, actual.Count); } [Fact] public void GetInnerXml() { XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Equal(1, xnl.Count); Assert.Equal("<XPath xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", xnl[0].OuterXml); } [Fact] public void OnlyInner() { XmlNodeList inner = InnerXml(""); // empty transform.LoadInnerXml(inner); XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(0, xnl.Count); } private XmlDocument GetDoc() { string test = "<catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><price>10.90</price>"; test += "<year>1985</year></cd><cd><title>Hide your heart</title><artist>Bonnie Tyler</artist><price>9.90</price>"; test += "<year>1988</year></cd><cd><title>Greatest Hits</title><artist>Dolly Parton</artist><price>9.90</price>"; test += "<year>1982</year></cd><cd><title>Still got the blues</title><artist>Gary Moore</artist><price>10.20</price>"; test += "<year>1990</year></cd><cd><title>Eros</title><artist>Eros Ramazzotti</artist><price>9.90</price>"; test += "<year>1997</year></cd></catalog>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); return doc; } private XmlNodeList InnerXml(string xpathExpr) { string xpath = "<XPath xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + xpathExpr + "</XPath>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xpath); return doc.ChildNodes; } [Fact] public void LoadInputAsXmlDocument() { XmlDocument doc = GetDoc(); transform.LoadInput(doc); XmlNodeList inner = InnerXml("//*/title"); transform.LoadInnerXml(inner); XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(73, xnl.Count); } [Fact] public void LoadInputAsXmlDocument_EmptyXPath() { XmlDocument doc = GetDoc(); transform.LoadInput(doc); // empty means no LoadInnerXml XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(0, xnl.Count); } [Fact] public void LoadInputAsXmlNodeList() { XmlDocument doc = GetDoc(); transform.LoadInput(doc.ChildNodes); XmlNodeList inner = InnerXml("//*/title"); transform.LoadInnerXml(inner); XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(1, xnl.Count); } [Fact] public void LoadInputAsXmlNodeList_EmptyXPath() { XmlDocument doc = GetDoc(); transform.LoadInput(doc.ChildNodes); // empty means no LoadInnerXml XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(0, xnl.Count); } [Fact] public void LoadInputAsStream() { XmlDocument doc = GetDoc(); doc.PreserveWhitespace = true; MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; transform.LoadInput(ms); XmlNodeList inner = InnerXml("//*/title"); transform.LoadInnerXml(inner); XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(73, xnl.Count); } [Fact] public void LoadInputAsStream_EmptyXPath() { XmlDocument doc = GetDoc(); MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; transform.LoadInput(ms); // empty means no LoadInnerXml XmlNodeList xnl = (XmlNodeList)transform.GetOutput(); Assert.Equal(0, xnl.Count); } [Fact] public void LoadInnerXml() { XmlNodeList inner = InnerXml("//*"); transform.LoadInnerXml(inner); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Equal(inner, xnl); } [Fact] public void UnsupportedInput() { byte[] bad = { 0xBA, 0xD }; // LAMESPEC: input MUST be one of InputType - but no exception is thrown (not documented) transform.LoadInput(bad); } [Fact] public void UnsupportedOutput() { XmlDocument doc = new XmlDocument(); Assert.Throws<ArgumentException>(() => transform.GetOutput(doc.GetType())); } [Fact] public void TransformSimple() { XmlDsigXPathTransform t = new XmlDsigXPathTransform(); XmlDocument xpdoc = new XmlDocument(); string ns = "http://www.w3.org/2000/09/xmldsig#"; string xpath = "<XPath xmlns='" + ns + "' xmlns:x='urn:foo'>*|@*|namespace::*</XPath>"; // not absolute path.. so @* and namespace::* does not make sense. xpdoc.LoadXml(xpath); t.LoadInnerXml(xpdoc.ChildNodes); XmlDocument doc = new XmlDocument(); doc.LoadXml("<element xmlns='urn:foo'><foo><bar>test</bar></foo></element>"); t.LoadInput(doc); XmlNodeList nl = (XmlNodeList)t.GetOutput(); Assert.Equal(XmlNodeType.Document, nl[0].NodeType); Assert.Equal(XmlNodeType.Element, nl[1].NodeType); Assert.Equal("element", nl[1].LocalName); Assert.Equal(XmlNodeType.Element, nl[2].NodeType); Assert.Equal("foo", nl[2].LocalName); Assert.Equal(XmlNodeType.Element, nl[3].NodeType); Assert.Equal("bar", nl[3].LocalName); // MS.NET bug - ms.net returns ns node even when the // current node is ns node (it is like returning // attribute from attribute nodes). // Assert.Equal (XmlNodeType.Attribute, nl [4].NodeType); // Assert.Equal ("xmlns", nl [4].LocalName); } [Fact] // MS.NET looks incorrect, or something incorrect in this test code; It turned out nothing to do with function here() public void FunctionHereObsolete() { XmlDsigXPathTransform t = new XmlDsigXPathTransform(); XmlDocument xpdoc = new XmlDocument(); string ns = "http://www.w3.org/2000/09/xmldsig#"; // string xpath = "<XPath xmlns='" + ns + "' xmlns:x='urn:foo'>here()</XPath>"; string xpath = "<XPath xmlns='" + ns + "' xmlns:x='urn:foo'></XPath>"; xpdoc.LoadXml(xpath); t.LoadInnerXml(xpdoc.ChildNodes); XmlDocument doc = new XmlDocument(); doc.LoadXml("<element a='b'><foo><bar>test</bar></foo></element>"); t.LoadInput(doc); XmlNodeList nl = (XmlNodeList)t.GetOutput(); Assert.Equal(0, nl.Count); doc.LoadXml("<element xmlns='urn:foo'><foo><bar>test</bar></foo></element>"); t.LoadInput(doc); nl = (XmlNodeList)t.GetOutput(); Assert.Equal(0, nl.Count); doc.LoadXml("<element xmlns='urn:foo'><foo xmlns='urn:bar'><bar>test</bar></foo></element>"); t.LoadInput(doc); nl = (XmlNodeList)t.GetOutput(); Assert.Equal(0, nl.Count); doc.LoadXml("<element xmlns='urn:foo' xmlns:x='urn:x'><foo xmlns='urn:bar'><bar>test</bar></foo></element>"); t.LoadInput(doc); nl = (XmlNodeList)t.GetOutput(); Assert.Equal(0, nl.Count); doc.LoadXml("<envelope><Signature xmlns='http://www.w3.org/2000/09/xmldsig#'><XPath>blah</XPath></Signature></envelope>"); t.LoadInput(doc); nl = (XmlNodeList)t.GetOutput(); Assert.Equal(0, nl.Count); } } }
// // PricingController.cs // // Author: // Eddy Zavaleta <eddy@mictlanix.com> // // Copyright (C) 2011-2016 Eddy Zavaleta, Mictlanix, and contributors. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Castle.ActiveRecord; using Mictlanix.BE.Model; using Mictlanix.BE.Web.Models; using Mictlanix.BE.Web.Mvc; using Mictlanix.BE.Web.Helpers; using Newtonsoft.Json; namespace Mictlanix.BE.Web.Controllers.Mvc { [Authorize] public class PricingController : CustomController { public ActionResult Index () { var qry = from x in Product.Queryable orderby x.Name select x; var search = new Search<Product> (); search.Limit = WebConfig.PageSize; search.Results = qry.Skip (search.Offset).Take (search.Limit).ToList (); search.Total = qry.Count (); var list = PriceList.Queryable.ToList (); if (!CurrentUser.IsInRole ("PriceLists.Update")) { list.Remove (list.Single (x => x.Id == 0)); } ViewBag.PriceLists = list; return View (search); } [HttpPost] public ActionResult Index (Search<Product> search) { if (!ModelState.IsValid) return View (search); var qry = from x in Product.Queryable orderby x.Name select x; if (!string.IsNullOrEmpty (search.Pattern)) { qry = from x in Product.Queryable where x.Name.Contains (search.Pattern) || x.Code.Contains (search.Pattern) || x.Model.Contains (search.Pattern) || x.SKU.Contains (search.Pattern) || x.Brand.Contains (search.Pattern) orderby x.Name select x; } search.Total = qry.Count (); search.Results = qry.Skip (search.Offset).Take (search.Limit).ToList (); ViewBag.PriceLists = PriceList.Queryable.ToList (); return PartialView ("_Index", search); } [HttpPost] public JsonResult SetPrice (int product, int list, string value) { decimal val; bool success; var p = Product.TryFind (product); var l = PriceList.TryFind (list); var item = ProductPrice.Queryable.SingleOrDefault (x => x.Product.Id == product && x.List.Id == list); if (item == null) { item = new ProductPrice { Product = p, List = l }; } success = decimal.TryParse (value.Trim (), System.Globalization.NumberStyles.Currency, null, out val); if (success && val >= 0) { item.Value = val; using (var scope = new TransactionScope ()) { item.SaveAndFlush (); } } return Json (new { id = item.Id, value = item.FormattedValueFor (x => x.Value) }); } [HttpPost] public JsonResult SetCurrency (int id, string value) { bool success; CurrencyCode val; var item = Product.TryFind (id); success = Enum.TryParse<CurrencyCode> (value.Trim (), out val); if (success && val >= 0) { item.Currency = val; using (var scope = new TransactionScope ()) { item.SaveAndFlush (); } } return Json (new { id = item.Id, value = item.Currency.ToString () }); } [HttpPost] public JsonResult SetMOQ (int id, decimal value) { var entity = Product.Find (id); if (value > 0) { entity.MinimumOrderQuantity = value; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.FormattedValueFor (x => x.MinimumOrderQuantity) }); } [HttpPost] public JsonResult SetTaxRate (int id, decimal value) { var entity = Product.Find (id); entity.TaxRate = value; entity.IsTaxIncluded = WebConfig.IsTaxIncluded; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, value = entity.FormattedValueFor (x => x.TaxRate) }); } [HttpPost] public JsonResult SetPriceType (int id, string value) { bool success; PriceType val; var item = Product.Find (id); success = Enum.TryParse<PriceType> (value.Trim (), out val); if (success && val >= 0) { item.PriceType = val; using (var scope = new TransactionScope ()) { item.UpdateAndFlush (); } } return Json (new { id = id, value = item.PriceType.GetDisplayName () }); } [HttpPost] public ActionResult ToogleTaxIncluded (int id) { var item = Product.Find (id); if (item == null) { Response.StatusCode = 400; return Content (Resources.ItemNotFound); } item.IsTaxIncluded = !item.IsTaxIncluded; using (var scope = new TransactionScope ()) { item.UpdateAndFlush (); } return PartialView ("_IsTaxIncluded", item); } public JsonResult PriceTypes () { var qry = from x in Enum.GetValues (typeof (PriceType)).Cast<PriceType> () select new { value = (int) x, text = x.GetDisplayName () }; return Json (qry.ToList (), JsonRequestBehavior.AllowGet); } public JsonResult TaxRates () { var rates = from x in WebConfig.TaxRates select new { value = x.Value, text = x.Key }; return Json (rates, JsonRequestBehavior.AllowGet); } public JsonResult RetentionRates () { var rates = from x in WebConfig.RetentionRates select new { value = x.Value, text = x.Key }; return Json (rates, JsonRequestBehavior.AllowGet); } public JsonResult LocalRetentionRates () { var rates = from x in WebConfig.LocalRetentionRates select new { value = x.Value, text = x.Key }; return Json (rates, JsonRequestBehavior.AllowGet); } } }
/* The MIT License (MIT) Copyright (c) 2014 Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Threading; namespace COST { public static class UnbufferedIO { public class SequentialWriter<T> : IDisposable { readonly string filename; // name of target file FileStream target; // file stream used for writing readonly byte[] buffer; // buffer for async writes readonly IAsyncResult[] results; // stores async write results readonly int bufferSize = 1 << 20; // number of bytes per write int currentIO = 0; // number of block writes done readonly T[] typedBuffer; // staging area for block writes int offset = 0; // position in the current buffer public void Write(T data) { typedBuffer[offset++] = data; if (offset == typedBuffer.Length) { this.Write(typedBuffer); offset = 0; } } public void Write(T[] data) { if (results[(currentIO % results.Length)] != null) target.EndWrite(results[(currentIO % results.Length)]); System.Buffer.BlockCopy(data, 0, buffer, bufferSize * (currentIO % results.Length), bufferSize); results[(currentIO % results.Length)] = target.BeginWrite(buffer, bufferSize * (currentIO % results.Length), bufferSize, null, null); currentIO++; } public void Close() { for (int i = 0; i < results.Length; i++) if (results[i] != null) target.EndWrite(results[i]); target.Flush(); target.Close(); target = null; System.Buffer.BlockCopy(typedBuffer, 0, buffer, 0, offset * 4); using (var file = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None)) file.Write(buffer, 0, offset * 4); } public void Dispose() { if (target != null) Close(); } public SequentialWriter(string filename, long expectedSize = 0) { this.filename = filename; // append not yet supported if (File.Exists(filename)) File.Delete(filename); target = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.WriteThrough); // | (FileOptions)0x20000000 results = new IAsyncResult[4]; buffer = new byte[results.Length * bufferSize]; typedBuffer = new T[bufferSize / System.Runtime.InteropServices.Marshal.SizeOf(typeof(T))]; } } public class SequentialReader<T> : IDisposable { public readonly long fileLength; // file length in bytes public readonly string filename; // name of source file readonly byte[] buffer; // buffers for async reads readonly int requestLength; // number of bytes per read readonly IAsyncResult[] results; // results of async reads readonly int typeSize; FileStream source; // source file stream int currentIO; // numbef of block reads readonly T[][] typedBuffers; AutoResetEvent[] waitEvents; public void EndRead(int index, IAsyncResult result) { if (source != null) { var read = source.EndRead(result); System.Buffer.BlockCopy(buffer, requestLength * index, typedBuffers[index], 0, read); waitEvents[index].Set(); } } public int Read(ref T[] dest) { if (dest == null || dest.Length != requestLength / this.typeSize) dest = new T[requestLength / this.typeSize]; // if we have a full block to read in ... if (currentIO < fileLength / requestLength) { var index = currentIO % results.Length; waitEvents[index].WaitOne(); var temp = typedBuffers[index]; typedBuffers[index] = dest; dest = temp; if (((long)requestLength * (currentIO + results.Length + 1)) <= fileLength) source.BeginRead(buffer, requestLength * index, requestLength, x => this.EndRead(index, x), null); currentIO++; return dest.Length; } else if (currentIO <= fileLength / requestLength) { source.Close(); source = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); source.Seek(-(fileLength % requestLength), SeekOrigin.End); var read = source.Read(buffer, 0, (int)(fileLength % requestLength)); dest = new T[read / System.Runtime.InteropServices.Marshal.SizeOf(typeof(T))]; System.Buffer.BlockCopy(buffer, 0, dest, 0, read); source.Close(); source = null; currentIO++; return read / System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); } else return 0; } public void Dispose() { for (int i = 0; i < results.Length; i++) if (results[i] != null && !results[i].IsCompleted) waitEvents[i].WaitOne(); if (source != null) { source.Close(); source = null; } } public SequentialReader(string filename, int depth = 4) { this.filename = filename; source = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.WriteThrough | (FileOptions)0x20000000); results = new IAsyncResult[depth]; requestLength = 1 << 20; buffer = new byte[depth * requestLength]; this.typeSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); typedBuffers = new T[depth][]; for (int i = 0; i < typedBuffers.Length; i++) typedBuffers[i] = new T[requestLength / this.typeSize]; waitEvents = new AutoResetEvent[depth]; for (int i = 0; i < waitEvents.Length; i++) waitEvents[i] = new AutoResetEvent(false); fileLength = source.Length; for (int i = 0; i < results.Length; i++) { var index = i; if (i < fileLength / requestLength) source.BeginRead(buffer, requestLength * i, requestLength, x => this.EndRead(index, x), null); } } public static IEnumerable<T> Enumerate(string filename) { var readBuffer = new T[] { }; using (var reader = new SequentialReader<T>(filename)) { while (reader.Read(ref readBuffer) > 0) for (int i = 0; i < readBuffer.Length; i++) yield return readBuffer[i]; } } public static IEnumerable<T[]> EnumerateArrays(string filename) { var readBuffer = new T[] { }; using (var reader = new SequentialReader<T>(filename)) { while (reader.Read(ref readBuffer) > 0) yield return readBuffer; } } } public class SequentialReader : IDisposable { public readonly long Length; // file length in bytes public readonly string filename; // name of source file private readonly byte[] buffer; // buffers for async reads private readonly int requestLength; // number of bytes per read private readonly IAsyncResult[] results; // results of async reads private readonly FileStream source; // source file stream private long position; public int Read<T>(T[] dest, int offset, int length) { var copied = 0; while (copied < length && this.position != this.Length) { var typeSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); // only snag as many records as are valid, and needed. var toCopy = length - copied; // if we would read over the segment boundary, limit read. if (toCopy > (this.requestLength - (this.position % this.requestLength)) / typeSize) toCopy = (int)(this.requestLength - (this.position % this.requestLength)) / typeSize; // if we would read past the end of file, don't. if (toCopy > (this.Length - this.position) / typeSize) toCopy = (int)(this.Length - this.position) / typeSize; Buffer.BlockCopy(this.buffer, (int)(this.position % this.buffer.Length), dest, typeSize * (offset + copied), typeSize * toCopy); copied += toCopy; this.position += typeSize * toCopy; // we may have emptied a hunk of data, and should start the next if ((this.position % this.requestLength) == 0) { var offsetToRead = this.position + this.buffer.Length - this.requestLength; // initiate new read request, only if there is a full valid page! if (offsetToRead / this.requestLength < this.Length / this.requestLength) { var nextReadPosition = (int)((this.position + this.buffer.Length - this.requestLength) % this.buffer.Length); results[nextReadPosition / this.requestLength] = source.BeginRead(this.buffer, nextReadPosition, this.requestLength, null, null); } // validate the forthcoming data if (this.Length - this.position < this.requestLength) { this.source.Close(); using (var finalSource = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { finalSource.Seek(-(Length % requestLength), SeekOrigin.End); finalSource.Read(buffer, (int)((this.position) % this.buffer.Length), (int)(Length % requestLength)); } } else if (!results[(position % this.buffer.Length) / this.requestLength].IsCompleted) source.EndRead(results[(position % this.buffer.Length) / this.requestLength]); } } return copied; } public void Dispose() { for (int i = 0; i < this.results.Length; i++) if (this.results[i] != null && !this.results[i].IsCompleted) this.results[i].AsyncWaitHandle.WaitOne(); if (source != null) { source.Close(); } } public SequentialReader(string filename) : this(filename, 4) { } public SequentialReader(string filename, int depth) { this.filename = filename; var options = FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.WriteThrough | (FileOptions)0x20000000; this.source = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite, 8, options); this.results = new IAsyncResult[depth]; this.requestLength = 1 << 24; this.buffer = new byte[depth * this.requestLength]; this.Length = source.Length; for (int i = 0; i < this.results.Length; i++) { var readPosition = i * this.requestLength; if (readPosition / this.requestLength < this.Length / this.requestLength) this.results[i] = this.source.BeginRead(this.buffer, readPosition, this.requestLength, null, null); } if (this.results[0] == null) { this.source.Close(); using (var finalSource = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { finalSource.Seek(-(Length % requestLength), SeekOrigin.End); finalSource.Read(buffer, 0, (int)(Length % requestLength)); } } else if (!this.results[0].IsCompleted) this.source.EndRead(this.results[0]); } } public static T[] ReadFile<T>(string filename) { using (var reader = new UnbufferedIO.SequentialReader(filename)) { var result = new T[reader.Length / System.Runtime.InteropServices.Marshal.SizeOf(typeof(T))]; // if the thing to read is bigger than 2GB, Buffer.BlockCopy will choke (yay 32 bits) if (((Int64)result.Length) * System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) > Int32.MaxValue) { var intermediate = new T[1 << 20]; var cursor = 0; while (reader.Read(intermediate, 0, intermediate.Length) > 0) { Array.Copy(intermediate, 0, result, cursor, Math.Min(intermediate.Length, result.Length - cursor)); cursor += intermediate.Length; } } else reader.Read(result, 0, result.Length); return result; } } } }
using System; using System.Threading; namespace Alachisoft.NCache.Common.Threading { /// <remarks> /// The scheduler supports varying scheduling intervals by asking the task /// every time for its next preferred scheduling interval. Scheduling can /// either be <i>fixed-delay</i> or <i>fixed-rate</i>. /// In fixed-delay scheduling, the task's new schedule is calculated /// as:<br></br> /// new_schedule = time_task_starts + scheduling_interval /// <p> /// In fixed-rate scheduling, the next schedule is calculated as:<br></br> /// new_schedule = time_task_was_supposed_to_start + scheduling_interval</p> /// <p> /// The scheduler internally holds a queue of tasks sorted in ascending order /// according to their next execution time. A task is removed from the queue /// if it is cancelled, i.e. if <tt>TimeScheduler.Task.isCancelled()</tt> /// returns true. /// </p> /// <p> /// Initially, the scheduler is in <tt>SUSPEND</tt>ed mode, <tt>start()</tt> /// need not be called: if a task is added, the scheduler gets started /// automatically. Calling <tt>start()</tt> starts the scheduler if it's /// suspended or stopped else has no effect. Once <tt>stop()</tt> is called, /// added tasks will not restart it: <tt>start()</tt> has to be called to /// restart the scheduler. /// </p> /// </remarks> /// <summary> /// Fixed-delay and fixed-rate single thread scheduler /// <p><b>Author:</b> Chris Koiak, Bela Ban</p> /// <p><b>Date:</b> 12/03/2003</p> /// </summary> public class TimeScheduler: IDisposable { /// <summary> /// The interface that submitted tasks must implement /// </summary> public interface Task { /// <summary> /// Returns true if task is cancelled and shouldn't be scheduled again /// </summary> /// <returns></returns> bool IsCancelled(); /// <summary> /// The next schedule interval /// </summary> /// <returns>The next schedule interval</returns> long GetNextInterval(); /// <summary> /// Execute the task /// </summary> void Run(); } /// <remarks> /// Needed in case all tasks have been /// cancelled and we are still waiting on the schedule time of the task /// at the top /// </remarks> /// <summary>Regular wake-up intervals for scheduler</summary> private const long TICK_INTERVAL = 1000; enum State { /// <summary>State Constant</summary> RUN = 0, /// <summary>State Constant</summary> SUSPEND = 1, /// <summary>State Constant</summary> STOPPING = 2, /// <summary>State Constant</summary> STOP = 3, /// <summary>State Constant</summary> DISPOSED = 4 } /// <summary>TimeScheduler thread name</summary> private const String THREAD_NAME = "TimeScheduler.Thread"; /// <summary>The scheduler thread</summary> private Thread thread = null; /// <summary>The thread's running state</summary> private State thread_state = State.SUSPEND; /// <summary>Time that task queue is empty before suspending the scheduling thread</summary> private long suspend_interval; /// <summary>Sorted list of <code>IntTask</code>s </summary> private EventQueue queue; bool _concurrent; public int QueueCount { get { if (queue == null) return 0; return queue.Count; } } /// <summary> /// Set the thread state to running, create and start the thread /// </summary> private void _start() { lock(this) { if(thread_state != State.DISPOSED) { thread_state = State.RUN; thread = new Thread(new ThreadStart(_run)); thread.Name = THREAD_NAME; thread.IsBackground = true; thread.Start(); } } } /// <summary> /// Restart the suspended thread /// </summary> private void _unsuspend() { _start(); } /// <summary> /// Set the thread state to suspended /// </summary> private void _suspend() { lock(this) { if(thread_state != State.DISPOSED) { thread_state = State.SUSPEND; thread = null; } } } /// <summary> /// Set the thread state to stopping /// </summary> private void _stopping() { lock(this) { if(thread_state != State.DISPOSED) { thread_state = State.STOPPING; } } } /// <summary> /// Set the thread state to stopped /// </summary> private void _stop() { lock(this) { if(thread_state != State.DISPOSED) { thread_state = State.STOP; thread = null; } } } /// <remarks> /// Get the first task, if the running time hasn't been /// reached then wait a bit and retry. Else reschedule the task and then /// run it. /// </remarks> /// <summary> /// If the task queue is empty, sleep until a task comes in or if slept /// for too long, suspend the thread. /// </summary> private void _run() { long elapsedTime; try { while(true) { lock(this) { if (thread == null) return; } Task task = null; bool lockReAcquired = true; lock(queue) { if(queue.IsEmpty) lockReAcquired = Monitor.Wait(queue, (int)suspend_interval); if (lockReAcquired) { QueuedEvent e = queue.Peek(); if (e != null) { lock (e) { long interval = e.Interval; task = e.Task; if (task.IsCancelled()) { queue.Pop(); continue; } elapsedTime = e.ElapsedTime; if (elapsedTime >= interval) { // Reschedule the task queue.Pop(); if (e.ReQueue()) { queue.Push(e); } } } if (elapsedTime < e.Interval) { Monitor.Wait(queue, (int)(e.Interval - elapsedTime)); continue; } } } } lock (this) { if (queue.IsEmpty && !lockReAcquired) { _suspend(); return; } } try { if (task != null) { if(_concurrent) ThreadPool.QueueUserWorkItem(ExecuterCallback, task); else task.Run(); } } catch(Exception ex) { Trace.error("TimeScheduler._run()", ex.ToString()); } } } catch(ThreadInterruptedException ex) { Trace.error("TimeScheduler._run()",ex.ToString()); } } private void ExecuterCallback(object state) { var task = state as Task; if (task != null) { task.Run(); } } /// <summary> /// Create a scheduler that executes tasks in dynamically adjustable /// intervals /// </summary> /// <param name="suspend_interval"> /// The time that the scheduler will wait for /// at least one task to be placed in the task queue before suspending /// the scheduling thread /// </param> public TimeScheduler(long suspend_interval) { queue = new EventQueue(); this.suspend_interval = suspend_interval; } /// <summary> /// Create a scheduler that executes tasks in dynamically adjustable /// intervals /// </summary> public TimeScheduler() : this(2000){} public TimeScheduler(bool concurrent): this(concurrent, 2000) { } public TimeScheduler(bool concurrent, long interval) : this(interval) { _concurrent = concurrent; } /// <remarks> /// <b>Relative Scheduling</b> /// <tt>true</tt>:<br></br> /// Task is rescheduled relative to the last time it <i>actually</i> /// started execution /// <p> /// <tt>false</tt>:<br></br> /// Task is scheduled relative to its <i>last</i> execution schedule. This /// has the effect that the time between two consecutive executions of /// the task remains the same. /// </p> /// </remarks> /// <summary> /// Add a task for execution at adjustable intervals /// </summary> /// <param name="t">The task to execute</param> /// <param name="relative">Use relative scheduling</param> public void AddTask(Task t, bool relative) { long interval; lock(this) { if(thread_state == State.DISPOSED) return; if((interval = t.GetNextInterval()) < 0) return; queue.Push(new QueuedEvent(t)); switch(thread_state) { case State.RUN: break; //Monitor.PulseAll(queue); case State.SUSPEND: _unsuspend(); break; case State.STOPPING: break; case State.STOP: break; } } } /// <summary> /// Add a task for execution at adjustable intervals /// </summary> /// <param name="t">The task to execute</param> public void AddTask(Task t) { AddTask(t, true); } /// <summary> /// Start the scheduler, if it's suspended or stopped /// </summary> public void Start() { lock(this) { switch(thread_state) { case State.DISPOSED: break; case State.RUN: break; case State.SUSPEND: _unsuspend(); break; case State.STOPPING: break; case State.STOP: _start(); break; } } } /// <summary> /// Stop the scheduler if it's running. Switch to stopped, if it's /// suspended. Clear the task queue. /// </summary> public void Stop() { // i. Switch to STOPPING, interrupt thread // ii. Wait until thread ends // iii. Clear the task queue, switch to STOPPED, lock(this) { switch(thread_state) { case State.RUN: _stopping(); break; case State.SUSPEND: _stop(); return; case State.STOPPING: return; case State.STOP: return; case State.DISPOSED: return; } thread.Interrupt(); } thread.Join(); lock(this) { queue.Clear(); _stop(); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> public virtual void Dispose() { Thread tmp = null; lock(this) { if(thread_state == State.DISPOSED) return; tmp = thread; thread_state = State.DISPOSED; thread = null; if(tmp != null) { tmp.Interrupt(); } } queue.Clear(); } } }
// 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.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // The class does the real work in authentication and // user data encryption with NEGO SSPI package. // // This is part of the NegotiateStream PAL. // internal static partial class NegotiateStreamPal { internal static int QueryMaxTokenSize(string package) { return SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; } internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer) { return SSPIWrapper.AcquireDefaultCredential( GlobalSSPI.SSPIAuth, package, (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND)); } internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential) { SafeSspiAuthDataHandle authData = null; try { Interop.SECURITY_STATUS result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity( credential.UserName, credential.Domain, credential.Password, out authData); if (result != Interop.SECURITY_STATUS.OK) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}")); throw new Win32Exception((int)result); } return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND), ref authData); } finally { authData?.Dispose(); } } internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) { return SSPIWrapper.QueryStringContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET); } internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext) { SecPkgContext_NegotiationInfoW ctx = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO, typeof(SafeFreeContextBuffer), out SafeHandle sspiHandle, ref ctx); using (sspiHandle) { return success ? NegotiationInfoClass.GetAuthenticationPackageName(sspiHandle, (int)ctx.NegotiationState) : null; } } internal static SecurityStatusPal InitializeSecurityContext( ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext securityContext, string spn, ContextFlagsPal requestedContextFlags, byte[] incomingBlob, ChannelBinding channelBinding, ref byte[] resultBlob, ref ContextFlagsPal contextFlags) { #if NETSTANDARD2_0 Span<SecurityBuffer> inSecurityBufferSpan = new SecurityBuffer[2]; #else TwoSecurityBuffers twoSecurityBuffers = default; Span<SecurityBuffer> inSecurityBufferSpan = MemoryMarshal.CreateSpan(ref twoSecurityBuffers._item0, 2); #endif int inSecurityBufferSpanLength = 0; if (incomingBlob != null && channelBinding != null) { inSecurityBufferSpan[0] = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); inSecurityBufferSpan[1] = new SecurityBuffer(channelBinding); inSecurityBufferSpanLength = 2; } else if (incomingBlob != null) { inSecurityBufferSpan[0] = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); inSecurityBufferSpanLength = 1; } else if (channelBinding != null) { inSecurityBufferSpan[0] = new SecurityBuffer(channelBinding); inSecurityBufferSpanLength = 1; } inSecurityBufferSpan = inSecurityBufferSpan.Slice(0, inSecurityBufferSpanLength); var outSecurityBuffer = new SecurityBuffer(resultBlob, SecurityBufferType.SECBUFFER_TOKEN); Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPIAuth, ref credentialsHandle, ref sslContext, spn, ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags), Interop.SspiCli.Endianness.SECURITY_NETWORK_DREP, inSecurityBufferSpan, ref outSecurityBuffer, ref outContextFlags); securityContext = sslContext; resultBlob = outSecurityBuffer.token; contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static SecurityStatusPal CompleteAuthToken( ref SafeDeleteContext securityContext, byte[] incomingBlob) { // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; var inSecurityBuffer = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.CompleteAuthToken( GlobalSSPI.SSPIAuth, ref sslContext, in inSecurityBuffer); securityContext = sslContext; return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static SecurityStatusPal AcceptSecurityContext( SafeFreeCredentials credentialsHandle, ref SafeDeleteContext securityContext, ContextFlagsPal requestedContextFlags, byte[] incomingBlob, ChannelBinding channelBinding, ref byte[] resultBlob, ref ContextFlagsPal contextFlags) { #if NETSTANDARD2_0 Span<SecurityBuffer> inSecurityBufferSpan = new SecurityBuffer[2]; #else TwoSecurityBuffers twoSecurityBuffers = default; Span<SecurityBuffer> inSecurityBufferSpan = MemoryMarshal.CreateSpan(ref twoSecurityBuffers._item0, 2); #endif int inSecurityBufferSpanLength = 0; if (incomingBlob != null && channelBinding != null) { inSecurityBufferSpan[0] = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); inSecurityBufferSpan[1] = new SecurityBuffer(channelBinding); inSecurityBufferSpanLength = 2; } else if (incomingBlob != null) { inSecurityBufferSpan[0] = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); inSecurityBufferSpanLength = 1; } else if (channelBinding != null) { inSecurityBufferSpan[0] = new SecurityBuffer(channelBinding); inSecurityBufferSpanLength = 1; } inSecurityBufferSpan = inSecurityBufferSpan.Slice(0, inSecurityBufferSpanLength); var outSecurityBuffer = new SecurityBuffer(resultBlob, SecurityBufferType.SECBUFFER_TOKEN); Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPIAuth, credentialsHandle, ref sslContext, ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags), Interop.SspiCli.Endianness.SECURITY_NETWORK_DREP, inSecurityBufferSpan, ref outSecurityBuffer, ref outContextFlags); resultBlob = outSecurityBuffer.token; securityContext = sslContext; contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode) { return new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(statusCode)); } internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count) { // validate offset within length if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { NetEventSource.Info("Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } // validate count within offset and end of buffer if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) { NetEventSource.Info("Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } // setup security buffers for ssp call // one points at signed data // two will receive payload if signature is valid #if NETSTANDARD2_0 Span<SecurityBuffer> securityBuffer = new SecurityBuffer[2]; #else TwoSecurityBuffers stackBuffer = default; Span<SecurityBuffer> securityBuffer = MemoryMarshal.CreateSpan(ref stackBuffer._item0, 2); #endif securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.SECBUFFER_STREAM); securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.SECBUFFER_DATA); // call SSP function int errorCode = SSPIWrapper.VerifySignature( GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { NetEventSource.Info($"VerifySignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); throw new Win32Exception(errorCode); } // not sure why this is here - retained from Encrypt code above if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA) throw new InternalException(securityBuffer[1].type); // return validated payload size return securityBuffer[1].size; } internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output) { SecPkgContext_Sizes sizes = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES, ref sizes); Debug.Assert(success); // alloc new output buffer if not supplied or too small int resultSize = count + sizes.cbMaxSignature; if (output == null || output.Length < resultSize) { output = new byte[resultSize]; } // make a copy of user data for in-place encryption Buffer.BlockCopy(buffer, offset, output, sizes.cbMaxSignature, count); // setup security buffers for ssp call #if NETSTANDARD2_0 Span<SecurityBuffer> securityBuffer = new SecurityBuffer[2]; #else TwoSecurityBuffers stackBuffer = default; Span<SecurityBuffer> securityBuffer = MemoryMarshal.CreateSpan(ref stackBuffer._item0, 2); #endif securityBuffer[0] = new SecurityBuffer(output, 0, sizes.cbMaxSignature, SecurityBufferType.SECBUFFER_TOKEN); securityBuffer[1] = new SecurityBuffer(output, sizes.cbMaxSignature, count, SecurityBufferType.SECBUFFER_DATA); // call SSP Function int errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { NetEventSource.Info($"MakeSignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); throw new Win32Exception(errorCode); } // return signed size return securityBuffer[0].size + securityBuffer[1].size; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Http { public partial class ByteArrayContent : System.Net.Http.HttpContent { public ByteArrayContent(byte[] content) { } public ByteArrayContent(byte[] content, int offset, int count) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); } protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); } } public enum ClientCertificateOption { Automatic = 1, Manual = 0, } public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler { protected DelegatingHandler() { } protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } public System.Net.Http.HttpMessageHandler InnerHandler { get { return default(System.Net.Http.HttpMessageHandler); } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } } public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent { public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base(default(byte[])) { } } public partial class HttpClient : System.Net.Http.HttpMessageInvoker { public HttpClient() : base(default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler) : base(default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base(default(System.Net.Http.HttpMessageHandler)) { } public System.Uri BaseAddress { get { return default(System.Uri); } set { } } public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { return default(System.Net.Http.Headers.HttpRequestHeaders); } } public long MaxResponseContentBufferSize { get { return default(long); } set { } } public System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } } public void CancelPendingRequests() { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } protected override void Dispose(bool disposing) { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { return default(System.Threading.Tasks.Task<byte[]>); } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<byte[]>); } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.IO.Stream>); } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.IO.Stream>); } public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { return default(System.Threading.Tasks.Task<string>); } public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<string>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } } public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler { public HttpClientHandler() { } public bool AllowAutoRedirect { get { return default(bool); } set { } } public System.Net.DecompressionMethods AutomaticDecompression { get { return default(System.Net.DecompressionMethods); } set { } } public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { return default(System.Net.Http.ClientCertificateOption); } set { } } public System.Net.CookieContainer CookieContainer { get { return default(System.Net.CookieContainer); } set { } } public System.Net.ICredentials Credentials { get { return default(System.Net.ICredentials); } set { } } public int MaxAutomaticRedirections { get { return default(int); } set { } } public long MaxRequestContentBufferSize { get { return default(long); } set { } } public bool PreAuthenticate { get { return default(bool); } set { } } public System.Net.IWebProxy Proxy { get { return default(System.Net.IWebProxy); } set { } } public virtual bool SupportsAutomaticDecompression { get { return default(bool); } } public virtual bool SupportsProxy { get { return default(bool); } } public virtual bool SupportsRedirectConfiguration { get { return default(bool); } } public bool UseCookies { get { return default(bool); } set { } } public bool UseDefaultCredentials { get { return default(bool); } set { } } public bool UseProxy { get { return default(bool); } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } } public enum HttpCompletionOption { ResponseContentRead = 0, ResponseHeadersRead = 1, } public abstract partial class HttpContent : System.IDisposable { protected HttpContent() { } public System.Net.Http.Headers.HttpContentHeaders Headers { get { return default(System.Net.Http.Headers.HttpContentHeaders); } } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); } protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Threading.Tasks.Task LoadIntoBufferAsync() { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { return default(System.Threading.Tasks.Task<byte[]>); } public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); } public System.Threading.Tasks.Task<string> ReadAsStringAsync() { return default(System.Threading.Tasks.Task<string>); } protected abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context); protected internal abstract bool TryComputeLength(out long length); } public abstract partial class HttpMessageHandler : System.IDisposable { protected HttpMessageHandler() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); } public partial class HttpMessageInvoker : System.IDisposable { public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { } public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } } public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod> { public HttpMethod(string method) { } public static System.Net.Http.HttpMethod Delete { get { return default(System.Net.Http.HttpMethod); } } public static System.Net.Http.HttpMethod Get { get { return default(System.Net.Http.HttpMethod); } } public static System.Net.Http.HttpMethod Head { get { return default(System.Net.Http.HttpMethod); } } public string Method { get { return default(string); } } public static System.Net.Http.HttpMethod Options { get { return default(System.Net.Http.HttpMethod); } } public static System.Net.Http.HttpMethod Post { get { return default(System.Net.Http.HttpMethod); } } public static System.Net.Http.HttpMethod Put { get { return default(System.Net.Http.HttpMethod); } } public static System.Net.Http.HttpMethod Trace { get { return default(System.Net.Http.HttpMethod); } } public bool Equals(System.Net.Http.HttpMethod other) { return default(bool); } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { return default(bool); } public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { return default(bool); } public override string ToString() { return default(string); } } public partial class HttpRequestException : System.Exception { public HttpRequestException() { } public HttpRequestException(string message) { } public HttpRequestException(string message, System.Exception inner) { } } public partial class HttpRequestMessage : System.IDisposable { public HttpRequestMessage() { } public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { } public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { } public System.Net.Http.HttpContent Content { get { return default(System.Net.Http.HttpContent); } set { } } public System.Net.Http.Headers.HttpRequestHeaders Headers { get { return default(System.Net.Http.Headers.HttpRequestHeaders); } } public System.Net.Http.HttpMethod Method { get { return default(System.Net.Http.HttpMethod); } set { } } public System.Collections.Generic.IDictionary<string, object> Properties { get { return default(System.Collections.Generic.IDictionary<string, object>); } } public System.Uri RequestUri { get { return default(System.Uri); } set { } } public System.Version Version { get { return default(System.Version); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override string ToString() { return default(string); } } public partial class HttpResponseMessage : System.IDisposable { public HttpResponseMessage() { } public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { } public System.Net.Http.HttpContent Content { get { return default(System.Net.Http.HttpContent); } set { } } public System.Net.Http.Headers.HttpResponseHeaders Headers { get { return default(System.Net.Http.Headers.HttpResponseHeaders); } } public bool IsSuccessStatusCode { get { return default(bool); } } public string ReasonPhrase { get { return default(string); } set { } } public System.Net.Http.HttpRequestMessage RequestMessage { get { return default(System.Net.Http.HttpRequestMessage); } set { } } public System.Net.HttpStatusCode StatusCode { get { return default(System.Net.HttpStatusCode); } set { } } public System.Version Version { get { return default(System.Version); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { return default(System.Net.Http.HttpResponseMessage); } public override string ToString() { return default(string); } } public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler { protected MessageProcessingHandler() { } protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken); protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); } } public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable { public MultipartContent() { } public MultipartContent(string subtype) { } public MultipartContent(string subtype, string boundary) { } public virtual void Add(System.Net.Http.HttpContent content) { } protected override void Dispose(bool disposing) { } public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent>); } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); } } public partial class MultipartFormDataContent : System.Net.Http.MultipartContent { public MultipartFormDataContent() { } public MultipartFormDataContent(string boundary) { } public override void Add(System.Net.Http.HttpContent content) { } public void Add(System.Net.Http.HttpContent content, string name) { } public void Add(System.Net.Http.HttpContent content, string name, string fileName) { } } public partial class StreamContent : System.Net.Http.HttpContent { public StreamContent(System.IO.Stream content) { } public StreamContent(System.IO.Stream content, int bufferSize) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); } protected override void Dispose(bool disposing) { } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); } protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); } } public partial class StringContent : System.Net.Http.ByteArrayContent { public StringContent(string content) : base(default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding) : base(default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base(default(byte[])) { } } } namespace System.Net.Http.Headers { public partial class AuthenticationHeaderValue { public AuthenticationHeaderValue(string scheme) { } public AuthenticationHeaderValue(string scheme, string parameter) { } public string Parameter { get { return default(string); } } public string Scheme { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { return default(System.Net.Http.Headers.AuthenticationHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.AuthenticationHeaderValue); return default(bool); } } public partial class CacheControlHeaderValue { public CacheControlHeaderValue() { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Extensions { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public System.Nullable<System.TimeSpan> MaxAge { get { return default(System.Nullable<System.TimeSpan>); } set { } } public bool MaxStale { get { return default(bool); } set { } } public System.Nullable<System.TimeSpan> MaxStaleLimit { get { return default(System.Nullable<System.TimeSpan>); } set { } } public System.Nullable<System.TimeSpan> MinFresh { get { return default(System.Nullable<System.TimeSpan>); } set { } } public bool MustRevalidate { get { return default(bool); } set { } } public bool NoCache { get { return default(bool); } set { } } public System.Collections.Generic.ICollection<string> NoCacheHeaders { get { return default(System.Collections.Generic.ICollection<string>); } } public bool NoStore { get { return default(bool); } set { } } public bool NoTransform { get { return default(bool); } set { } } public bool OnlyIfCached { get { return default(bool); } set { } } public bool Private { get { return default(bool); } set { } } public System.Collections.Generic.ICollection<string> PrivateHeaders { get { return default(System.Collections.Generic.ICollection<string>); } } public bool ProxyRevalidate { get { return default(bool); } set { } } public bool Public { get { return default(bool); } set { } } public System.Nullable<System.TimeSpan> SharedMaxAge { get { return default(System.Nullable<System.TimeSpan>); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { return default(System.Net.Http.Headers.CacheControlHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.CacheControlHeaderValue); return default(bool); } } public partial class ContentDispositionHeaderValue { protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source) { } public ContentDispositionHeaderValue(string dispositionType) { } public System.Nullable<System.DateTimeOffset> CreationDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public string DispositionType { get { return default(string); } set { } } public string FileName { get { return default(string); } set { } } public string FileNameStar { get { return default(string); } set { } } public System.Nullable<System.DateTimeOffset> ModificationDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public string Name { get { return default(string); } set { } } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public System.Nullable<System.DateTimeOffset> ReadDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Nullable<long> Size { get { return default(System.Nullable<long>); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ContentDispositionHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentDispositionHeaderValue); return default(bool); } } public partial class ContentRangeHeaderValue { public ContentRangeHeaderValue(long length) { } public ContentRangeHeaderValue(long from, long to) { } public ContentRangeHeaderValue(long from, long to, long length) { } public System.Nullable<long> From { get { return default(System.Nullable<long>); } } public bool HasLength { get { return default(bool); } } public bool HasRange { get { return default(bool); } } public System.Nullable<long> Length { get { return default(System.Nullable<long>); } } public System.Nullable<long> To { get { return default(System.Nullable<long>); } } public string Unit { get { return default(string); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ContentRangeHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentRangeHeaderValue); return default(bool); } } public partial class EntityTagHeaderValue { public EntityTagHeaderValue(string tag) { } public EntityTagHeaderValue(string tag, bool isWeak) { } public static System.Net.Http.Headers.EntityTagHeaderValue Any { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } } public bool IsWeak { get { return default(bool); } } public string Tag { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { return default(System.Net.Http.Headers.EntityTagHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.EntityTagHeaderValue); return default(bool); } } public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpContentHeaders() { } public System.Collections.Generic.ICollection<string> Allow { get { return default(System.Collections.Generic.ICollection<string>); } } public System.Net.Http.Headers.ContentDispositionHeaderValue ContentDisposition { get { return default(System.Net.Http.Headers.ContentDispositionHeaderValue); } set { } } public System.Collections.Generic.ICollection<string> ContentEncoding { get { return default(System.Collections.Generic.ICollection<string>); } } public System.Collections.Generic.ICollection<string> ContentLanguage { get { return default(System.Collections.Generic.ICollection<string>); } } public System.Nullable<long> ContentLength { get { return default(System.Nullable<long>); } set { } } public System.Uri ContentLocation { get { return default(System.Uri); } set { } } public byte[] ContentMD5 { get { return default(byte[]); } set { } } public System.Net.Http.Headers.ContentRangeHeaderValue ContentRange { get { return default(System.Net.Http.Headers.ContentRangeHeaderValue); } set { } } public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get { return default(System.Net.Http.Headers.MediaTypeHeaderValue); } set { } } public System.Nullable<System.DateTimeOffset> Expires { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Nullable<System.DateTimeOffset> LastModified { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } } public abstract partial class HttpHeaders : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>, System.Collections.IEnumerable { protected HttpHeaders() { } public void Add(string name, System.Collections.Generic.IEnumerable<string> values) { } public void Add(string name, string value) { } public void Clear() { } public bool Contains(string name) { return default(bool); } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>); } public System.Collections.Generic.IEnumerable<string> GetValues(string name) { return default(System.Collections.Generic.IEnumerable<string>); } public bool Remove(string name) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public override string ToString() { return default(string); } public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable<string> values) { return default(bool); } public bool TryAddWithoutValidation(string name, string value) { return default(bool); } public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable<string> values) { values = default(System.Collections.Generic.IEnumerable<string>); return default(bool); } } public sealed partial class HttpHeaderValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : class { internal HttpHeaderValueCollection() { } public int Count { get { return default(int); } } public bool IsReadOnly { get { return default(bool); } } public void Add(T item) { } public void Clear() { } public bool Contains(T item) { return default(bool); } public void CopyTo(T[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } public void ParseAdd(string input) { } public bool Remove(T item) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public override string ToString() { return default(string); } public bool TryParseAdd(string input) { return default(bool); } } public sealed partial class HttpRequestHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpRequestHeaders() { } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue> Accept { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptCharset { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptLanguage { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } } public System.Net.Http.Headers.AuthenticationHeaderValue Authorization { get { return default(System.Net.Http.Headers.AuthenticationHeaderValue); } set { } } public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { return default(System.Net.Http.Headers.CacheControlHeaderValue); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Nullable<bool> ConnectionClose { get { return default(System.Nullable<bool>); } set { } } public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue> Expect { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue>); } } public System.Nullable<bool> ExpectContinue { get { return default(System.Nullable<bool>); } set { } } public string From { get { return default(string); } set { } } public string Host { get { return default(string); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfMatch { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue>); } } public System.Nullable<System.DateTimeOffset> IfModifiedSince { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfNoneMatch { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue>); } } public System.Net.Http.Headers.RangeConditionHeaderValue IfRange { get { return default(System.Net.Http.Headers.RangeConditionHeaderValue); } set { } } public System.Nullable<System.DateTimeOffset> IfUnmodifiedSince { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Nullable<int> MaxForwards { get { return default(System.Nullable<int>); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public System.Net.Http.Headers.AuthenticationHeaderValue ProxyAuthorization { get { return default(System.Net.Http.Headers.AuthenticationHeaderValue); } set { } } public System.Net.Http.Headers.RangeHeaderValue Range { get { return default(System.Net.Http.Headers.RangeHeaderValue); } set { } } public System.Uri Referrer { get { return default(System.Uri); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue> TE { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue>); } } public System.Nullable<bool> TransferEncodingChunked { get { return default(System.Nullable<bool>); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> UserAgent { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue>); } } } public sealed partial class HttpResponseHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpResponseHeaders() { } public System.Net.Http.Headers.HttpHeaderValueCollection<string> AcceptRanges { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Nullable<System.TimeSpan> Age { get { return default(System.Nullable<System.TimeSpan>); } set { } } public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { return default(System.Net.Http.Headers.CacheControlHeaderValue); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Nullable<bool> ConnectionClose { get { return default(System.Nullable<bool>); } set { } } public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } set { } } public System.Net.Http.Headers.EntityTagHeaderValue ETag { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } set { } } public System.Uri Location { get { return default(System.Uri); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> ProxyAuthenticate { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue>); } } public System.Net.Http.Headers.RetryConditionHeaderValue RetryAfter { get { return default(System.Net.Http.Headers.RetryConditionHeaderValue); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> Server { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue>); } } public System.Nullable<bool> TransferEncodingChunked { get { return default(System.Nullable<bool>); } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Vary { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue>); } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> WwwAuthenticate { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue>); } } } public partial class MediaTypeHeaderValue { protected MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue source) { } public MediaTypeHeaderValue(string mediaType) { } public string CharSet { get { return default(string); } set { } } public string MediaType { get { return default(string); } set { } } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.MediaTypeHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeHeaderValue); return default(bool); } } public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue { public MediaTypeWithQualityHeaderValue(string mediaType) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { } public MediaTypeWithQualityHeaderValue(string mediaType, double quality) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { } public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } set { } } public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); } public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); return default(bool); } } public partial class NameValueHeaderValue { protected NameValueHeaderValue(System.Net.Http.Headers.NameValueHeaderValue source) { } public NameValueHeaderValue(string name) { } public NameValueHeaderValue(string name, string value) { } public string Name { get { return default(string); } } public string Value { get { return default(string); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { return default(System.Net.Http.Headers.NameValueHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueHeaderValue); return default(bool); } } public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue { protected NameValueWithParametersHeaderValue(System.Net.Http.Headers.NameValueWithParametersHeaderValue source) : base(default(string)) { } public NameValueWithParametersHeaderValue(string name) : base(default(string)) { } public NameValueWithParametersHeaderValue(string name, string value) : base(default(string)) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { return default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); return default(bool); } } public partial class ProductHeaderValue { public ProductHeaderValue(string name) { } public ProductHeaderValue(string name, string version) { } public string Name { get { return default(string); } } public string Version { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ProductHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductHeaderValue); return default(bool); } } public partial class ProductInfoHeaderValue { public ProductInfoHeaderValue(System.Net.Http.Headers.ProductHeaderValue product) { } public ProductInfoHeaderValue(string comment) { } public ProductInfoHeaderValue(string productName, string productVersion) { } public string Comment { get { return default(string); } } public System.Net.Http.Headers.ProductHeaderValue Product { get { return default(System.Net.Http.Headers.ProductHeaderValue); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ProductInfoHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductInfoHeaderValue); return default(bool); } } public partial class RangeConditionHeaderValue { public RangeConditionHeaderValue(System.DateTimeOffset date) { } public RangeConditionHeaderValue(System.Net.Http.Headers.EntityTagHeaderValue entityTag) { } public RangeConditionHeaderValue(string entityTag) { } public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } } public System.Net.Http.Headers.EntityTagHeaderValue EntityTag { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RangeConditionHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeConditionHeaderValue); return default(bool); } } public partial class RangeHeaderValue { public RangeHeaderValue() { } public RangeHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue> Ranges { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue>); } } public string Unit { get { return default(string); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RangeHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeHeaderValue); return default(bool); } } public partial class RangeItemHeaderValue { public RangeItemHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { } public System.Nullable<long> From { get { return default(System.Nullable<long>); } } public System.Nullable<long> To { get { return default(System.Nullable<long>); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public override string ToString() { return default(string); } } public partial class RetryConditionHeaderValue { public RetryConditionHeaderValue(System.DateTimeOffset date) { } public RetryConditionHeaderValue(System.TimeSpan delta) { } public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } } public System.Nullable<System.TimeSpan> Delta { get { return default(System.Nullable<System.TimeSpan>); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RetryConditionHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RetryConditionHeaderValue); return default(bool); } } public partial class StringWithQualityHeaderValue { public StringWithQualityHeaderValue(string value) { } public StringWithQualityHeaderValue(string value, double quality) { } public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } } public string Value { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.StringWithQualityHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.StringWithQualityHeaderValue); return default(bool); } } public partial class TransferCodingHeaderValue { protected TransferCodingHeaderValue(System.Net.Http.Headers.TransferCodingHeaderValue source) { } public TransferCodingHeaderValue(string value) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } } public string Value { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { return default(System.Net.Http.Headers.TransferCodingHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingHeaderValue); return default(bool); } } public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue { public TransferCodingWithQualityHeaderValue(string value) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { } public TransferCodingWithQualityHeaderValue(string value, double quality) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { } public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } set { } } public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); } public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); return default(bool); } } public partial class ViaHeaderValue { public ViaHeaderValue(string protocolVersion, string receivedBy) { } public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName) { } public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment) { } public string Comment { get { return default(string); } } public string ProtocolName { get { return default(string); } } public string ProtocolVersion { get { return default(string); } } public string ReceivedBy { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ViaHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ViaHeaderValue); return default(bool); } } public partial class WarningHeaderValue { public WarningHeaderValue(int code, string agent, string text) { } public WarningHeaderValue(int code, string agent, string text, System.DateTimeOffset date) { } public string Agent { get { return default(string); } } public int Code { get { return default(int); } } public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } } public string Text { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { return default(System.Net.Http.Headers.WarningHeaderValue); } public override string ToString() { return default(string); } public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.WarningHeaderValue); return default(bool); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.VisualBasic; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RemoveEmptyFinalizersAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RemoveEmptyFinalizersAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class RemoveEmptyFinalizersTests { [Fact] public async Task CA1821CSharpTestNoWarning() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // No violation because the finalizer contains a method call ~Class1() { System.Console.Write("" ""); } } public class Class2 { // No violation because the finalizer contains a local declaration statement ~Class2() { var x = 1; } } public class Class3 { bool x = true; // No violation because the finalizer contains an expression statement ~Class3() { x = false; } } public class Class4 { // No violation because the finalizer's body is not empty ~Class4() { var x = false; Debug.Fail(""Finalizer called!""); } } public class Class5 { // No violation because the finalizer's body is not empty ~Class5() { while (true) ; } } public class Class6 { // No violation because the finalizer's body is not empty ~Class6() { System.Console.WriteLine(); Debug.Fail(""Finalizer called!""); } } public class Class7 { // Violation will not occur because the finalizer's body is not empty. ~Class7() { if (true) { Debug.Fail(""Finalizer called!""); } } } "); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizers() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { // Violation occurs because the finalizer is empty. ~Class1() { } } public class Class2 { // Violation occurs because the finalizer is empty. ~Class2() { //// Comments here } } ", GetCA1821CSharpResultAt(5, 3), GetCA1821CSharpResultAt(13, 3)); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithScope() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { // Violation occurs because the finalizer is empty. ~[|Class1|]() { } } public class Class2 { // Violation occurs because the finalizer is empty. ~[|Class2|]() { //// Comments here } } "); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFail() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. // The finalizer will contain code only if the DEBUG directive // symbol is present at compile time. When the DEBUG // directive is not present, the finalizer will still exist, but // it will be empty. ~Class1() { Debug.Fail(""Finalizer called!""); } } ", GetCA1821CSharpResultAt(11, 3)); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFail_ExpressionBody() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. // The finalizer will contain code only if the DEBUG directive // symbol is present at compile time. When the DEBUG // directive is not present, the finalizer will still exist, but // it will be empty. ~Class1() => Debug.Fail(""Finalizer called!""); } ", GetCA1821CSharpResultAt(11, 3)); } [Fact, WorkItem(1241, "https://github.com/dotnet/roslyn-analyzers/issues/1241")] public async Task CA1821_DebugFailAndDebugDirective_NoDiagnostic() { await new VerifyCS.Test { TestCode = @" public class Class1 { #if DEBUG // Violation will not occur because the finalizer will exist and // contain code when the DEBUG directive is present. When the // DEBUG directive is not present, the finalizer will not exist, // and therefore not be empty. ~Class1() { System.Diagnostics.Debug.Fail(""Finalizer called!""); } #endif } ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols("DEBUG"); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); await new VerifyVB.Test { TestCode = @" Public Class Class1 #If DEBUG Then Protected Overrides Sub Finalize() System.Diagnostics.Debug.Fail(""Finalizer called!"") End Sub #End If End Class ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((VisualBasicParseOptions)project.ParseOptions).WithPreprocessorSymbols(new KeyValuePair<string, object>("DEBUG", true)); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); } [Fact, WorkItem(1241, "https://github.com/dotnet/roslyn-analyzers/issues/1241")] public async Task CA1821_DebugFailAndReleaseDirective_NoDiagnostic_FalsePositive() { await new VerifyCS.Test { TestCode = @" public class Class1 { #if RELEASE // There should be a diagnostic because in release the finalizer will be empty. ~Class1() { System.Diagnostics.Debug.Fail(""Finalizer called!""); } #endif } ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols("RELEASE"); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); await new VerifyVB.Test { TestCode = @" Public Class Class1 #If RELEASE Then ' There should be a diagnostic because in release the finalizer will be empty. Protected Overrides Sub Finalize() System.Diagnostics.Debug.Fail(""Finalizer called!"") End Sub #End If End Class ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((VisualBasicParseOptions)project.ParseOptions).WithPreprocessorSymbols(new KeyValuePair<string, object>("RELEASE", true)); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFailAndDirectiveAroundStatements() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. ~Class1() { Debug.Fail(""Class1 finalizer called!""); } } public class Class2 { // Violation will not occur because the finalizer's body is not empty. ~Class2() { Debug.Fail(""Class2 finalizer called!""); SomeMethod(); } void SomeMethod() { } } ", GetCA1821CSharpResultAt(7, 3)); } [WorkItem(820941, "DevDiv")] [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithNonInvocationBody() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() { Class2.SomeFlag = true; } } public class Class2 { public static bool SomeFlag; } "); } [Fact] public async Task CA1821BasicTestNoWarning() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' No violation because the finalizer contains a method call Protected Overrides Sub Finalize() System.Console.Write("" "") End Sub End Class Public Class Class2 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() Dim a = true End Sub End Class Public Class Class3 Dim a As Boolean = True ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() a = False End Sub End Class Public Class Class4 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() Dim a = False Debug.Fail(""Finalizer called!"") End Sub End Class Public Class Class5 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() If True Then Debug.Fail(""Finalizer called!"") End If End Sub End Class "); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizers() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because the finalizer is empty. Protected Overrides Sub Finalize() End Sub End Class Public Class Class2 ' Violation occurs because the finalizer is empty. Protected Overrides Sub Finalize() ' Comments End Sub End Class Public Class Class3 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Debug.Fail(""Finalizer called!"") End Sub End Class ", GetCA1821BasicResultAt(6, 29), GetCA1821BasicResultAt(13, 29), GetCA1821BasicResultAt(20, 29)); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithScope() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because the finalizer is empty. Protected Overrides Sub [|Finalize|]() End Sub End Class Public Class Class2 ' Violation occurs because the finalizer is empty. Protected Overrides Sub [|Finalize|]() ' Comments End Sub End Class Public Class Class3 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub [|Finalize|]() Debug.Fail(""Finalizer called!"") End Sub End Class "); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithDebugFail() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Debug.Fail(""Finalizer called!"") End Sub End Class Public Class Class2 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Dim a = False Debug.Fail(""Finalizer called!"") End Sub End Class ", GetCA1821BasicResultAt(6, 29)); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithThrowStatement() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() { throw new System.Exception(); } }", GetCA1821CSharpResultAt(4, 6)); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithThrowExpression() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() => throw new System.Exception(); }", GetCA1821CSharpResultAt(4, 6)); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithThrowStatement() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Throw New System.Exception() End Sub End Class ", GetCA1821BasicResultAt(4, 29)); } [Fact, WorkItem(1211, "https://github.com/dotnet/roslyn-analyzers/issues/1211")] public async Task CA1821CSharpRemoveEmptyFinalizersInvalidInvocationExpression() { await VerifyCS.VerifyAnalyzerAsync(@" public class C1 { ~C1() { {|CS0103:a|}{|CS1002:|} } } "); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpRemoveEmptyFinalizers_ErrorCodeWithBothBlockAndExpressionBody() { await VerifyCS.VerifyAnalyzerAsync(@" public class C1 { {|CS8057:~C1() { } => {|CS1525:;|}|} } "); } [Fact, WorkItem(1211, "https://github.com/dotnet/roslyn-analyzers/issues/1211")] public async Task CA1821BasicRemoveEmptyFinalizersInvalidInvocationExpression() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 Protected Overrides Sub Finalize() {|BC30451:a|} End Sub End Class "); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpRemoveEmptyFinalizers_ExpressionBodiedImpl() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.IO; public class SomeTestClass : IDisposable { private readonly Stream resource = new MemoryStream(1024); public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool dispose) { if (dispose) { this.resource.Dispose(); } } ~SomeTestClass() => this.Dispose(false); }"); } private static DiagnosticResult GetCA1821CSharpResultAt(int line, int column) => VerifyCS.Diagnostic() .WithLocation(line, column); private static DiagnosticResult GetCA1821BasicResultAt(int line, int column) => VerifyVB.Diagnostic() .WithLocation(line, column); } }
using System; using System.Collections.Generic; using System.Linq; using com.tinylabproductions.TLPLib.Data; using com.tinylabproductions.TLPLib.Extensions; using tlplib.exts; using com.tinylabproductions.TLPLib.Functional; using com.tinylabproductions.TLPLib.Logger; using tlplib.log; using GenerationAttributes; using JetBrains.Annotations; using tlplib.collection; using tlplib.concurrent; using tlplib.functional; using UnityEngine; using UnityEngine.ResourceManagement.AsyncOperations; namespace com.tinylabproductions.TLPLib.Concurrent { [PublicAPI] public interface IAsyncOperationHandle<A> { AsyncOperationStatus Status { get; } bool IsDone { get; } /// <summary> /// Combined progress of downloading from internet and loading from disk /// </summary> float PercentComplete { get; } /// <summary> /// Status about bytes that are downloaded from the internet /// </summary> DownloadStatus downloadStatus { get; } Future<Try<A>> asFuture { get; } void release(); } public static class DownloadStatusExts { public static DownloadStatus join(this DownloadStatus a, DownloadStatus b) => new DownloadStatus { DownloadedBytes = a.DownloadedBytes + b.DownloadedBytes, TotalBytes = a.TotalBytes + b.TotalBytes, IsDone = a.IsDone && b.IsDone }; public static string debugStr(this DownloadStatus ds) => $"{ds.DownloadedBytes}/{ds.TotalBytes} bytes ({ds.Percent * 100} %), isDone = {ds.IsDone}"; } [PublicAPI] public static class IASyncOperationHandle_ { public static IAsyncOperationHandle<Unit> delayFrames(uint durationInFrames) => new DelayAsyncOperationHandle<Unit>(durationInFrames, Unit._); public static IAsyncOperationHandle<A> delayFrames<A>(uint durationInFrames, A a) => new DelayAsyncOperationHandle<A>(durationInFrames, a); public static IAsyncOperationHandle<Unit> done => DoneAsyncOperationHandle.instance; /// <summary>Launches given async operation, retrying it if it fails.</summary> /// <param name="launch"></param> /// <param name="tryCount"> /// If None will retry forever. How many times we should try the operation? If lower than 1 will still try at least /// 1 time. /// </param> /// <param name="retryInterval"></param> /// <param name="timeContext"></param> public static IAsyncOperationHandle<A> withRetries<A>( Func<IAsyncOperationHandle<A>> launch, Option<uint> tryCount, Duration retryInterval, ITimeContext timeContext ) => new RetryingAsyncOperationHandle<A>(launch, tryCount, retryInterval, timeContext); } [PublicAPI] public static class IAsyncOperationHandleExts { public static IAsyncOperationHandle<A> wrap<A>( this AsyncOperationHandle<A> handle, Action<AsyncOperationHandle<A>> release ) => new WrappedAsyncOperationHandle<A>(handle, release); public static IAsyncOperationHandle<A> wrap<A>( this AsyncOperationHandle<A> handle, Action<A> onSuccess, Action<AsyncOperationHandle<A>> release ) { var result = new WrappedAsyncOperationHandle<A>(handle, release); result.asFuture.onSuccess(onSuccess); return result; } public static IAsyncOperationHandle<object> wrap( this AsyncOperationHandle handle, Action<AsyncOperationHandle> release ) => new WrappedAsyncOperationHandle(handle, release); public static IAsyncOperationHandle<B> map<A, B>( this IAsyncOperationHandle<A> handle, Func<A, IAsyncOperationHandle<A>, B> mapper ) => new MappedAsyncOperationHandle<A, B>(handle, a => mapper(a, handle)); public static IAsyncOperationHandle<B> flatMap<A, B>( this IAsyncOperationHandle<A> handle, Func<A, IAsyncOperationHandle<A>, IAsyncOperationHandle<B>> mapper, float aHandleProgressPercentage=0.5f ) => new FlatMappedAsyncOperationHandle<A, B>(handle, a => mapper(a, handle), aHandleProgressPercentage); public static IAsyncOperationHandle<A> delayedFrames<A>( this IAsyncOperationHandle<A> handle, uint durationInFrames, float aHandleProgressPercentage=0.5f ) => handle.flatMap( (a, h) => new DelayAsyncOperationHandle<A>(durationInFrames, a, h.release), aHandleProgressPercentage: aHandleProgressPercentage ); public static IAsyncOperationHandle<ImmutableArrayC<A>> sequenceNonFailing<A>( this IReadOnlyCollection<IAsyncOperationHandle<A>> collection ) => new SequencedNonFailingAsyncOperationHandle<A>(collection); public static IAsyncOperationHandle<ImmutableArrayC<Try<A>>> sequence<A>( this IReadOnlyCollection<IAsyncOperationHandle<A>> collection ) => new SequencedAsyncOperationHandle<A>(collection); public static Try<A> toTry<A>(this IAsyncOperationHandle<A> handle) { if (handle.asFuture.value.valueOut(out var val)) return val; return Try<A>.failed(new Exception("Handle is not completed!")); } } #region implementations [Record] sealed partial class HandleStatusOnRelease { public readonly AsyncOperationStatus status; public readonly float percentComplete; public readonly DownloadStatus downloadStatus; public bool isDone => status != AsyncOperationStatus.None; } public sealed partial class WrappedAsyncOperationHandle<A> : IAsyncOperationHandle<A> { readonly AsyncOperationHandle<A> handle; readonly Action<AsyncOperationHandle<A>> _release; Option<HandleStatusOnRelease> released = None._; public WrappedAsyncOperationHandle( AsyncOperationHandle<A> handle, Action<AsyncOperationHandle<A>> release ) { this.handle = handle; _release = release; } public AsyncOperationStatus Status => released.valueOut(out var r) ? r.status : handle.Status; public bool IsDone => released.valueOut(out var r) ? r.isDone : handle.IsDone; public float PercentComplete => released.valueOut(out var r) ? r.percentComplete : handle.PercentComplete; public DownloadStatus downloadStatus => released.valueOut(out var r) ? r.downloadStatus : handle.GetDownloadStatus(); [LazyProperty] public Future<Try<A>> asFuture => handle.toFuture().map(h => h.toTry()); public void release() { if (released) return; var data = new HandleStatusOnRelease(handle.Status, handle.PercentComplete, handle.GetDownloadStatus()); _release(handle); released = Some.a(data); } } public sealed class WrappedAsyncOperationHandle : IAsyncOperationHandle<object> { readonly AsyncOperationHandle handle; readonly Action<AsyncOperationHandle> _release; Option<HandleStatusOnRelease> released = None._; public WrappedAsyncOperationHandle( AsyncOperationHandle handle, Action<AsyncOperationHandle> release ) { this.handle = handle; _release = release; } public AsyncOperationStatus Status => released.valueOut(out var r) ? r.status : handle.Status; public bool IsDone => released.valueOut(out var r) ? r.isDone : handle.IsDone; public float PercentComplete => released.valueOut(out var r) ? r.percentComplete : handle.PercentComplete; public DownloadStatus downloadStatus => released.valueOut(out var r) ? r.downloadStatus : handle.GetDownloadStatus(); public Future<Try<object>> asFuture => handle.toFuture().map(h => h.toTry()); public void release() { if (released) return; var data = new HandleStatusOnRelease(handle.Status, handle.PercentComplete, handle.GetDownloadStatus()); _release(handle); released = Some.a(data); } } public sealed class MappedAsyncOperationHandle<A, B> : IAsyncOperationHandle<B> { readonly IAsyncOperationHandle<A> handle; readonly Func<A, B> mapper; public MappedAsyncOperationHandle(IAsyncOperationHandle<A> handle, Func<A, B> mapper) { this.handle = handle; this.mapper = mapper; } public AsyncOperationStatus Status => handle.Status; public bool IsDone => handle.IsDone; public float PercentComplete => handle.PercentComplete; public DownloadStatus downloadStatus => handle.downloadStatus; [LazyProperty] public Future<Try<B>> asFuture => handle.asFuture.map(try_ => try_.map(mapper)); public void release() => handle.release(); } public sealed class FlatMappedAsyncOperationHandle<A, B> : IAsyncOperationHandle<B> { readonly IAsyncOperationHandle<A> aHandle; readonly Future<Try<IAsyncOperationHandle<B>>> bHandleF; readonly float aHandleProgressPercentage; float bHandleProgressPercentage => 1 - aHandleProgressPercentage; public FlatMappedAsyncOperationHandle( IAsyncOperationHandle<A> handle, Func<A, IAsyncOperationHandle<B>> mapper, float aHandleProgressPercentage ) { aHandle = handle; if (aHandleProgressPercentage < 0 || aHandleProgressPercentage > 1) Log.d.error($"{aHandleProgressPercentage.echo()} not within [0..1], clamping"); this.aHandleProgressPercentage = Mathf.Clamp01(aHandleProgressPercentage); bHandleF = handle.asFuture.map(try_ => try_.map(mapper)); } public AsyncOperationStatus Status => bHandleF.value.valueOut(out var b) ? b.fold(h => h.Status, e => AsyncOperationStatus.Failed) : aHandle.Status; public bool IsDone => bHandleF.value.valueOut(out var b) && b.fold(h => h.IsDone, e => true); public float PercentComplete => bHandleF.value.valueOut(out var b) ? aHandleProgressPercentage + b.fold(h => h.PercentComplete, e => 1) * bHandleProgressPercentage : aHandle.PercentComplete * aHandleProgressPercentage; public DownloadStatus downloadStatus { get { if (bHandleF.value.valueOut(out var b)) { return b.fold(h => h.downloadStatus, e => aHandle.downloadStatus); } return aHandle.downloadStatus; } } public Future<Try<B>> asFuture => bHandleF.flatMapT(bHandle => bHandle.asFuture); public void release() { { if (bHandleF.value.valueOut(out var b) && b.valueOut(out var h)) h.release(); } aHandle.release(); } } public sealed class DelayAsyncOperationHandle<A> : IAsyncOperationHandle<A> { public readonly uint startedAtFrame, endAtFrame, durationInFrames; readonly Option<Action> onRelease; readonly A value; public DelayAsyncOperationHandle(uint durationInFrames, A value, Action onRelease=null) { this.durationInFrames = durationInFrames; startedAtFrame = Time.frameCount.toUIntClamped(); endAtFrame = startedAtFrame + durationInFrames; this.value = value; this.onRelease = onRelease.opt(); } long framesPassed => Time.frameCount - startedAtFrame; long framesLeft => endAtFrame - Time.frameCount; public override string ToString() => $"{nameof(DelayAsyncOperationHandle<A>)}({startedAtFrame.echo()}, {endAtFrame.echo()})"; public AsyncOperationStatus Status => IsDone ? AsyncOperationStatus.Succeeded : AsyncOperationStatus.None; public bool IsDone => Time.frameCount >= endAtFrame; public float PercentComplete => Mathf.Clamp01(framesPassed / (float) durationInFrames); public DownloadStatus downloadStatus => new DownloadStatus { IsDone = IsDone }; public Future<Try<A>> asFuture { get { var left = framesLeft; return left <= 0 ? Future.successful(Try.value(value)) : FutureU.delayFrames(left.toIntClamped(), Try.value(value)); } } public void release() { if (onRelease.valueOut(out var action)) action(); } } [Singleton] public sealed partial class DoneAsyncOperationHandle : IAsyncOperationHandle<Unit> { public AsyncOperationStatus Status => AsyncOperationStatus.Succeeded; public bool IsDone => true; public float PercentComplete => 1; public DownloadStatus downloadStatus => new DownloadStatus { IsDone = IsDone }; public Future<Try<Unit>> asFuture => Future.successful(Try.value(Unit._)); public void release() {} } public sealed class SequencedAsyncOperationHandle<A> : IAsyncOperationHandle<ImmutableArrayC<Try<A>>> { public readonly IReadOnlyCollection<IAsyncOperationHandle<A>> handles; public SequencedAsyncOperationHandle(IReadOnlyCollection<IAsyncOperationHandle<A>> handles) => this.handles = handles; public AsyncOperationStatus Status { get { foreach (var handle in handles) { switch (handle.Status) { case AsyncOperationStatus.None: return AsyncOperationStatus.None; case AsyncOperationStatus.Failed: return AsyncOperationStatus.Failed; case AsyncOperationStatus.Succeeded: break; default: throw new ArgumentOutOfRangeException(); } } return AsyncOperationStatus.Succeeded; } } public bool IsDone => handles.Count == 0 || handles.All(_ => _.IsDone); public float PercentComplete => handles.Count == 0 ? 1 : handles.Average(_ => _.PercentComplete); public DownloadStatus downloadStatus => handles.Aggregate( new DownloadStatus { IsDone = true }, (a, b) => a.join(b.downloadStatus) ); public Future<Try<ImmutableArrayC<Try<A>>>> asFuture => handles.Select(h => h.asFuture).parallel().map(arr => Try.value(ImmutableArrayC.move(arr))); public void release() { foreach (var handle in handles) handle.release(); } } public sealed class SequencedNonFailingAsyncOperationHandle<A> : IAsyncOperationHandle<ImmutableArrayC<A>> { public readonly IReadOnlyCollection<IAsyncOperationHandle<A>> handles; public SequencedNonFailingAsyncOperationHandle(IReadOnlyCollection<IAsyncOperationHandle<A>> handles) => this.handles = handles; public AsyncOperationStatus Status { get { foreach (var handle in handles) { switch (handle.Status) { case AsyncOperationStatus.None: return AsyncOperationStatus.None; case AsyncOperationStatus.Failed: return AsyncOperationStatus.Failed; case AsyncOperationStatus.Succeeded: break; default: throw new ArgumentOutOfRangeException(); } } return AsyncOperationStatus.Succeeded; } } public bool IsDone => handles.Count == 0 || handles.All(_ => _.IsDone); public float PercentComplete => handles.Count == 0 ? 1 : handles.Average(_ => _.PercentComplete); public DownloadStatus downloadStatus => handles.Aggregate( new DownloadStatus { IsDone = true }, (a, b) => a.join(b.downloadStatus) ); public Future<Try<ImmutableArrayC<A>>> asFuture => handles.Select(h => h.asFuture).parallel().map(arr => arr.sequence().map(_ => _.toImmutableArrayC())); public void release() { foreach (var handle in handles) handle.release(); } } public sealed class RetryingAsyncOperationHandle<A> : IAsyncOperationHandle<A> { enum State : byte { Launched, WaitingToRetry, Finished, Released } readonly Func<IAsyncOperationHandle<A>> launchRaw; readonly Option<uint> tryCount; readonly Duration retryInterval; readonly ITimeContext timeContext; readonly Future<IAsyncOperationHandle<A>> finalHandleFuture; readonly Promise<IAsyncOperationHandle<A>> finalHandlePromise; uint retryNo = 1; State state; IAsyncOperationHandle<A> current; IDisposable currentRetryWait = F.emptyDisposable; public RetryingAsyncOperationHandle( Func<IAsyncOperationHandle<A>> launch, Option<uint> tryCount, Duration retryInterval, ITimeContext timeContext ) { launchRaw = launch; this.tryCount = tryCount; this.retryInterval = retryInterval; this.timeContext = timeContext; finalHandleFuture = Future.async(out finalHandlePromise); this.launch(); } public AsyncOperationStatus Status => current.Status; public bool IsDone => current.IsDone; public float PercentComplete => current.PercentComplete; public DownloadStatus downloadStatus => current.downloadStatus; public Future<Try<A>> asFuture => finalHandleFuture.flatMap(h => h.asFuture); public void release() { current.release(); state = State.Released; currentRetryWait.Dispose(); } void launch() { var handle = current = launchRaw(); state = State.Launched; handle.asFuture.onComplete(try_ => { if (state == State.Released) return; try_.voidFold( // Success! a => { state = State.Finished; finalHandlePromise.complete(handle); }, err => { if (!tryCount.valueOut(out var count) || retryNo < count) { // Retry retryNo++; state = State.WaitingToRetry; currentRetryWait = timeContext.after( retryInterval, name: nameof(RetryingAsyncOperationHandle<A>), act: launch ); } else { // We've run out of retries, complete with what we had last. state = State.Finished; finalHandlePromise.complete(handle); } } ); }); } } #endregion }
using System; using NUnit.Framework; using System.Text; #if FX1_1 using IList_ServiceElement = System.Collections.IList; using List_ServiceElement = System.Collections.ArrayList; using IList_ServiceAttribute = System.Collections.IList; using List_ServiceAttribute = System.Collections.ArrayList; #else using IList_ServiceElement = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceElement>; using List_ServiceElement = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceElement>; using IList_ServiceAttribute = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceAttribute>; using List_ServiceAttribute = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceAttribute>; #endif using InTheHand.Net.Bluetooth; using InTheHand.Net.Bluetooth.AttributeIds; namespace InTheHand.Net.Tests.Sdp2 { [TestFixture] public class RecordStringLanguageBase { public const string CrLf = "\r\n"; public static readonly byte[] RecordBytesEnIs = { 0x35, 41, 0x09, 0x00, 0x06, // Languages 0x35, 18, 0x09, 0x69, 0x73, // "is" 0x09, 0x08, 0xcc, // windows-1252 0x09, 0x01, 0x10, // base=0x0110 0x09, 0x65, 0x6e, // "en" 0x09, 0x00, 0x6a, // utf-8 0x09, 0x01, 0x00, // base=0x0100 0x09, 0x01, 0x00, // SvcName/En 0x25, 4, (byte)'a', (byte)'b', (byte)'c', (byte)'d', 0x09, 0x01, 0x10, // SvcName/IS 0x25, 4, (byte)'a', (byte)'b', (byte)'c', (byte)'e', }; public static readonly byte[] RecordBytesEnIsEncodings = { 0x35, 46, 0x09, 0x00, 0x06, // Languages 0x35, 18, 0x09, 0x69, 0x73, // "is" 0x09, 0x08, 0xcc, // windows-1252 0x09, 0x01, 0x10, // base=0x0110 0x09, 0x65, 0x6e, // "en" 0x09, 0x00, 0x6a, // utf-8 0x09, 0x01, 0x00, // base=0x0100 0x09, 0x01, 0x00, // SvcName/En 0x25, 7, (byte)'a', (byte)'b', 0xE2, 0x80, 0xA0, (byte)'c', (byte)'d', 0x09, 0x01, 0x10, // SvcName/IS 0x25, 6, (byte)'a', (byte)'b', 0xD0, (byte)'c', 0xDE, (byte)'e', }; public static readonly byte[] RecordBytesEnIsEncodingsNoLangBaseItems = { 0x35, 23, // No LangBaseItems!!! //0x09, 0x00, 0x06, // Languages //0x35, 18, // 0x09, 0x69, 0x73, // "is" // 0x09, 0x08, 0xcc, // windows-1252 // 0x09, 0x01, 0x10, // base=0x0110 // 0x09, 0x65, 0x6e, // "en" // 0x09, 0x00, 0x6a, // utf-8 // 0x09, 0x01, 0x00, // base=0x0100 0x09, 0x01, 0x00, // SvcName/En 0x25, 7, (byte)'a', (byte)'b', 0xE2, 0x80, 0xA0, (byte)'c', (byte)'d', 0x09, 0x01, 0x10, // SvcName/IS 0x25, 6, (byte)'a', (byte)'b', 0xD0, (byte)'c', 0xDE, (byte)'e', }; [Test] public void EnIsSimple() { String expectedEn = "abcd"; String expectedIs = "abce"; byte[] buffer = RecordBytesEnIs; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langIs = langList[0]; Assert.AreEqual("is", langIs.NaturalLanguage); LanguageBaseItem langEn = langList[1]; Assert.AreEqual("en", langEn.NaturalLanguage); // ServiceAttribute attrEn = record.GetAttributeByIndex(1); ServiceAttribute attrIs = record.GetAttributeByIndex(2); Assert.AreEqual((ServiceAttributeId)0x0100, attrEn.Id); Assert.AreEqual((ServiceAttributeId)0x0110, attrIs.Id); String resultEn = attrEn.Value.GetValueAsString(langEn); String resultIs = attrIs.Value.GetValueAsString(langIs); Assert.AreEqual(expectedEn, resultEn); Assert.AreEqual(expectedIs, resultIs); } [Test] public void EnIsEncodings() { String expectedEn = "ab\u2020cd"; String expectedIs = "ab\u00D0c\u00DEe"; byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langIs = langList[0]; Assert.AreEqual("is", langIs.NaturalLanguage); LanguageBaseItem langEn = langList[1]; Assert.AreEqual("en", langEn.NaturalLanguage); // ServiceAttribute attrEn = record.GetAttributeByIndex(1); ServiceAttribute attrIs = record.GetAttributeByIndex(2); Assert.AreEqual((ServiceAttributeId)0x0100, attrEn.Id); Assert.AreEqual((ServiceAttributeId)0x0110, attrIs.Id); String resultEn = attrEn.Value.GetValueAsString(langEn); String resultIs = attrIs.Value.GetValueAsString(langIs); Assert.AreEqual(expectedEn, resultEn); Assert.AreEqual(expectedIs, resultIs); } [Test] public void EnIsEncodingsById() { String expectedEn = "ab\u2020cd"; String expectedIs = "ab\u00D0c\u00DEe"; byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langIs = langList[0]; Assert.AreEqual("is", langIs.NaturalLanguage); LanguageBaseItem langEn = langList[1]; Assert.AreEqual("en", langEn.NaturalLanguage); // ServiceAttribute attrEn = record.GetAttributeById(0, langEn); ServiceAttribute attrIs = record.GetAttributeById(0, langIs); Assert.AreEqual((ServiceAttributeId)0x0100, attrEn.Id); Assert.AreEqual((ServiceAttributeId)0x0110, attrIs.Id); String resultEn = attrEn.Value.GetValueAsString(langEn); String resultIs = attrIs.Value.GetValueAsString(langIs); Assert.AreEqual(expectedEn, resultEn); Assert.AreEqual(expectedIs, resultIs); } [Test] public void EnIsEncodingsRecordGetStringByIdAndLang() { String expectedEn = "ab\u2020cd"; String expectedIs = "ab\u00D0c\u00DEe"; byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langIs = langList[0]; Assert.AreEqual("is", langIs.NaturalLanguage); LanguageBaseItem langEn = langList[1]; Assert.AreEqual("en", langEn.NaturalLanguage); // // Here's the stuff really tested here!!!! String resultEn = record.GetMultiLanguageStringAttributeById(0, langEn); String resultIs = record.GetMultiLanguageStringAttributeById(0, langIs); Assert.AreEqual(expectedEn, resultEn); Assert.AreEqual(expectedIs, resultIs); String resultEnPrimary = record.GetPrimaryMultiLanguageStringAttributeById(0); Assert.AreEqual(expectedEn, resultEnPrimary); } [Test] public void EnIsEncodingsRecordGetStringByIdAndLangNoLangBaseItems() { String expectedEn = "ab\u2020cd"; byte[] buffer = RecordBytesEnIsEncodingsNoLangBaseItems; ServiceRecord record = new ServiceRecordParser().Parse(buffer); // LanguageBaseItem[] langList = record.GetLanguageBaseList(); Assert.AreEqual(0, langList.Length, "#LangItems==0"); // String resultEnPrimary = record.GetPrimaryMultiLanguageStringAttributeById(0); Assert.AreEqual(expectedEn, resultEnPrimary); } [Test] [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = "Value cannot be null." + CrLf + "Parameter name: language")] public void BadGetStringByIdAndLang_LangNull() { byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); record.GetMultiLanguageStringAttributeById(0, null); } [Test] [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Not TextString type.")] public void BadNonStringAttribute() { byte[] buffer = Data_CompleteThirdPartyRecords.Xp1Sdp; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langEn = langList[0]; Assert.AreEqual("en", langEn.NaturalLanguage); // // There's a attribute 0x0201 of type UInt32, accessing it should fail String resultEn = record.GetMultiLanguageStringAttributeById((ServiceAttributeId)0x101, langEn); Assert.Fail("should have thrown!"); } [Test] [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Not TextString type.")] public void BadNonStringAttributePrimary() { byte[] buffer = Data_CompleteThirdPartyRecords.Xp1Sdp; ServiceRecord record = new ServiceRecordParser().Parse(buffer); LanguageBaseItem[] langList = record.GetLanguageBaseList(); // LanguageBaseItem langEn = langList[0]; Assert.AreEqual("en", langEn.NaturalLanguage); // // There's a attribute 0x0201 of type UInt32, accessing it should fail String resultEn = record.GetPrimaryMultiLanguageStringAttributeById((ServiceAttributeId)0x101); Assert.Fail("should have thrown!"); } [Test] #if ! PocketPC [ExpectedException(typeof(System.Text.DecoderFallbackException), ExpectedMessage = "Unable to translate bytes [E2] at index 2 from specified code page to Unicode.")] #endif public void BadStringEncodingNotAscii() { byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); // ServiceAttribute attr = record.GetAttributeById((ServiceAttributeId)0x0100); const ushort langEn = 0x656e; const ushort ietfAscii = 3; LanguageBaseItem langBase = new LanguageBaseItem(langEn, ietfAscii, (ServiceAttributeId)0x0999); String x = attr.Value.GetValueAsString(langBase); } //-------------------------------------------------------------- static ServiceRecord CreateRecord(params ServiceAttribute[] attributes) { //ServiceRecord record = new ServiceRecord(); //record.Add(id, element_); // List_ServiceAttribute list = new List_ServiceAttribute(attributes); ServiceRecord record = new ServiceRecord(list); // return record; } [Test] public void StringGivenString() { ushort LangCodeEn = 0x656e; // "en" ushort LangCodeIs = 0x6973; // "is" ushort EncodingIdUtf8 = 106; ushort EncodingIdUtf16BE = 1013; ushort BaseA = 0x0100; ushort BaseB = 0x0100; // String str = "ambds\u2022nbdas\u00FEdlka\U00012004slkda"; ServiceElement element_ = new ServiceElement(ElementType.TextString, str); ServiceAttributeId id = ServiceRecord.CreateLanguageBasedAttributeId(UniversalAttributeId.ServiceName, (ServiceAttributeId)BaseA); ServiceAttribute attribute = new ServiceAttribute(id, element_); ServiceRecord record = CreateRecord(attribute); // LanguageBaseItem langBaseEn = new LanguageBaseItem(LangCodeEn, EncodingIdUtf8, BaseA); LanguageBaseItem langBaseIs = new LanguageBaseItem(LangCodeIs, EncodingIdUtf16BE, BaseB); Assert.AreEqual(str, record.GetMultiLanguageStringAttributeById( InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceName, langBaseEn)); Assert.AreEqual(str, record.GetMultiLanguageStringAttributeById( InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceName, langBaseIs)); // ServiceElement element = record.GetAttributeById(UniversalAttributeId.ServiceName, langBaseIs).Value; Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor); Assert.AreEqual(ElementType.TextString, element.ElementType); Assert.IsInstanceOfType(typeof(String), element.Value); Assert.AreEqual(str, element.GetValueAsStringUtf8()); Assert.AreEqual(str, element.GetValueAsString(Encoding.ASCII)); Assert.AreEqual(str, element.GetValueAsString(Encoding.Unicode)); } }//class }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { #if !NET45PLUS extern alias rax; using rax::System.Collections; using rax::System.Collections.Generic; #if !NET40PLUS using rax::System.Diagnostics.Contracts; #endif #endif public class ImmutableHashSetTest : ImmutableSetTest { protected override bool IncludesGetHashCodeDerivative { get { return true; } } [Fact] public void EmptyTest() { this.EmptyTestHelper(Empty<int>(), 5, null); this.EmptyTestHelper(EmptyTyped<string>().WithComparer(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase); } [Fact] public void CustomSort() { this.CustomSortTestHelper( ImmutableHashSet<string>.Empty.WithComparer(StringComparer.Ordinal), false, new[] { "apple", "APPLE" }, new[] { "apple", "APPLE" }); this.CustomSortTestHelper( ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase), false, new[] { "apple", "APPLE" }, new[] { "apple" }); } [Fact] public void ChangeUnorderedEqualityComparer() { var ordinalSet = ImmutableHashSet<string>.Empty .WithComparer(StringComparer.Ordinal) .Add("apple") .Add("APPLE"); Assert.Equal(2, ordinalSet.Count); // claimed count Assert.False(ordinalSet.Contains("aPpLe")); var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, ignoreCaseSet.Count); Assert.True(ignoreCaseSet.Contains("aPpLe")); } [Fact] public void ToSortTest() { var set = ImmutableHashSet<string>.Empty .Add("apple") .Add("APPLE"); var sorted = set.ToImmutableSortedSet(); CollectionAssertAreEquivalent(set.ToList(), sorted.ToList()); } [Fact] public void EnumeratorWithHashCollisionsTest() { var emptySet = this.EmptyTyped<int>().WithComparer(new BadHasher<int>()); this.EnumeratorTestHelper(emptySet, null, 3, 1, 5); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableHashSet.Create<int>().Add(5); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } [Fact] public void Create() { var comparer = StringComparer.OrdinalIgnoreCase; var set = ImmutableHashSet.Create<string>(); Assert.Equal(0, set.Count); Assert.Same(EqualityComparer<string>.Default, set.KeyComparer); set = ImmutableHashSet.Create<string>(comparer); Assert.Equal(0, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableHashSet.Create("a"); Assert.Equal(1, set.Count); Assert.Same(EqualityComparer<string>.Default, set.KeyComparer); set = ImmutableHashSet.Create(comparer, "a"); Assert.Equal(1, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableHashSet.Create("a", "b"); Assert.Equal(2, set.Count); Assert.Same(EqualityComparer<string>.Default, set.KeyComparer); set = ImmutableHashSet.Create(comparer, "a", "b"); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableHashSet.CreateRange((IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(EqualityComparer<string>.Default, set.KeyComparer); set = ImmutableHashSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); } /// <summary> /// Verifies the non-removal of an item that does not belong to the set, /// but which happens to have a colliding hash code with another value /// that *is* in the set. /// </summary> [Fact] public void RemoveValuesFromCollidedHashCode() { var set = ImmutableHashSet.Create<int>(new BadHasher<int>(), 5, 6); Assert.Same(set, set.Remove(2)); var setAfterRemovingFive = set.Remove(5); Assert.Equal(1, setAfterRemovingFive.Count); Assert.Equal(new[] { 6 }, setAfterRemovingFive); } [Fact] public void TryGetValueTest() { this.TryGetValueTestHelper(ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase)); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.Create<string>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableHashSet.Create<int>(1, 2, 3)); } protected override IImmutableSet<T> Empty<T>() { return ImmutableHashSet<T>.Empty; } protected ImmutableHashSet<T> EmptyTyped<T>() { return ImmutableHashSet<T>.Empty; } protected override ISet<T> EmptyMutable<T>() { #if NET40PLUS return new HashSet<T>(); #else return new SortedSet<T>(); #endif } #if !NET45PLUS internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set) { return ((ImmutableHashSet<T>)set).Root; } #endif /// <summary> /// Tests various aspects of an unordered set. /// </summary> /// <typeparam name="T">The type of element stored in the set.</typeparam> /// <param name="emptySet">The empty set.</param> /// <param name="value">A value that could be placed in the set.</param> /// <param name="comparer">The comparer used to obtain the empty set, if any.</param> private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IEqualityComparer<T> comparer) { Contract.Requires(emptySet != null); this.EmptyTestHelper(emptySet); Assert.Same(emptySet, emptySet.ToImmutableHashSet(comparer)); #if !NET45PLUS Assert.Same(comparer ?? EqualityComparer<T>.Default, ((IHashKeyCollection<T>)emptySet).KeyComparer); #endif if (comparer == null) { Assert.Same(emptySet, ImmutableHashSet<T>.Empty); } var reemptied = emptySet.Add(value).Clear(); Assert.Same(reemptied, reemptied.ToImmutableHashSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer."); } } }
namespace StockSharp.Algo { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.Localization; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// Subscription counter adapter. /// </summary> public class SubscriptionMessageAdapter : MessageAdapterWrapper { private class SubscriptionInfo { public ISubscriptionMessage Subscription { get; } public SubscriptionInfo(ISubscriptionMessage subscription) { Subscription = subscription ?? throw new ArgumentNullException(nameof(subscription)); } public SubscriptionStates State { get; set; } = SubscriptionStates.Stopped; public override string ToString() => Subscription.ToString(); } private readonly SyncObject _sync = new(); private readonly Dictionary<long, ISubscriptionMessage> _historicalRequests = new(); private readonly Dictionary<long, SubscriptionInfo> _subscriptionsById = new(); private readonly PairSet<long, long> _replaceId = new(); private readonly HashSet<long> _allSecIdChilds = new(); private readonly List<Message> _reMapSubscriptions = new(); /// <summary> /// Initializes a new instance of the <see cref="SubscriptionMessageAdapter"/>. /// </summary> /// <param name="innerAdapter">Inner message adapter.</param> public SubscriptionMessageAdapter(IMessageAdapter innerAdapter) : base(innerAdapter) { } /// <summary> /// Restore subscription on reconnect. /// </summary> /// <remarks> /// Error case like connection lost etc. /// </remarks> public bool IsRestoreSubscriptionOnErrorReconnect { get; set; } /// <inheritdoc /> protected override bool OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: return ProcessReset(message); case MessageTypes.OrderStatus: return ProcessOrderStatusMessage((OrderStatusMessage)message); case MessageTypes.ProcessSuspended: { Message[] reMapSubscriptions; lock (_sync) reMapSubscriptions = _reMapSubscriptions.CopyAndClear(); foreach (var reMapSubscription in reMapSubscriptions) base.OnSendInMessage(reMapSubscription); return true; } default: { if (message is ISubscriptionMessage subscrMsg) return ProcessInSubscriptionMessage(subscrMsg); else return base.OnSendInMessage(message); } } } private bool ProcessReset(Message message) { lock (_sync) { _historicalRequests.Clear(); _subscriptionsById.Clear(); _replaceId.Clear(); _allSecIdChilds.Clear(); _reMapSubscriptions.Clear(); } return base.OnSendInMessage(message); } private void ChangeState(SubscriptionInfo info, SubscriptionStates state) { info.State = info.State.ChangeSubscriptionState(state, info.Subscription.TransactionId, this, !_allSecIdChilds.Contains(info.Subscription.TransactionId)); } /// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { long TryReplaceOriginId(long id) { if (id == 0) return 0; lock (_sync) return _replaceId.TryGetValue(id, out var prevId) ? prevId : id; } var prevOriginId = 0L; var newOriginId = 0L; if (message is IOriginalTransactionIdMessage originIdMsg1) { newOriginId = originIdMsg1.OriginalTransactionId; prevOriginId = originIdMsg1.OriginalTransactionId = TryReplaceOriginId(newOriginId); } switch (message.Type) { case MessageTypes.SubscriptionResponse: { lock (_sync) { if (((SubscriptionResponseMessage)message).IsOk()) { if (_subscriptionsById.TryGetValue(prevOriginId, out var info)) { // no need send response after re-subscribe cause response was handled prev time if (_replaceId.ContainsKey(newOriginId)) { if (info.State != SubscriptionStates.Stopped) return; } else ChangeState(info, SubscriptionStates.Active); } } else { if (!_historicalRequests.Remove(prevOriginId)) { if (_subscriptionsById.TryGetAndRemove(prevOriginId, out var info)) { ChangeState(info, SubscriptionStates.Error); _replaceId.Remove(newOriginId); } } } } break; } case MessageTypes.SubscriptionOnline: { lock (_sync) { if (!_subscriptionsById.TryGetValue(prevOriginId, out var info)) break; if (_replaceId.ContainsKey(newOriginId)) { // no need send response after re-subscribe cause response was handled prev time if (info.State == SubscriptionStates.Online) return; } else ChangeState(info, SubscriptionStates.Online); } break; } case MessageTypes.SubscriptionFinished: { lock (_sync) { if (_replaceId.ContainsKey(newOriginId)) return; _historicalRequests.Remove(prevOriginId); if (_subscriptionsById.TryGetValue(newOriginId, out var info)) ChangeState(info, SubscriptionStates.Finished); } break; } default: { if (message is ISubscriptionIdMessage subscrMsg) { lock (_sync) { var ids = subscrMsg.GetSubscriptionIds(); if (ids.Length == 0) { if (subscrMsg.OriginalTransactionId != 0 && _historicalRequests.ContainsKey(subscrMsg.OriginalTransactionId)) subscrMsg.SetSubscriptionIds(subscriptionId: subscrMsg.OriginalTransactionId); } else { lock (_sync) { if (_replaceId.Count > 0) subscrMsg.SetSubscriptionIds(ids.Select(id => _replaceId.TryGetValue2(id) ?? id).ToArray()); } } } } break; } } base.OnInnerAdapterNewOutMessage(message); switch (message.Type) { case ExtendedMessageTypes.ReconnectingFinished: { ProcessSuspendedMessage supended = null; lock (_sync) { _replaceId.Clear(); _reMapSubscriptions.Clear(); _reMapSubscriptions.AddRange(_subscriptionsById.Values.Distinct().Where(i => i.State.IsActive()).Select(i => { var subscription = i.Subscription.TypedClone(); subscription.TransactionId = TransactionIdGenerator.GetNextId(); _replaceId.Add(subscription.TransactionId, i.Subscription.TransactionId); this.AddInfoLog("Re-map subscription: {0}->{1} for '{2}'.", i.Subscription.TransactionId, subscription.TransactionId, i.Subscription); return (Message)subscription; })); if (_reMapSubscriptions.Count > 0) supended = new ProcessSuspendedMessage(this); } if (supended != null) base.OnInnerAdapterNewOutMessage(supended); break; } } } /// <inheritdoc /> protected override void InnerAdapterNewOutMessage(Message message) { switch (message.Type) { case ExtendedMessageTypes.SubscriptionSecurityAll: { var allMsg = (SubscriptionSecurityAllMessage)message; lock (_sync) _allSecIdChilds.Add(allMsg.TransactionId); break; } } base.InnerAdapterNewOutMessage(message); } private bool ProcessOrderStatusMessage(OrderStatusMessage message) { if (message.HasOrderId()) return base.OnSendInMessage(message); return ProcessInSubscriptionMessage(message); } private bool ProcessInSubscriptionMessage(ISubscriptionMessage message) { return ProcessInSubscriptionMessage(message, message.DataType); } private bool ProcessInSubscriptionMessage(ISubscriptionMessage message, DataType dataType) { if (message == null) throw new ArgumentNullException(nameof(message)); if (dataType == null) throw new ArgumentNullException(nameof(dataType)); var transId = message.TransactionId; var isSubscribe = message.IsSubscribe; ISubscriptionMessage sendInMsg = null; Message[] sendOutMsgs = null; var isInfoLevel = true; lock (_sync) { if (isSubscribe) { if (_replaceId.ContainsKey(transId)) { sendInMsg = message; } else { var clone = message.TypedClone(); if (message.IsHistoryOnly()) _historicalRequests.Add(transId, clone); else _subscriptionsById.Add(transId, new SubscriptionInfo(clone)); sendInMsg = message; } isInfoLevel = !_allSecIdChilds.Contains(transId); } else { ISubscriptionMessage MakeUnsubscribe(ISubscriptionMessage m) { m = m.TypedClone(); m.IsSubscribe = false; m.OriginalTransactionId = m.TransactionId; m.TransactionId = transId; if (_replaceId.TryGetKey(m.OriginalTransactionId, out var oldOriginId)) m.OriginalTransactionId = oldOriginId; return m; } var originId = message.OriginalTransactionId; if (_historicalRequests.TryGetAndRemove(originId, out var subscription)) { sendInMsg = MakeUnsubscribe(subscription); } else if (_subscriptionsById.TryGetValue(originId, out var info)) { if (info.State.IsActive()) { // copy full subscription's details into unsubscribe request sendInMsg = MakeUnsubscribe(info.Subscription); ChangeState(info, SubscriptionStates.Stopped); } else this.AddWarningLog(LocalizedStrings.SubscriptionInState, originId, info.State); } else { sendOutMsgs = new[] { (Message)originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId))) }; } if (sendInMsg != null) isInfoLevel = !_allSecIdChilds.Contains(originId); } } var retVal = true; if (sendInMsg != null) { if (isInfoLevel) this.AddInfoLog("In: {0}", sendInMsg); else this.AddDebugLog("In: {0}", sendInMsg); retVal = base.OnSendInMessage((Message)sendInMsg); } if (sendOutMsgs != null) { foreach (var sendOutMsg in sendOutMsgs) { this.AddInfoLog("Out: {0}", sendOutMsg); RaiseNewOutMessage(sendOutMsg); } } return retVal; } /// <summary> /// Create a copy of <see cref="SubscriptionMessageAdapter"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() { return new SubscriptionMessageAdapter(InnerAdapter.TypedClone()) { IsRestoreSubscriptionOnErrorReconnect = IsRestoreSubscriptionOnErrorReconnect, }; } } }
namespace InControl { using System; using System.Collections.Generic; using UnityEngine; public class UnityInputDeviceManager : InputDeviceManager { const float deviceRefreshInterval = 1.0f; float deviceRefreshTimer = 0.0f; List<UnityInputDeviceProfileBase> systemDeviceProfiles = new List<UnityInputDeviceProfileBase>( UnityInputDeviceProfileList.Profiles.Length ); List<UnityInputDeviceProfileBase> customDeviceProfiles = new List<UnityInputDeviceProfileBase>(); string[] joystickNames; int lastJoystickCount; int lastJoystickHash; int joystickCount; int joystickHash; public UnityInputDeviceManager() { AddSystemDeviceProfiles(); // LoadDeviceProfiles(); QueryJoystickInfo(); AttachDevices(); } public override void Update( ulong updateTick, float deltaTime ) { deviceRefreshTimer += deltaTime; if (deviceRefreshTimer >= deviceRefreshInterval) { deviceRefreshTimer = 0.0f; QueryJoystickInfo(); if (JoystickInfoHasChanged) { Logger.LogInfo( "Change in attached Unity joysticks detected; refreshing device list." ); DetachDevices(); AttachDevices(); } } } void QueryJoystickInfo() { joystickNames = Input.GetJoystickNames(); joystickCount = joystickNames.Length; joystickHash = 17 * 31 + joystickCount; for (var i = 0; i < joystickCount; i++) { joystickHash = joystickHash * 31 + joystickNames[i].GetHashCode(); } } bool JoystickInfoHasChanged { get { return joystickHash != lastJoystickHash || joystickCount != lastJoystickCount; } } void AttachDevices() { AttachKeyboardDevices(); AttachJoystickDevices(); lastJoystickCount = joystickCount; lastJoystickHash = joystickHash; } void DetachDevices() { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { InputManager.DetachDevice( devices[i] ); } devices.Clear(); } public void ReloadDevices() { QueryJoystickInfo(); DetachDevices(); AttachDevices(); } void AttachDevice( UnityInputDevice device ) { devices.Add( device ); InputManager.AttachDevice( device ); } void AttachKeyboardDevices() { var deviceProfileCount = systemDeviceProfiles.Count; for (var i = 0; i < deviceProfileCount; i++) { var deviceProfile = systemDeviceProfiles[i]; if (deviceProfile.IsNotJoystick && deviceProfile.IsSupportedOnThisPlatform) { AttachDevice( new UnityInputDevice( deviceProfile ) ); } } } void AttachJoystickDevices() { try { for (var i = 0; i < joystickCount; i++) { DetectJoystickDevice( i + 1, joystickNames[i] ); } } catch (Exception e) { Logger.LogError( e.Message ); Logger.LogError( e.StackTrace ); } } bool HasAttachedDeviceWithJoystickId( int unityJoystickId ) { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var device = devices[i] as UnityInputDevice; if (device != null) { if (device.JoystickId == unityJoystickId) { return true; } } } return false; } void DetectJoystickDevice( int unityJoystickId, string unityJoystickName ) { if (HasAttachedDeviceWithJoystickId( unityJoystickId )) { return; } #if UNITY_PS4 if (unityJoystickName == "Empty") { // On PS4 console, disconnected controllers may have this name. return; } #endif if (unityJoystickName.IndexOf( "webcam", StringComparison.OrdinalIgnoreCase ) != -1) { // Unity thinks some webcams are joysticks. >_< return; } // PS4 controller only works properly as of Unity 4.5 if (InputManager.UnityVersion < new VersionInfo( 4, 5, 0, 0 )) { if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer #if !UNITY_5_4_OR_NEWER || Application.platform == RuntimePlatform.OSXWebPlayer #endif ) { if (unityJoystickName == "Unknown Wireless Controller") { // Ignore PS4 controller in Bluetooth mode on Mac since it connects but does nothing. return; } } } // As of Unity 4.6.3p1, empty strings on windows represent disconnected devices. if (InputManager.UnityVersion >= new VersionInfo( 4, 6, 3, 0 )) { if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer #if !UNITY_5_4_OR_NEWER || Application.platform == RuntimePlatform.WindowsWebPlayer #endif ) { if (String.IsNullOrEmpty( unityJoystickName )) { return; } } } UnityInputDeviceProfileBase deviceProfile = null; if (deviceProfile == null) { deviceProfile = customDeviceProfiles.Find( config => config.HasJoystickName( unityJoystickName ) ); } if (deviceProfile == null) { deviceProfile = systemDeviceProfiles.Find( config => config.HasJoystickName( unityJoystickName ) ); } if (deviceProfile == null) { deviceProfile = customDeviceProfiles.Find( config => config.HasLastResortRegex( unityJoystickName ) ); } if (deviceProfile == null) { deviceProfile = systemDeviceProfiles.Find( config => config.HasLastResortRegex( unityJoystickName ) ); } if (deviceProfile == null) { var joystickDevice = new UnityInputDevice( unityJoystickId, unityJoystickName ); AttachDevice( joystickDevice ); Debug.Log( "[InControl] Joystick " + unityJoystickId + ": \"" + unityJoystickName + "\"" ); Logger.LogWarning( "Device " + unityJoystickId + " with name \"" + unityJoystickName + "\" does not match any supported profiles and will be considered an unknown controller." ); return; } if (!deviceProfile.IsHidden) { var joystickDevice = new UnityInputDevice( deviceProfile, unityJoystickId, unityJoystickName ); AttachDevice( joystickDevice ); // Debug.Log( "[InControl] Joystick " + unityJoystickId + ": \"" + unityJoystickName + "\"" ); Logger.LogInfo( "Device " + unityJoystickId + " matched profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" ); } else { Logger.LogInfo( "Device " + unityJoystickId + " matching profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" + " is hidden and will not be attached." ); } } void AddSystemDeviceProfile( UnityInputDeviceProfile deviceProfile ) { if (deviceProfile.IsSupportedOnThisPlatform) { systemDeviceProfiles.Add( deviceProfile ); } } void AddSystemDeviceProfiles() { foreach (var typeName in UnityInputDeviceProfileList.Profiles) { var deviceProfile = (UnityInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) ); AddSystemDeviceProfile( deviceProfile ); } } /* public void AddDeviceProfile( UnityInputDeviceProfile deviceProfile ) { if (deviceProfile.IsSupportedOnThisPlatform) { customDeviceProfiles.Add( deviceProfile ); } } public void LoadDeviceProfiles() { LoadDeviceProfilesFromPath( CustomProfileFolder ); } public void LoadDeviceProfile( string data ) { var deviceProfile = UnityInputDeviceProfile.Load( data ); AddDeviceProfile( deviceProfile ); } public void LoadDeviceProfileFromFile( string filePath ) { var deviceProfile = UnityInputDeviceProfile.LoadFromFile( filePath ); AddDeviceProfile( deviceProfile ); } public void LoadDeviceProfilesFromPath( string rootPath ) { if (Directory.Exists( rootPath )) { var filePaths = Directory.GetFiles( rootPath, "*.json", SearchOption.AllDirectories ); foreach (var filePath in filePaths) { LoadDeviceProfileFromFile( filePath ); } } } internal static void DumpSystemDeviceProfiles() { var filePath = CustomProfileFolder; Directory.CreateDirectory( filePath ); foreach (var typeName in UnityInputDeviceProfileList.Profiles) { var deviceProfile = (UnityInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) ); var fileName = deviceProfile.GetType().Name + ".json"; deviceProfile.SaveToFile( filePath + "/" + fileName ); } } static string CustomProfileFolder { get { return Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ) + "/InControl/Profiles"; } } /**/ } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using CoreFXTestLibrary; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Test { public static class ParallelLoopResultTests { [Fact] public static void ForPLRTests() { ParallelLoopResult plr = Parallel.For(1, 0, delegate (int i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Empty", true, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Stop", false, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For-Break", false, 10); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For-Completion", true, null); } [Fact] public static void ForPLR64Tests() { ParallelLoopResult plr = Parallel.For(1L, 0L, delegate (long i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Empty", true, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Stop", false, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For64-Break", false, 10); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For64-Completion", true, null); } [Fact] public static void ForEachPLRTests() { Dictionary<string, string> dict = new Dictionary<string, string>(); ParallelLoopResult plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Empty", true, null); dict.Add("Apple", "Red"); dict.Add("Banana", "Yellow"); dict.Add("Pear", "Green"); dict.Add("Plum", "Red"); dict.Add("Grape", "Green"); dict.Add("Cherry", "Red"); dict.Add("Carrot", "Orange"); dict.Add("Eggplant", "Purple"); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Stop", false, null); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Break(); }); PLRcheck(plr, "ForEach-Break", false, 7); // right?? plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { //if(kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Complete", true, null); } [Fact] public static void PartitionerForEachPLRTests() { // // Now try testing Partitionable, OrderablePartitionable // List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); MyPartitioner<int> mp = new MyPartitioner<int>(intlist); ParallelLoopResult plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { if (item == 0) ps.Stop(); }); PLRcheck(plr, "Partitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { }); PLRcheck(plr, "Partitioner-ForEach-Complete", true, null); } [Fact] public static void OrderablePartitionerForEachTests() { List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); OrderablePartitioner<int> mop = Partitioner.Create(intlist, true); ParallelLoopResult plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Stop(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Break(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Break", false, 2); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { }); PLRcheck(plr, "OrderablePartitioner-ForEach-Complete", true, null); } private static void PLRcheck(ParallelLoopResult plr, string ttype, bool shouldComplete, Int32? expectedLBI) { Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(expectedLBI, plr.LowestBreakIteration); } // Generalized test for testing For-loop results private static void ForPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForPLRTest( Action<int, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0, 1, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("For-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { string LBIval = "null"; if (plr.LowestBreakIteration != null) LBIval = plr.LowestBreakIteration.Value.ToString(); Logger.LogInformation("For-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, LBIval); } } catch (OperationCanceledException oce) { if (!shouldCancel) { Logger.LogInformation("For-PLRTest -- {0}: > FAILED -- got unexpected OCE: {1}.", desc, oce.Message); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("For-PLRTest -- {0}: > failed -- unexpected exception from loop. Error: {1}", desc, e.ToString()); } } } // ... and a 64-bit version private static void For64PLRTest( Action<long, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { For64PLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void For64PLRTest( Action<long, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0L, 1L, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("For64-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { string LBIval = "null"; if (plr.LowestBreakIteration != null) LBIval = plr.LowestBreakIteration.Value.ToString(); Logger.LogInformation("For64-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, LBIval); } } catch (OperationCanceledException) { if (!shouldCancel) { Logger.LogInformation("For64-PLRTest -- {0} > FAILED -- got unexpected OCE.", desc); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("For64-PLRTest -- {0}: > failed -- unexpected exception from loop. Error: {1} ", desc, e.ToString()); } } } // Generalized test for testing ForEach-loop results private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForEachPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); try { ParallelLoopResult plr = Parallel.ForEach(dict, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (OperationCanceledException oce) { if (!shouldCancel) { Logger.LogInformation("ForEach-PLRTest -- {0} > FAILED -- got unexpected OCE. Exception: {1}", desc, oce); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Generalized test for testing Partitioner ForEach-loop results private static void PartitionerForEachPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); MyPartitioner<int> mp = new MyPartitioner<int>(list); try { ParallelLoopResult plr = Parallel.ForEach(mp, body); if (excExpected) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0}: > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0} > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Generalized test for testing OrderablePartitioner ForEach-loop results private static void OrderablePartitionerForEachPLRTest( Action<int, ParallelLoopState, long> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); OrderablePartitioner<int> mop = Partitioner.Create(list, true); try { ParallelLoopResult plr = Parallel.ForEach(mop, body); if (excExpected) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Perform tests on various combinations of Stop()/Break() [Fact] public static void SimultaneousStopBreakTests() { // // Test 32-bit Parallel.For() // ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); // // Test "vanilla" Parallel.ForEach // ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ Partitioner // PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ OrderablePartitioner // OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test 64-bit Parallel.For // For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop after Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break after Cancel", false, false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); } #region Helper Classes and Methods // // Utility class for use w/ Partitioner-style ForEach testing. // Created by Cindy Song. // public class MyPartitioner<TSource> : Partitioner<TSource> { private IList<TSource> _data; public MyPartitioner(IList<TSource> data) { _data = data; } override public IList<IEnumerator<TSource>> GetPartitions(int partitionCount) { if (partitionCount <= 0) { throw new ArgumentOutOfRangeException("partitionCount"); } IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount]; IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = Partitioner.Create(_data, true).GetOrderableDynamicPartitions(); for (int i = 0; i < partitionCount; i++) { partitions[i] = DropIndices(partitionEnumerable.GetEnumerator()); } return partitions; } override public IEnumerable<TSource> GetDynamicPartitions() { return DropIndices(Partitioner.Create(_data, true).GetOrderableDynamicPartitions()); } private static IEnumerable<TSource> DropIndices(IEnumerable<KeyValuePair<long, TSource>> source) { foreach (KeyValuePair<long, TSource> pair in source) { yield return pair.Value; } } private static IEnumerator<TSource> DropIndices(IEnumerator<KeyValuePair<long, TSource>> source) { while (source.MoveNext()) { yield return source.Current.Value; } } public override bool SupportsDynamicPartitions { get { return true; } } } #endregion } }
// *********************************************************************** // Copyright (c) 2017 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; using System.Collections.Generic; namespace NUnit.Framework.Internal { #region Mock types namespace DifferingNamespace1 { class Dummy { internal readonly int value; public Dummy(int value) { this.value = value; } public override string ToString() { return "Dummy " + value; } } class DummyGeneric<T> { public DummyGeneric(T obj) { } } } namespace DifferingNamespace2 { class Dummy { internal readonly int value; public Dummy(int value) { this.value = value; } public override string ToString() { return "Dummy " + value; } } } namespace A { class GenA<T> { } class GenB<T> { } class GenC<T, R> { } namespace B { class GenX<T> { } class GenY<T> { } } } namespace B { class GenA<T> { } class GenB<T> { } class GenC<T, R> { } namespace B { class GenX<T> { } class GenY<T> { } } } #endregion public class TypeNameDifferenceTests { #region Mock types class Dummy { internal readonly int value; public Dummy(int value) { this.value = value; } public override string ToString() { return "Dummy " + value; } } class Dummy1 { internal readonly int value; public Dummy1(int value) { this.value = value; } public override string ToString() { return "Dummy " + value; } } class DummyGenericClass<T> { private readonly object _obj; public DummyGenericClass(object obj) { _obj = obj; } public override string ToString() { return _obj.ToString(); } } #endregion TypeNameDifferenceResolver _differenceGetter; [SetUp] public void TestSetup() { _differenceGetter = new TypeNameDifferenceResolver(); } private void TestShortenedNameDifference(object objA, object objB, string expectedA, string expectedB) { string actualA, actualB; _differenceGetter.ResolveTypeNameDifference( objA, objB, out actualA, out actualB); Assert.That(actualA, Is.EqualTo(expectedA)); Assert.That(actualB, Is.EqualTo(expectedB)); } [Test] public void TestResolveTypeNameDifferenceNonGenericDifferingTypes() { TestShortenedNameDifference( new Dummy(1), new Dummy1(1), "TypeNameDifferenceTests+Dummy", "TypeNameDifferenceTests+Dummy1"); } [Test] public void TestResolveTypeNameDifferenceNonGenericNonDifferingTypes() { TestShortenedNameDifference( new Dummy(1), new Dummy(1), "TypeNameDifferenceTests+Dummy", "TypeNameDifferenceTests+Dummy"); } [Test] public void TestResolveTypeNameDifferenceNonGenericNonDifferingTypesSingularDiffNamespace() { TestShortenedNameDifference( new DifferingNamespace1.Dummy(1), new Dummy(1), "Dummy", "TypeNameDifferenceTests+Dummy"); } [Test] public void TestResolveTypeNameDifferenceNonGenericNonDifferingTypesBothDiffNamespace() { TestShortenedNameDifference( new DifferingNamespace1.Dummy(1), new DifferingNamespace2.Dummy(1), "DifferingNamespace1.Dummy", "DifferingNamespace2.Dummy"); } [Test] public void TestResolveTypeNameDifferenceGeneric() { TestShortenedNameDifference( new DummyGenericClass<Dummy1>(new Dummy(1)), new DummyGenericClass<Dummy>(new Dummy(1)), "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy1]", "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy]"); } [Test] public void TestResolveTypeNameDifferenceGenericDifferingNamespaces() { TestShortenedNameDifference( new DummyGenericClass<Dummy>(new Dummy(1)), new DummyGenericClass<DifferingNamespace1.Dummy>(new DifferingNamespace1.Dummy(1)), "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy]", "TypeNameDifferenceTests+DummyGenericClass`1[Dummy]"); TestShortenedNameDifference( new DummyGenericClass<DifferingNamespace1.Dummy>(new DifferingNamespace1.Dummy(1)), new DummyGenericClass<Dummy>(new Dummy(1)), "TypeNameDifferenceTests+DummyGenericClass`1[Dummy]", "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy]"); TestShortenedNameDifference( new DummyGenericClass<DifferingNamespace1.Dummy>(new DifferingNamespace1.Dummy(1)), new DummyGenericClass<DifferingNamespace2.Dummy>(new DifferingNamespace2.Dummy(1)), "TypeNameDifferenceTests+DummyGenericClass`1[DifferingNamespace1.Dummy]", "TypeNameDifferenceTests+DummyGenericClass`1[DifferingNamespace2.Dummy]"); } [Test] public void TestResolveTypeNameDifferenceGenericDifferentAmountGenericParams() { TestShortenedNameDifference( new DummyGenericClass<Dummy>(new Dummy(1)), new KeyValuePair<int, string>(1, ""), "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy]", "KeyValuePair`2[Int32,String]"); TestShortenedNameDifference( new KeyValuePair<int, string>(1, ""), new DummyGenericClass<Dummy>(new Dummy(1)), "KeyValuePair`2[Int32,String]", "TypeNameDifferenceTests+DummyGenericClass`1[TypeNameDifferenceTests+Dummy]"); } [Test] public void TestResolveNameDifferenceOneIsGenericOtherIsNot() { TestShortenedNameDifference( new DummyGenericClass<Dummy>(new Dummy(1)), new Dummy(1), "DummyGenericClass`1[Dummy]", "Dummy"); TestShortenedNameDifference( new Dummy(1), new DummyGenericClass<Dummy>(new Dummy(1)), "Dummy", "DummyGenericClass`1[Dummy]"); TestShortenedNameDifference( new KeyValuePair<string, int>("str", 0), new Dummy(1), "KeyValuePair`2[String,Int32]", "Dummy"); TestShortenedNameDifference( new Dummy(1), new KeyValuePair<string, int>("str", 0), "Dummy", "KeyValuePair`2[String,Int32]"); TestShortenedNameDifference( new Dummy(1), new A.GenA<B.GenA<B.GenC<string, int>>>(), "Dummy", "GenA`1[GenA`1[GenC`2[String,Int32]]]"); TestShortenedNameDifference( new A.GenA<B.GenA<B.GenC<string, int>>>(), new Dummy(1), "GenA`1[GenA`1[GenC`2[String,Int32]]]", "Dummy"); } [Test] public void TestNestedGenerics() { TestShortenedNameDifference( new DifferingNamespace1.DummyGeneric<List<string>>(new List<string>()), new DifferingNamespace1.DummyGeneric<IEnumerable<string>>(new List<string>()), "DummyGeneric`1[List`1[String]]", "DummyGeneric`1[IEnumerable`1[String]]"); TestShortenedNameDifference( new DifferingNamespace1.DummyGeneric<IEnumerable<string>>(new List<string>()), new DifferingNamespace1.DummyGeneric<List<string>>(new List<string>()), "DummyGeneric`1[IEnumerable`1[String]]", "DummyGeneric`1[List`1[String]]"); TestShortenedNameDifference( new DifferingNamespace1.DummyGeneric<KeyValuePair<DifferingNamespace1.Dummy, DifferingNamespace2.Dummy>>(new KeyValuePair<DifferingNamespace1.Dummy, DifferingNamespace2.Dummy>()), new DifferingNamespace1.DummyGeneric<KeyValuePair<DifferingNamespace2.Dummy, DifferingNamespace1.Dummy>>(new KeyValuePair<DifferingNamespace2.Dummy, DifferingNamespace1.Dummy>()), "DummyGeneric`1[KeyValuePair`2[DifferingNamespace1.Dummy,DifferingNamespace2.Dummy]]", "DummyGeneric`1[KeyValuePair`2[DifferingNamespace2.Dummy,DifferingNamespace1.Dummy]]"); TestShortenedNameDifference( new DifferingNamespace1.DummyGeneric<KeyValuePair<DifferingNamespace2.Dummy, DifferingNamespace1.Dummy>>(new KeyValuePair<DifferingNamespace2.Dummy, DifferingNamespace1.Dummy>()), new DifferingNamespace1.DummyGeneric<KeyValuePair<DifferingNamespace1.Dummy, DifferingNamespace2.Dummy>>(new KeyValuePair<DifferingNamespace1.Dummy, DifferingNamespace2.Dummy>()), "DummyGeneric`1[KeyValuePair`2[DifferingNamespace2.Dummy,DifferingNamespace1.Dummy]]", "DummyGeneric`1[KeyValuePair`2[DifferingNamespace1.Dummy,DifferingNamespace2.Dummy]]"); TestShortenedNameDifference( new A.GenA<A.B.GenX<int>>(), new B.GenA<A.B.GenX<short>>(), "A.GenA`1[GenX`1[Int32]]", "B.GenA`1[GenX`1[Int16]]"); TestShortenedNameDifference( new B.GenA<A.B.GenX<short>>(), new A.GenA<A.B.GenX<int>>(), "B.GenA`1[GenX`1[Int16]]", "A.GenA`1[GenX`1[Int32]]"); TestShortenedNameDifference( new A.GenC<int, string>(), new B.GenC<int, A.GenA<string>>(), "A.GenC`2[Int32,String]", "B.GenC`2[Int32,GenA`1[String]]"); TestShortenedNameDifference( new A.GenA<A.GenC<string, int>>(), new B.GenC<A.GenA<List<int>>, B.GenC<string, int>>(), "GenA`1[GenC`2[String,Int32]]", "GenC`2[GenA`1[List`1[Int32]],GenC`2[String,Int32]]"); TestShortenedNameDifference( new B.GenC<A.GenA<List<int>>, B.GenC<string, int>>(), new A.GenA<A.GenC<string, int>>(), "GenC`2[GenA`1[List`1[Int32]],GenC`2[String,Int32]]", "GenA`1[GenC`2[String,Int32]]"); TestShortenedNameDifference( new B.GenC<A.GenA<List<int>>, B.GenC<string, B.GenC<string, int>>>(), new A.GenA<B.GenC<string, B.GenC<string,int>>>(), "GenC`2[GenA`1[List`1[Int32]],GenC`2[String,GenC`2[String,Int32]]]", "GenA`1[GenC`2[String,GenC`2[String,Int32]]]"); TestShortenedNameDifference( new A.GenA<B.GenC<string, B.GenC<string, int>>>(), new B.GenC<A.GenA<List<int>>, B.GenC<string, B.GenC<string, int>>>(), "GenA`1[GenC`2[String,GenC`2[String,Int32]]]", "GenC`2[GenA`1[List`1[Int32]],GenC`2[String,GenC`2[String,Int32]]]"); } [Test] public void TestIsObjectInstanceGeneric() { var notGeneric = new DifferingNamespace1.Dummy(1); Assert.False(_differenceGetter.IsTypeGeneric(notGeneric.GetType())); var generic = new DifferingNamespace1.DummyGeneric<DifferingNamespace1.Dummy>(new DifferingNamespace1.Dummy(1)); Assert.That(_differenceGetter.IsTypeGeneric(generic.GetType())); } [Test] public void TestGetTopLevelGenericName() { var generic = new DifferingNamespace1.DummyGeneric<int>(1).GetType(); var expected = "NUnit.Framework.Internal.DifferingNamespace1.DummyGeneric`1"; var actual = _differenceGetter.GetGenericTypeName(generic); Assert.AreEqual(expected, actual); } [Test] public void TestGetTopLevelGenericNameThrowsWhenNotGeneric() { var notGeneric = new object().GetType(); Assert.Throws<ArgumentException>(() => _differenceGetter.GetGenericTypeName(notGeneric)); } [Test] public void TestReconstructShortenedGenericTypeName() { var expected = "KeyValuePair`2[String,Int32]"; var actual = _differenceGetter.ReconstructGenericTypeName( "KeyValuePair`2", new List<string>() { "String", "Int32" }); Assert.AreEqual(expected, actual); } private void TestShortenTypeNames(object objA, object objB, string shortenedA, string shortenedB) { string actualA, actualB; _differenceGetter.ShortenTypeNames(objA.GetType(), objB.GetType(), out actualA, out actualB); Assert.AreEqual(shortenedA, actualA); Assert.AreEqual(shortenedB, actualB); } [Test] public void TestShortenTypeNamesDifferingNamespace() { TestShortenTypeNames( new DifferingNamespace1.Dummy(1), new DifferingNamespace2.Dummy(1), "DifferingNamespace1.Dummy", "DifferingNamespace2.Dummy"); } private void TestShortenGenericTopLevelTypeNames(object objA, object objB, string shortenedA, string shortenedB) { string actualA, actualB; _differenceGetter.GetShortenedGenericTypes(objA.GetType(), objB.GetType(), out actualA, out actualB); Assert.AreEqual(shortenedA, actualA); Assert.AreEqual(shortenedB, actualB); } [Test] public void TestShortenGenericTopLevelTypes() { TestShortenGenericTopLevelTypeNames( new A.GenA<int>(), new B.GenA<int>(), "A.GenA`1", "B.GenA`1"); TestShortenGenericTopLevelTypeNames( new KeyValuePair<string, int>(), new KeyValuePair<int, string>(), "KeyValuePair`2", "KeyValuePair`2"); } private void TestFullyShortenTypeName(Type type, string expectedOutput) { string actual = _differenceGetter.FullyShortenTypeName(type); Assert.AreEqual(expectedOutput, actual); } [Test] public void TestFullyShortenTypeName() { TestFullyShortenTypeName( new A.GenA<A.GenA<int>>().GetType(), "GenA`1[GenA`1[Int32]]"); TestFullyShortenTypeName( new A.GenC<B.GenA<int>, A.GenA<int>>().GetType(), "GenC`2[GenA`1[Int32],GenA`1[Int32]]"); } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copysecond (c) 2017 Atif Aziz. All seconds 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using System.Linq; static partial class MoreEnumerable { /// <summary> /// Performs a left outer join on two homogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a left /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> LeftJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TSource, TResult> bothSelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.LeftJoin(second, keySelector, firstSelector, bothSelector, null); } /// <summary> /// Performs a left outer join on two homogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a left /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> LeftJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TSource, TResult> bothSelector, IEqualityComparer<TKey> comparer) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.LeftJoin(second, keySelector, keySelector, firstSelector, bothSelector, comparer); } /// <summary> /// Performs a left outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a left /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> LeftJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TFirst, TSecond, TResult> bothSelector) => first.LeftJoin(second, firstKeySelector, secondKeySelector, firstSelector, bothSelector, null); /// <summary> /// Performs a left outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a left /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> LeftJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TFirst, TSecond, TResult> bothSelector, IEqualityComparer<TKey> comparer) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector)); if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector)); if (firstSelector == null) throw new ArgumentNullException(nameof(firstSelector)); if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector)); KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v); return // TODO replace KeyValuePair<,> with (,) for clarity from j in first.GroupJoin(second, firstKeySelector, secondKeySelector, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comparer) from s in j.Value.DefaultIfEmpty() select s.Key ? bothSelector(j.Key, s.Value) : firstSelector(j.Key); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Reflection; namespace System.Dynamic { /// <summary> /// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding. /// </summary> public class DynamicMetaObject { private readonly Expression _expression; private readonly BindingRestrictions _restrictions; private readonly object _value; private readonly bool _hasValue; /// <summary> /// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read only. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public static readonly DynamicMetaObject[] EmptyMetaObjects = Array.Empty<DynamicMetaObject>(); /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions) { ContractUtils.RequiresNotNull(expression, "expression"); ContractUtils.RequiresNotNull(restrictions, "restrictions"); _expression = expression; _restrictions = restrictions; } /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value) : this(expression, restrictions) { _value = value; _hasValue = true; } /// <summary> /// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process. /// </summary> public Expression Expression { get { return _expression; } } /// <summary> /// The set of binding restrictions under which the binding is valid. /// </summary> public BindingRestrictions Restrictions { get { return _restrictions; } } /// <summary> /// The runtime value represented by this <see cref="DynamicMetaObject"/>. /// </summary> public object Value { get { return _value; } } /// <summary> /// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value. /// </summary> public bool HasValue { get { return _hasValue; } } /// <summary> /// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it. /// </summary> public Type RuntimeType { get { if (_hasValue) { Type ct = Expression.Type; // valuetype at compile tyme, type cannot change. if (ct.GetTypeInfo().IsValueType) { return ct; } if (_value != null) { return _value.GetType(); } else { return null; } } else { return null; } } } /// <summary> /// Gets the limit type of the <see cref="DynamicMetaObject"/>. /// </summary> /// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks> public Type LimitType { get { return RuntimeType ?? Expression.Type; } } /// <summary> /// Performs the binding of the dynamic conversion operation. /// </summary> /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindConvert(ConvertBinder binder) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackConvert(this); } /// <summary> /// Performs the binding of the dynamic get member operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackGetMember(this); } /// <summary> /// Performs the binding of the dynamic set member operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackSetMember(this, value); } /// <summary> /// Performs the binding of the dynamic delete member operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackDeleteMember(this); } /// <summary> /// Performs the binding of the dynamic get index operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackGetIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic set index operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackSetIndex(this, indexes, value); } /// <summary> /// Performs the binding of the dynamic delete index operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackDeleteIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic invoke member operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackInvokeMember(this, args); } /// <summary> /// Performs the binding of the dynamic invoke operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackInvoke(this, args); } /// <summary> /// Performs the binding of the dynamic create instance operation. /// </summary> /// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackCreateInstance(this, args); } /// <summary> /// Performs the binding of the dynamic unary operation. /// </summary> /// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackUnaryOperation(this); } /// <summary> /// Performs the binding of the dynamic binary operation. /// </summary> /// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { ContractUtils.RequiresNotNull(binder, "binder"); return binder.FallbackBinaryOperation(this, arg); } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns>The list of dynamic member names.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual IEnumerable<string> GetDynamicMemberNames() { return Array.Empty<string>(); } /// <summary> /// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances. /// </summary> /// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param> /// <returns>The array of expressions.</returns> internal static Expression[] GetExpressions(DynamicMetaObject[] objects) { ContractUtils.RequiresNotNull(objects, "objects"); Expression[] res = new Expression[objects.Length]; for (int i = 0; i < objects.Length; i++) { DynamicMetaObject mo = objects[i]; ContractUtils.RequiresNotNull(mo, "objects"); Expression expr = mo.Expression; ContractUtils.RequiresNotNull(expr, "objects"); res[i] = expr; } return res; } /// <summary> /// Creates a meta-object for the specified object. /// </summary> /// <param name="value">The object to get a meta-object for.</param> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <returns> /// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain, /// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object /// with no restrictions is created and returned. /// </returns> public static DynamicMetaObject Create(object value, Expression expression) { ContractUtils.RequiresNotNull(expression, "expression"); IDynamicMetaObjectProvider ido = value as IDynamicMetaObjectProvider; if (ido != null) { var idoMetaObject = ido.GetMetaObject(expression); if (idoMetaObject == null || !idoMetaObject.HasValue || idoMetaObject.Value == null || (object)idoMetaObject.Expression != (object)expression) { throw Error.InvalidMetaObjectCreated(ido.GetType()); } return idoMetaObject; } else { return new DynamicMetaObject(expression, BindingRestrictions.Empty, value); } } } }
//------------------------------------------------------------------------------ // <copyright file="FormsAuthenticationModule.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * FormsAuthenticationModule class * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web.Security { using System.Globalization; using System.Web; using System.Text; using System.Web.Configuration; using System.Web.Caching; using System.Web.Handlers; using System.Collections; using System.Web.Util; using System.Security.Principal; using System.Security.Permissions; using System.Web.Management; public sealed class FormsAuthenticationModule : IHttpModule { // Config values private static bool _fAuthChecked; private static bool _fAuthRequired; internal static bool FormsAuthRequired { get { return _fAuthRequired; } } private bool _fOnEnterCalled; private FormsAuthenticationEventHandler _eventHandler; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.Security.FormsAuthenticationModule'/> /// class. /// </para> /// </devdoc> [SecurityPermission(SecurityAction.Demand, Unrestricted=true)] public FormsAuthenticationModule() { } /// <devdoc> /// This is a Global.asax event which must be /// named FormsAuthenticate_OnAuthenticate event. It's used by advanced users to /// customize cookie authentication. /// </devdoc> public event FormsAuthenticationEventHandler Authenticate { add { _eventHandler += value; } remove { _eventHandler -= value; } } public void Dispose() { } public void Init(HttpApplication app) { // authentication is an app level setting only // so we can read app config early on in an attempt to try and // skip wiring up event delegates if (!_fAuthChecked) { _fAuthRequired = (AuthenticationConfig.Mode == AuthenticationMode.Forms); _fAuthChecked = true; } if (_fAuthRequired) { // initialize if mode is forms auth FormsAuthentication.Initialize(); app.AuthenticateRequest += new EventHandler(this.OnEnter); app.EndRequest += new EventHandler(this.OnLeave); } } //////////////////////////////////////////////////////////// // OnAuthenticate: Forms Authentication modules can override // this method to create a Forms IPrincipal object from // a WindowsIdentity private void OnAuthenticate(FormsAuthenticationEventArgs e) { HttpCookie cookie = null; //////////////////////////////////////////////////////////// // Step 1: If there are event handlers, invoke the handlers if (_eventHandler != null) _eventHandler(this, e); //////////////////////////////////////////////////////////// // Step 2: Check if the event handler created a user-object if (e.Context.User != null) { // do nothing because someone else authenticated return; } if (e.User != null) { // the event handler created a user e.Context.SetPrincipalNoDemand(e.User); return; } //////////////////////////////////////////////////////////// // Step 3: Extract the cookie and create a ticket from it bool cookielessTicket = false; FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket); //////////////////////////////////////////////////////////// // Step 4: See if the ticket was created: No => exit immediately if (ticket == null || ticket.Expired) return; //////////////////////////////////////////////////////////// // Step 5: Renew the ticket FormsAuthenticationTicket ticket2 = ticket; if (FormsAuthentication.SlidingExpiration) ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); //////////////////////////////////////////////////////////// // Step 6: Create a user object for the ticket e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0])); //////////////////////////////////////////////////////////// // Step 7: Browser does not send us the correct cookie-path // Update the cookie to show the correct path if (!cookielessTicket && !ticket2.CookiePath.Equals("/")) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { cookie.Path = ticket2.CookiePath; } } //////////////////////////////////////////////////////////// // Step 8: If the ticket was renewed, save the ticket in the cookie if (ticket2 != ticket) { if(cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1) { FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket2.Version, ticket2.Name, ticket2.IssueDateUtc, ticket2.ExpirationUtc, ticket2.IsPersistent, ticket2.UserData, "/"); ticket2 = tempTicket; } String strEnc = FormsAuthentication.Encrypt(ticket2, !cookielessTicket); if (cookielessTicket) { e.Context.CookielessHelper.SetCookieValue('F', strEnc); e.Context.Response.Redirect(e.Context.Request.RawUrl); } else { if (cookie != null) cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc); cookie.Path = ticket2.CookiePath; } if (ticket2.IsPersistent) cookie.Expires = ticket2.Expiration; cookie.Value = strEnc; cookie.Secure = FormsAuthentication.RequireSSL; cookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) cookie.Domain = FormsAuthentication.CookieDomain; e.Context.Response.Cookies.Remove(cookie.Name); e.Context.Response.Cookies.Add(cookie); } } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> private void OnEnter(Object source, EventArgs eventArgs) { _fOnEnterCalled = true; HttpApplication app; HttpContext context; app = (HttpApplication)source; context = app.Context; #if DBG Trace("*******************Request path: " + context.Request.RawUrl); #endif //////////////////////////////////////////////////////// // Step 2: Call OnAuthenticate virtual method to create // an IPrincipal for this request OnAuthenticate( new FormsAuthenticationEventArgs(context) ); //////////////////////////////////////////////////////// // Skip AuthZ if accessing the login page // We do this here to force the cookieless helper to fish out and // remove the token from the URL if it's present there. CookielessHelperClass cookielessHelper = context.CookielessHelper; if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl)) { context.SetSkipAuthorizationNoDemand(true, false /*managedOnly*/); cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode); } if (!context.SkipAuthorization) { context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false /*managedOnly*/); } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> private void OnLeave(Object source, EventArgs eventArgs) { if (_fOnEnterCalled) _fOnEnterCalled = false; else return; // no need to continue if we skipped OnEnter HttpApplication app; HttpContext context; app = (HttpApplication)source; context = app.Context; //////////////////////////////////////////////////////////// // Step 1: Check if we are using cookie authentication and // if authentication failed if (context.Response.StatusCode != 401) return; //////////////////////////////////////////////////////////// // Change 401 to a redirect to login page // Don't do it if the redirect is suppressed for this response if (context.Response.SuppressFormsAuthenticationRedirect) { return; } // Don't do it if already there is ReturnUrl, already being redirected, // to avoid infinite redirection loop String strUrl = context.Request.RawUrl; if (strUrl.IndexOf("?" + FormsAuthentication.ReturnUrlVar + "=", StringComparison.Ordinal) != -1 || strUrl.IndexOf("&" + FormsAuthentication.ReturnUrlVar + "=", StringComparison.Ordinal) != -1) { return; } //////////////////////////////////////////////////////////// // Step 2: Get the complete url to the login-page String loginUrl = null; if (!String.IsNullOrEmpty(FormsAuthentication.LoginUrl)) loginUrl = AuthenticationConfig.GetCompleteLoginUrl(context, FormsAuthentication.LoginUrl); //////////////////////////////////////////////////////////// // Step 3: Check if we have a valid url to the login-page if (loginUrl == null || loginUrl.Length <= 0) throw new HttpException(SR.GetString(SR.Auth_Invalid_Login_Url)); //////////////////////////////////////////////////////////// // Step 4: Construct the redirect-to url String strRedirect; int iIndex; CookielessHelperClass cookielessHelper; // if(context.Request.Browser["isMobileDevice"] == "true") { // //__redir=1 is marker for devices that post on redirect // if(strUrl.IndexOf("__redir=1") >= 0) { // strUrl = SanitizeUrlForCookieless(strUrl); // } // else { // if(strUrl.IndexOf('?') >= 0) // strSep = "&"; // else // strSep = "?"; // strUrl = SanitizeUrlForCookieless(strUrl + strSep + "__redir=1"); // } // } // Create the CookielessHelper class to rewrite the path, if needed. cookielessHelper = context.CookielessHelper; if (loginUrl.IndexOf('?') >= 0) { loginUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(loginUrl, FormsAuthentication.ReturnUrlVar); strRedirect = loginUrl + "&" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding); } else { strRedirect = loginUrl + "?" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding); } //////////////////////////////////////////////////////////// // Step 5: Add the query-string from the current url iIndex = strUrl.IndexOf('?'); if (iIndex >= 0 && iIndex < strUrl.Length - 1) { strRedirect += "&" + strUrl.Substring(iIndex + 1); } cookielessHelper.SetCookieValue('F', null); // remove old ticket if present cookielessHelper.RedirectWithDetectionIfRequired(strRedirect, FormsAuthentication.CookieMode); //////////////////////////////////////////////////////////// // Step 6: Do the redirect context.Response.Redirect(strRedirect, false); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Private method for decrypting a cookie private static FormsAuthenticationTicket ExtractTicketFromCookie(HttpContext context, String name, out bool cookielessTicket) { FormsAuthenticationTicket ticket = null; string encValue = null; bool ticketExpired = false; bool badTicket = false; try { try { //////////////////////////////////////////////////////////// // Step 0: Check if we should use cookieless cookielessTicket = CookielessHelperClass.UseCookieless(context, false, FormsAuthentication.CookieMode); //////////////////////////////////////////////////////////// // Step 1: Check URI/cookie for ticket if (cookielessTicket) { encValue = context.CookielessHelper.GetCookieValue('F'); } else { HttpCookie cookie = context.Request.Cookies[name]; if (cookie != null) { encValue = cookie.Value; } } //////////////////////////////////////////////////////////// // Step 2: Decrypt encrypted ticket if (encValue != null && encValue.Length > 1) { try { ticket = FormsAuthentication.Decrypt(encValue); } catch { if (cookielessTicket) context.CookielessHelper.SetCookieValue('F', null); else context.Request.Cookies.Remove(name); badTicket = true; //throw; } if (ticket == null) { badTicket = true; } if (ticket != null && !ticket.Expired) { if (cookielessTicket || !FormsAuthentication.RequireSSL || context.Request.IsSecureConnection) // Make sure it is NOT a secure cookie over an in-secure connection return ticket; // Found valid ticket } if (ticket != null && ticket.Expired) { ticketExpired = true; } // Step 2b: Remove expired/bad ticket ticket = null; if (cookielessTicket) context.CookielessHelper.SetCookieValue('F', null); else context.Request.Cookies.Remove(name); } //////////////////////////////////////////////////////////// // Step 3: Look in QueryString if (FormsAuthentication.EnableCrossAppRedirects) { encValue = context.Request.QueryString[name]; if (encValue != null && encValue.Length > 1) { if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect) cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure try { ticket = FormsAuthentication.Decrypt(encValue); } catch { badTicket = true; //throw; } if (ticket == null) { badTicket = true; } } // Step 3b: Look elsewhere in the request (i.e. posted body) if (ticket == null || ticket.Expired) { encValue = context.Request.Form[name]; if (encValue != null && encValue.Length > 1) { if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect) cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure try { ticket = FormsAuthentication.Decrypt(encValue); } catch { badTicket = true; //throw; } if (ticket == null) { badTicket = true; } } } } if (ticket == null || ticket.Expired) { if (ticket != null && ticket.Expired) ticketExpired = true; return null; // not found! Exit with null } if (FormsAuthentication.RequireSSL && !context.Request.IsSecureConnection) // Bad scenario: valid ticket over non-SSL throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie)); //////////////////////////////////////////////////////////// // Step 4: Create the cookie/URI value if (cookielessTicket) { if (ticket.CookiePath != "/") { FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc, ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData, "/"); ticket = tempTicket; encValue = FormsAuthentication.Encrypt(ticket); } context.CookielessHelper.SetCookieValue('F', encValue); string strUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(context.Request.RawUrl, name); context.Response.Redirect(strUrl); } else { HttpCookie cookie = new HttpCookie(name, encValue); cookie.HttpOnly = true; cookie.Path = ticket.CookiePath; if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; cookie.Secure = FormsAuthentication.RequireSSL; if (FormsAuthentication.CookieDomain != null) cookie.Domain = FormsAuthentication.CookieDomain; context.Response.Cookies.Remove(cookie.Name); context.Response.Cookies.Add(cookie); } return ticket; } finally { if (badTicket) { WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure, WebEventCodes.InvalidTicketFailure); } else if (ticketExpired) { WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure, WebEventCodes.ExpiredTicketFailure); } } } catch { throw; } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// private static void Trace(String str) { Debug.Trace("cookieauth", str); } } }
// dnlib: See LICENSE.txt for more info using System; using System.Text; using dnlib.DotNet.MD; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the Constant table /// </summary> public abstract class Constant : IMDTokenProvider { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.Constant, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <summary> /// From column Constant.Type /// </summary> public ElementType Type { get { return type; } set { type = value; } } /// <summary/> protected ElementType type; /// <summary> /// From column Constant.Value /// </summary> public object Value { get { return value; } set { this.value = value; } } /// <summary/> protected object value; } /// <summary> /// A Constant row created by the user and not present in the original .NET file /// </summary> public class ConstantUser : Constant { /// <summary> /// Default constructor /// </summary> public ConstantUser() { } /// <summary> /// Constructor /// </summary> /// <param name="value">Value</param> public ConstantUser(object value) { this.type = GetElementType(value); this.value = value; } /// <summary> /// Constructor /// </summary> /// <param name="value">Value</param> /// <param name="type">Type</param> public ConstantUser(object value, ElementType type) { this.type = type; this.value = value; } static ElementType GetElementType(object value) { if (value == null) return ElementType.Class; switch (System.Type.GetTypeCode(value.GetType())) { case TypeCode.Boolean: return ElementType.Boolean; case TypeCode.Char: return ElementType.Char; case TypeCode.SByte: return ElementType.I1; case TypeCode.Byte: return ElementType.U1; case TypeCode.Int16: return ElementType.I2; case TypeCode.UInt16: return ElementType.U2; case TypeCode.Int32: return ElementType.I4; case TypeCode.UInt32: return ElementType.U4; case TypeCode.Int64: return ElementType.I8; case TypeCode.UInt64: return ElementType.U8; case TypeCode.Single: return ElementType.R4; case TypeCode.Double: return ElementType.R8; case TypeCode.String: return ElementType.String; default: return ElementType.Void; } } } /// <summary> /// Created from a row in the Constant table /// </summary> sealed class ConstantMD : Constant, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>Constant</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public ConstantMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.ConstantTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("Constant rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; uint value = readerModule.TablesStream.ReadConstantRow(origRid, out this.type); this.value = GetValue(this.type, readerModule.BlobStream.ReadNoNull(value)); } static object GetValue(ElementType etype, byte[] data) { switch (etype) { case ElementType.Boolean: if (data == null || data.Length < 1) return false; return BitConverter.ToBoolean(data, 0); case ElementType.Char: if (data == null || data.Length < 2) return (char)0; return BitConverter.ToChar(data, 0); case ElementType.I1: if (data == null || data.Length < 1) return (sbyte)0; return (sbyte)data[0]; case ElementType.U1: if (data == null || data.Length < 1) return (byte)0; return data[0]; case ElementType.I2: if (data == null || data.Length < 2) return (short)0; return BitConverter.ToInt16(data, 0); case ElementType.U2: if (data == null || data.Length < 2) return (ushort)0; return BitConverter.ToUInt16(data, 0); case ElementType.I4: if (data == null || data.Length < 4) return (int)0; return BitConverter.ToInt32(data, 0); case ElementType.U4: if (data == null || data.Length < 4) return (uint)0; return BitConverter.ToUInt32(data, 0); case ElementType.I8: if (data == null || data.Length < 8) return (long)0; return BitConverter.ToInt64(data, 0); case ElementType.U8: if (data == null || data.Length < 8) return (ulong)0; return BitConverter.ToUInt64(data, 0); case ElementType.R4: if (data == null || data.Length < 4) return (float)0; return BitConverter.ToSingle(data, 0); case ElementType.R8: if (data == null || data.Length < 8) return (double)0; return BitConverter.ToDouble(data, 0); case ElementType.String: if (data == null) return string.Empty; return Encoding.Unicode.GetString(data, 0, data.Length / 2 * 2); case ElementType.Class: return null; default: return null; } } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; using DaydreamElements.Common; using DaydreamElements.Common.IconMenu; namespace DaydreamElements.ClickMenu { /// A circular section of a menu. /// Contains a tooltip, a foreground icon, a background icon and /// shares an auto-generated mesh background. [RequireComponent(typeof(SpriteRenderer))] [RequireComponent(typeof(MeshCollider))] public class ClickMenuIcon : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { private const int NUM_SIDES_CIRCLE_MESH = 48; /// Distance to push the icon when hovered in meters. private const float HOVERING_Z_OFFSET = 0.04f; /// Distance to push the menu in depth during fades in meters. private const float CLOSING_Z_OFFSET = 0.0f; /// Distance to push the menu out while it is being hidden in meters. private const float HIDING_Z_OFFSET = 0.02f; /// Default pop out distance in meters. private const float SHOWING_Z_OFFSET = 0.0f; /// Distance the background is pushed when idle in meters. private const float BACKGROUND_PUSH = 0.01f; /// Radius from center to menu item in units of scale. private const float ITEM_SPACING = 0.15f; /// The spacing for this many items is the minimum spacing. private const int MIN_ITEM_SPACE = 5; /// Time for the fading animation in seconds. private const float CLOSE_ANIMATION_SECONDS = 0.12f; private const float HIDE_ANIMATION_SECONDS = 0.12f; private const float HOVER_ANIMATION_SECONDS = 0.06f; private const float SHOW_ANIMATION_SECONDS = 0.24f; /// Scaling factor for the tooltip text. private const float TOOLTIP_SCALE = 0.1f; /// Distance in meters the icon hovers above pie slices to prevent occlusion. private const float ICON_Z_OFFSET = 0.1f; private Vector3 startPosition; private Vector3 startScale; private Vector3 menuCenter; private Quaternion menuOrientation; private float menuScale; private ClickMenuIcon parentMenu; private List<ClickMenuIcon> childMenus; private GameObject background; private ClickMenuItem menuItem; private AssetTree.Node menuNode; /// Manages events for all icons in the menu. public ClickMenuRoot menuRoot { private get; set; } private GameObject tooltip; private Vector3 localOffset; private MeshCollider meshCollider; private Mesh sharedMesh; private MaterialPropertyBlock propertyBlock; private SpriteRenderer spriteRenderer; private SpriteRenderer backgroundSpriteRenderer; private MeshRenderer tooltipRenderer; private GameObject pieBackground; private MeshRenderer pieMeshRenderer; private Color pieStartColor; private const float INNER_RADIUS = 0.6f; private const float OUTER_RADIUS = 1.6f; private float startAngle; private float endAngle; /// The time when the fade started. Used to interpolate fade parameters private float timeAtFadeStart; private float alphaAtFadeStart; private float scaleAtFadeStart; private float zOffsetAtFadeStart; private float highlightAtFadeStart; private bool selected; private bool buttonActive; private bool isBackButton; /// The most recent fade is at the front of the list. // Old fades are removed after they finish. List<FadeParameters> fades = new List<FadeParameters>(){ new FadeParameters(IconState.Closed, IconState.Closed) }; /// Describes how a button should behave in a particular state. // Provides functionality to interpolate to the new draw style. private class FadeParameters { public FadeParameters(IconState nextState, IconState prevState) { state = nextState; switch(state) { case IconState.Shown: alpha = 1.0f; if (prevState == IconState.Hovering) { duration = HOVER_ANIMATION_SECONDS; } else { duration = SHOW_ANIMATION_SECONDS; } buttonActive = true; highlight = 0.0f; scale = 1.0f; zOffset = SHOWING_Z_OFFSET; break; case IconState.Hovering: alpha = 1.0f; duration = HOVER_ANIMATION_SECONDS; buttonActive = true; highlight = 1.0f; scale = 1.0f; zOffset = HOVERING_Z_OFFSET; break; case IconState.Hidden: alpha = 0.0f; duration = HIDE_ANIMATION_SECONDS; buttonActive = false; highlight = 0.0f; scale = 1.5f; zOffset = HIDING_Z_OFFSET; break; case IconState.Closed: alpha = 0.0f; duration = CLOSE_ANIMATION_SECONDS; buttonActive = false; highlight = 0.0f; scale = 0.1f; zOffset = CLOSING_Z_OFFSET; break; } } public IconState state; public float duration; public float scale; public float alpha; public float zOffset; public float highlight; public bool buttonActive = false; }; public GameObject tooltipPrefab; void Awake() { sharedMesh = new Mesh(); sharedMesh.name = "Pie Mesh"; meshCollider = GetComponent<MeshCollider>(); propertyBlock = new MaterialPropertyBlock(); spriteRenderer = GetComponent<SpriteRenderer>(); childMenus = new List<ClickMenuIcon>(); buttonActive = false; selected = false; isBackButton = false; } /// A "dummy" icon will be invisible and non-interactable /// The top icon in the hierarchy will be a dummy icon public void SetDummy() { buttonActive = false; } /// Called to make this icon visible and interactable public void Initialize(ClickMenuRoot root, ClickMenuIcon _parentMenu, AssetTree.Node node, Vector3 _menuCenter, float scale, Vector3 offset) { string name = (node == null ? "Back " : ((ClickMenuItem)node.value).toolTip); gameObject.name = name + " Item"; parentMenu = _parentMenu; startPosition = transform.position; startScale = transform.localScale; menuRoot = root; menuNode = node; menuCenter = _menuCenter; menuOrientation = transform.rotation; menuScale = scale; localOffset = offset; background = null; if (node != null) { // Set foreground icon menuItem = (ClickMenuItem)node.value; spriteRenderer.sprite = menuItem.icon; // Set background icon if (menuItem.background) { background = new GameObject(name + " Item Background"); background.transform.parent = transform.parent; background.transform.localPosition = transform.localPosition + transform.forward * BACKGROUND_PUSH; background.transform.localRotation = transform.localRotation; background.transform.localScale = transform.localScale; backgroundSpriteRenderer = background.AddComponent<SpriteRenderer>(); backgroundSpriteRenderer.sprite = menuItem.background; } // Set tooltip text tooltip = Instantiate(tooltipPrefab); tooltip.name = name + " Tooltip"; tooltip.transform.parent = transform.parent; tooltip.transform.localPosition = menuCenter; tooltip.transform.localRotation = menuOrientation; tooltip.transform.localScale = transform.localScale * TOOLTIP_SCALE; tooltip.GetComponent<TextMesh>().text = menuItem.toolTip.Replace('\\','\n'); tooltipRenderer = tooltip.GetComponent<MeshRenderer>(); SetTooltipAlpha(0.0f); } else { // This is a back button spriteRenderer.sprite = root.backIcon; isBackButton = true; } pieBackground = null; pieMeshRenderer = null; if (root.pieMaterial) { pieBackground = new GameObject(name + " Pie Background"); pieBackground.transform.SetParent(transform.parent, false); pieBackground.transform.localPosition = transform.localPosition; pieBackground.transform.localRotation = transform.localRotation; pieBackground.transform.localScale = transform.localScale; pieBackground.AddComponent<MeshFilter>().sharedMesh = sharedMesh; pieMeshRenderer = pieBackground.AddComponent<MeshRenderer>(); pieMeshRenderer.sharedMaterial = root.pieMaterial; pieStartColor = root.pieMaterial.GetColor("_Color"); } parentMenu.childMenus.Add(this); StartFade(IconState.Shown); SetButtonTransparency(0.0f); SetPieMeshTransparency(0.0f, 0.0f); } private void MakeMeshColliderCircle() { Vector3[] vertices = new Vector3[NUM_SIDES_CIRCLE_MESH*2 + 1]; int[] triangles = new int[NUM_SIDES_CIRCLE_MESH * 9]; vertices[0] = new Vector3(0.0f, 0.0f, ICON_Z_OFFSET); float pushScaled = GetCurrentZOffset() / transform.localScale[0]; for (int i = 0; i < NUM_SIDES_CIRCLE_MESH; i++) { float angle = i * 2.0f * Mathf.PI / NUM_SIDES_CIRCLE_MESH; float x = Mathf.Sin(angle) * INNER_RADIUS; float y = Mathf.Cos(angle) * INNER_RADIUS; vertices[i + 1] = new Vector3(x, y, ICON_Z_OFFSET); vertices[i + NUM_SIDES_CIRCLE_MESH + 1] = new Vector3(x, y, pushScaled + ICON_Z_OFFSET); int nextIx = (i == NUM_SIDES_CIRCLE_MESH - 1 ? 1 : i + 2); triangles[i * 9 + 0] = i + 1; triangles[i * 9 + 1] = nextIx; triangles[i * 9 + 2] = 0; triangles[i * 9 + 3] = i + 1; triangles[i * 9 + 4] = i + NUM_SIDES_CIRCLE_MESH + 1; triangles[i * 9 + 5] = nextIx; triangles[i * 9 + 6] = nextIx; triangles[i * 9 + 7] = i + NUM_SIDES_CIRCLE_MESH + 1; triangles[i * 9 + 8] = nextIx + NUM_SIDES_CIRCLE_MESH; } sharedMesh.vertices = vertices; sharedMesh.triangles = triangles; } private void MakeMeshCollider() { if (localOffset.sqrMagnitude <= Mathf.Epsilon) { MakeMeshColliderCircle(); return; } int numSides = (int)((endAngle - startAngle) * 8.0f) + 1; Vector3[] vertices = new Vector3[numSides * 4 + 4]; int[] triangles = new int[numSides * 18 + 12]; float outerRadius = localOffset.magnitude + Mathf.Min(localOffset.magnitude - INNER_RADIUS, OUTER_RADIUS - 1.0f); float pushScaled = GetCurrentZOffset() / transform.localScale[0]; float x = Mathf.Sin(startAngle); float y = Mathf.Cos(startAngle); vertices[0] = new Vector3(x * INNER_RADIUS, y * INNER_RADIUS, pushScaled + ICON_Z_OFFSET) - localOffset; vertices[1] = new Vector3(x * outerRadius, y * outerRadius, pushScaled + ICON_Z_OFFSET) - localOffset; vertices[2] = new Vector3(x * INNER_RADIUS, y * INNER_RADIUS, ICON_Z_OFFSET) - localOffset; vertices[3] = new Vector3(x * outerRadius, y * outerRadius, ICON_Z_OFFSET) - localOffset; triangles[0] = 0; triangles[1] = 1; triangles[2] = 2; triangles[3] = 3; triangles[4] = 2; triangles[5] = 1; for (int i = 0; i < numSides; i++) { float angle = startAngle + (i + 1) * (endAngle - startAngle) / numSides; x = Mathf.Sin(angle); y = Mathf.Cos(angle); vertices[i*4 + 4] = new Vector3(x * INNER_RADIUS, y * INNER_RADIUS, pushScaled + ICON_Z_OFFSET) - localOffset; vertices[i*4 + 5] = new Vector3(x * outerRadius, y * outerRadius, pushScaled + ICON_Z_OFFSET) - localOffset; vertices[i*4 + 6] = new Vector3(x * INNER_RADIUS, y * INNER_RADIUS, ICON_Z_OFFSET) - localOffset; vertices[i*4 + 7] = new Vector3(x * outerRadius, y * outerRadius, ICON_Z_OFFSET) - localOffset; triangles[i*18 + 6] = i*4 + 0; triangles[i*18 + 7] = i*4 + 2; triangles[i*18 + 8] = i*4 + 4; triangles[i*18 + 9] = i*4 + 6; triangles[i*18 + 10] = i*4 + 4; triangles[i*18 + 11] = i *4 + 2; triangles[i * 18 + 12] = i*4 + 2; triangles[i * 18 + 13] = i*4 + 3; triangles[i * 18 + 14] = i*4 + 6; triangles[i * 18 + 15] = i*4 + 7; triangles[i * 18 + 16] = i*4 + 6; triangles[i * 18 + 17] = i*4 + 3; triangles[i * 18 + 18] = i*4 + 3; triangles[i * 18 + 19] = i*4 + 1; triangles[i * 18 + 20] = i*4 + 7; triangles[i * 18 + 21] = i*4 + 5; triangles[i * 18 + 22] = i*4 + 7; triangles[i * 18 + 23] = i*4 + 1; } int lastTriangleIx = numSides * 18 + 6; int lastVertIx = numSides * 4; triangles[lastTriangleIx + 0] = lastVertIx + 2; triangles[lastTriangleIx + 1] = lastVertIx + 1; triangles[lastTriangleIx + 2] = lastVertIx + 0; triangles[lastTriangleIx + 3] = lastVertIx + 1; triangles[lastTriangleIx + 4] = lastVertIx + 2; triangles[lastTriangleIx + 5] = lastVertIx + 3; sharedMesh.vertices = vertices; sharedMesh.triangles = triangles; } /// Shows a new menu, returns true if a fade needs to occur. public static bool ShowMenu(ClickMenuRoot root, AssetTree.Node treeNode, ClickMenuIcon parent, Vector3 center, Quaternion orientation, float scale) { // Determine how many children are in the sub-menu List<AssetTree.Node> childItems = treeNode.children; // If this is the end of a menu, invoke the action and return early if (childItems.Count == 0) { if (parent.menuItem.closeAfterSelected) { root.CloseAll(); } return false; } // Radius needs to expand when there are more icons float radius = ITEM_SPACING * Mathf.Max(childItems.Count, MIN_ITEM_SPACE) / (2.0f * Mathf.PI); // Create and arrange the icons in a circle float arcAngle = 2.0f * Mathf.PI / childItems.Count; for (int i = 0; i < childItems.Count; ++i) { float angle = i * arcAngle; Vector3 posOffset = new Vector3(Mathf.Sin(angle), Mathf.Cos(angle), 0.0f) * radius; ClickMenuIcon childMenu = (ClickMenuIcon)Instantiate(root.menuIconPrefab, root.transform); childMenu.transform.position = center + (orientation * posOffset); childMenu.transform.rotation = orientation; childMenu.transform.localScale = Vector3.one * scale; childMenu.startAngle = angle - arcAngle / 2; childMenu.endAngle = angle + arcAngle / 2; childMenu.Initialize(root, parent, childItems[i], center, scale, posOffset / scale); } // Also create a back button ClickMenuIcon backButton = (ClickMenuIcon)Instantiate(root.menuIconPrefab, root.transform); backButton.transform.position = center; backButton.transform.rotation = orientation; backButton.transform.localScale = Vector3.one * scale; backButton.Initialize(root, parent, null, center, scale, Vector3.zero); return true; } /// Returns true if a fade starts. private bool ShowChildMenu() { return ShowMenu(menuRoot, menuNode, this, menuCenter, menuOrientation, menuScale); } /// Closes this menu and shows the parent level public void ShowParentMenu() { if (!parentMenu) { menuRoot.CloseAll(); } else { FadeChildren(IconState.Closed); parentMenu.FadeChildren(IconState.Shown); childMenus.Clear(); } } void Update() { ContinueFade(); var highlight = GetCurrentHighlight(); SetTooltipAlpha(highlight); // The back button needs special handling because the tooltips draw over it. // Make it fade out unless it is highlighted. if (isBackButton) { SetButtonTransparency(highlight); } if (buttonActive) { // Make button interactive and process clicks MakeMeshCollider(); if (selected && (GvrControllerInput.ClickButtonDown)) { menuRoot.MakeSelection(menuItem); if (isBackButton) { parentMenu.ShowParentMenu(); } else { if (ShowChildMenu()) { parentMenu.FadeChildren(IconState.Hidden); } } } } } /// Shrink / Grow button // t is the scale of the button. // depth adjusts the buttons z position to move a button toward or away from viewer private void SetButtonScale(float t, float depth) { float scaleMult = Mathf.Max(t, 0.01f); Vector3 delta = (startPosition - menuCenter) * t; transform.position = menuCenter + delta - transform.forward * depth; transform.localScale = startScale * scaleMult; if (background) { background.transform.position = menuCenter + transform.forward * BACKGROUND_PUSH + delta; background.transform.localScale = startScale * scaleMult; } if (pieBackground) { pieBackground.transform.position = menuCenter + delta - pieBackground.transform.forward * depth; pieBackground.transform.localScale = startScale * scaleMult; } } private void SetButtonTransparency(float alpha) { Color alphaColor = new Color(1.0f, 1.0f, 1.0f, alpha); if (isBackButton) { alphaColor.a = Mathf.Min(zOffsetAtFadeStart / HOVERING_Z_OFFSET, alpha); } spriteRenderer.GetPropertyBlock(propertyBlock); propertyBlock.SetColor("_Color", alphaColor); spriteRenderer.SetPropertyBlock(propertyBlock); if (background) { backgroundSpriteRenderer.GetPropertyBlock(propertyBlock); propertyBlock.SetColor("_Color", alphaColor); backgroundSpriteRenderer.SetPropertyBlock(propertyBlock); } } // Draw the pie background with highlight private void SetPieMeshTransparency(float alpha, float highlight) { if (pieMeshRenderer) { Color pieColor = pieStartColor; pieColor.a = pieColor.a * alpha * (1.0f - highlight) + highlight; pieMeshRenderer.GetPropertyBlock(propertyBlock); propertyBlock.SetColor("_Color", pieColor); pieMeshRenderer.SetPropertyBlock(propertyBlock); } } private void SetTooltipAlpha(float alpha) { if (tooltip) { Color alphaColor = new Color(1.0f, 1.0f, 1.0f, alpha); tooltipRenderer.GetPropertyBlock(propertyBlock); propertyBlock.SetColor("_Color", alphaColor); tooltipRenderer.SetPropertyBlock(propertyBlock); } } void OnDestroy() { Destroy(sharedMesh); if (pieBackground) { Destroy(pieBackground); } if (background) { Destroy(background); } if (tooltip) { Destroy(tooltip); } if (parentMenu) { parentMenu.childMenus.Remove (this); } } private void FadeChildren(IconState nextState) { foreach (ClickMenuIcon child in childMenus) { child.StartFade(nextState); } } private void StartFade(IconState nextState) { FadeParameters prev = fades[0]; if (prev.state == nextState) { return; } if (fades.Count > 1) { // A fade is currently in progress. Save off any values where they are now. float t = GetCurrentProgress(); alphaAtFadeStart = GetCurrentAlpha(); scaleAtFadeStart = Mathf.Lerp(scaleAtFadeStart, prev.scale, t); zOffsetAtFadeStart = GetCurrentZOffset(); highlightAtFadeStart = GetCurrentHighlight(); // Delete any old fades fades.RemoveRange(1, fades.Count - 1); } FadeParameters nextFade = new FadeParameters(nextState, prev.state); fades.Insert(0, nextFade); timeAtFadeStart = Time.time; buttonActive = nextFade.buttonActive; if (!buttonActive) { // Collisions are only allowed on active buttons. meshCollider.sharedMesh = null; } } private void FinishFade() { // Save values from the completed fade. FadeParameters finishedFade = fades[0]; alphaAtFadeStart = GetCurrentAlpha(); scaleAtFadeStart = finishedFade.scale; zOffsetAtFadeStart = GetCurrentZOffset(); highlightAtFadeStart = GetCurrentHighlight(); // remove any old fades if (fades.Count > 1) { fades.RemoveRange(1, fades.Count - 1); } if (finishedFade.buttonActive) { MakeMeshCollider(); meshCollider.sharedMesh = sharedMesh; buttonActive = true; } if (finishedFade.state == IconState.Closed) { Destroy(gameObject); } } /// Updates icon with interpolated fade values. private void ContinueFade() { if (fades.Count < 2) { // no fade in progress. Do nothing. return; } float t = GetCurrentProgress(); float scale = Mathf.Lerp(scaleAtFadeStart, fades[0].scale, t); float alpha = GetCurrentAlpha(); SetButtonScale(scale, GetCurrentZOffset()); SetButtonTransparency(alpha); SetPieMeshTransparency(alpha, GetCurrentHighlight()); if (fades[0].state == IconState.Closed) { selected = false; } else if (fades[0].state == IconState.Hidden) { MakeMeshCollider(); selected = false; } else { // Fade in. MakeMeshCollider(); } if (!(GetCurrentProgress() < 1.0f)) { FinishFade(); return; } } /// Starts a fade if the there is a match for fromState private void FadeIfNeeded(IconState fromState, IconState toState) { if (fades[0].state != fromState) { return; } StartFade(toState); } /// returns 1 if completed, 0 if just started or values in between depending on time private float GetCurrentProgress() { if (fades.Count < 2) { return 1.0f; } return Mathf.Clamp01((Time.time - timeAtFadeStart) / fades[0].duration); } /// The width in z of the button mesh we create. /// Also used to move button forward in z. private float GetCurrentZOffset() { float zOffset = zOffsetAtFadeStart; if (fades.Count > 1) { if (fades[0].state == IconState.Closed && fades[1].state == IconState.Hovering) { // Special Behavior: One button is hovering above the others. // Force it to close with the same height as other buttons. zOffset = SHOWING_Z_OFFSET; } zOffset = Mathf.Lerp(zOffset, fades[0].zOffset, GetCurrentProgress()); } return zOffset; } private float GetCurrentHighlight() { if (buttonActive==false) { // Special Behavior: disabled buttons can not be highlighted. return 0.0f; } float highlight = highlightAtFadeStart; if (fades.Count > 1) { highlight = Mathf.Lerp(highlightAtFadeStart, fades[0].highlight, GetCurrentProgress()); } return highlight; } private float GetCurrentAlpha() { float alpha = alphaAtFadeStart; if (fades.Count > 1) { float t = GetCurrentProgress(); if(fades[0].alpha < alphaAtFadeStart) { // Special Behavior: fade out 50% faster. t = Mathf.Clamp01(t * 1.5f); } alpha = Mathf.Lerp(alphaAtFadeStart, fades[0].alpha, t); } return alpha; } /// Recursively closes this menu and its children public void CloseAll() { foreach (ClickMenuIcon child in childMenus) { child.CloseAll(); } if (buttonActive) { StartFade(IconState.Closed); } else { // If the button is already disabled, destroy it instantly Destroy(gameObject); } } public ClickMenuIcon DeepestMenu() { foreach (ClickMenuIcon child in childMenus) { if (child.childMenus.Count > 0) { return child.DeepestMenu(); } } return this; } public void OnPointerEnter(PointerEventData eventData) { if (!selected) { menuRoot.MakeHover(menuItem); } selected = true; FadeIfNeeded(IconState.Shown, IconState.Hovering); } public void OnPointerExit(PointerEventData eventData) { selected = false; FadeIfNeeded(IconState.Hovering, IconState.Shown); } } }
// NoteDataXML_Interface.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Windows.Forms; using System.Drawing; using System.Collections.Generic; using CoreUtilities; using System.Xml.Serialization; /* This is to contain the interface related elements (interaction with the GUID) to keep that distinct from the xml definition*/ namespace Layout { public partial class NoteDataXML { #region UI protected ToolStripMenuItem AppearanceSet=null; protected ToolStrip CaptionLabel; //protected ContextMenuStrip contextMenu; // this holds the PropertyGrid protected Panel PropertyPanel; protected PropertyGrid propertyGrid; // the properties button on header protected ToolStripDropDownButton properties; protected ToolStripLabel captionLabel; protected ToolStripButton ReadOnlyButton; protected ToolStripButton MaximizeButton; protected ToolStripButton MinimizeButton; #endregion public virtual void Dispose () { } // http://stackoverflow.com/questions/7367152/c-dynamically-assign-method-method-as-variable Func<System.Collections.Generic.List<NoteDataInterface>> GetAvailableFolders; Action<string,string> MoveNote; private Action<bool> setsaverequired; protected Action<NoteDataInterface> DeleteNote; [XmlIgnore] public Action<bool> SetSaveRequired { get { return setsaverequired;} set { setsaverequired = value;} } protected delegate void delegate_UpdateListOfNotes(); protected virtual AppearanceClass UpdateAppearance () { // This is the slow operation - removing it gives us 3 seconds back // takes the current appearance and adjusts it. AppearanceClass app = LayoutDetails.Instance.GetAppearanceByName (this.Appearance); if (null != app) { this.SetSaveRequired(true); // I was adding this to all children anyways, so figured I'd try it out in the base // REJECTED: This is too ugly //ParentNotePanel.BackColor = app.captionBackground; //Layout.AppearanceClass app = AppearanceClass.SetAsProgrammer(); CaptionLabel.SuspendLayout (); //minor, fraction of a second savings CaptionLabel.Font = app.captionFont; //1 this.CaptionLabel.Height = app.nHeaderHeight; //2 // SystemInformation.MouseHoverTime = 1000; ParentNotePanel.BorderStyle = app.mainPanelBorderStyle; //3 this.CaptionLabel.BackColor = app.captionBackground; //4 this.CaptionLabel.ForeColor = app.captionForeground; //5 foreach (ToolStripItem item in this.CaptionLabel.Items) { // // intending this to COLOR the new NoteDock buttons ONLY 03/11/2014 // if (item.Tag != null && item.Tag.ToString() == "NoteDock") { item.BackColor = app.captionForeground; item.ForeColor = app.captionBackground; } } DoChildAppearance (app); CaptionLabel.ResumeLayout (); } AppearanceSet.Text = Loc.Instance.GetStringFmt ("Appearance: {0}", this.Appearance); // we pass this out so inherited methods do not need to make a second load of this resource return app; } // this is overrideen by children to updat their own controls colors protected virtual void DoChildAppearance (Layout.AppearanceClass app) { } //delegate_UpdateListOfNotes UpdateListOfNotes; public void CreateParent (LayoutPanelBase _Layout) { ParentNotePanel = new NotePanel (this); //ParentNotePanel.Visible = false; // ParentNotePanel.SuspendLayout (); ParentNotePanel.Visible = true; ParentNotePanel.Location = Location; ParentNotePanel.Dock = System.Windows.Forms.DockStyle.None; ParentNotePanel.Height = Height; ParentNotePanel.Width = Width; ParentNotePanel.Dock = this.Dock; try { _Layout.NoteCanvas.Controls.Add (ParentNotePanel); } catch (Exception ex) { lg.Instance.Line ("CreateParent", ProblemType.EXCEPTION, "Unable to create note after changing properties" + ex.ToString ()); throw new Exception ("Failed to add control"); } CaptionLabel = new ToolStrip (); // must be false for height to matter CaptionLabel.AutoSize = false; // CaptionLabel.SuspendLayout (); CaptionLabel.Click += (object sender, EventArgs e) => BringToFrontAndShow (); // CaptionLabel.DoubleClick += HandleCaptionLabelDoubleClick; CaptionLabel.MouseDown += HandleMouseDown; CaptionLabel.MouseUp += HandleMouseUp; CaptionLabel.MouseLeave += HandleMouseLeave; CaptionLabel.MouseMove += HandleMouseMove; CaptionLabel.Parent = ParentNotePanel; CaptionLabel.BackColor = Color.Green; CaptionLabel.Dock = DockStyle.Fill; CaptionLabel.GripStyle = ToolStripGripStyle.Hidden; captionLabel = new ToolStripLabel (this.Caption); captionLabel.ToolTipText = Loc.Instance.GetString ("TIP: Doubleclick this to set the note to its regular size"); captionLabel.MouseDown += HandleMouseDown; captionLabel.MouseUp += HandleMouseUp; //captionLabel.MouseLeave += HandleMouseLeave; captionLabel.MouseMove += HandleMouseMove; captionLabel.DoubleClickEnabled = true; captionLabel.DoubleClick+= HandleCaptionLabelDoubleClick; CaptionLabel.Items.Add (captionLabel); //if (Caption == "") NewMessage.Show ("Caption is blank"); properties = new ToolStripDropDownButton (""); properties.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("application_form_edit.png"); CaptionLabel.Items.Add (properties); MinimizeButton = new ToolStripButton (); //MinimizeButton.Text = "--"; MinimizeButton.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("application_put.png"); MinimizeButton.ToolTipText = "Hides the note. Bring it back by using the List or a Tab"; MinimizeButton.Click += HandleMinimizeButtonClick; MaximizeButton = new ToolStripButton (); //MaximizeButton.Text = "[ ]"; MaximizeButton.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("application_xp.png"); MaximizeButton.ToolTipText = Loc.Instance.GetString ("Fills available screen"); MaximizeButton.Click += HandleMaximizeButtonClick; if (true == IsSystemNote) { // not really a delete, more of a close ToolStripButton closeButton = new ToolStripButton (); //closeButton.Text = " X "; closeButton.Image = CoreUtilities.FileUtils.GetImage_ForDLL ("delete_x.png"); closeButton.Click += HandleCloseClick; ; CaptionLabel.Items.Add (closeButton); //closeButton.Anchor = AnchorStyles.Right; closeButton.Alignment = ToolStripItemAlignment.Right; // ToolStripItem item = new ToolStripItem(); //item.ToolStripItemAlignment = ToolStripItemAlignment.Right; //closeButton.Dock = DockStyle.Right; } if (false == IsSystemNote) { ToolStripTextBox captionEditor = new ToolStripTextBox (); captionEditor.Text = Caption; captionEditor.TextChanged += HandleCaptionTextChanged; captionEditor.KeyDown += HandleCaptionEditorKeyDown; properties.DropDownItems.Add (captionEditor); } CaptionLabel.Items.Add (MaximizeButton); MaximizeButton.Alignment = ToolStripItemAlignment.Right; CaptionLabel.Items.Add (MinimizeButton); MinimizeButton.Alignment = ToolStripItemAlignment.Right; //contextMenu = new ContextMenuStrip(); ToolStripButton BringToFront = new ToolStripButton (); BringToFront.Text = Loc.Instance.Cat.GetString ("Bring to Front"); BringToFront.Click += HandleBringToFrontClick; properties.DropDownItems.Add (BringToFront); properties.DropDownItems.Add (new ToolStripSeparator ()); if (false == IsSystemNote) { ReadOnlyButton = new ToolStripButton (); ReadOnlyButton.CheckOnClick = true; ReadOnlyButton.Checked = this.ReadOnly; ReadOnlyButton.Text = Loc.Instance.Cat.GetString ("Read Only"); ReadOnlyButton.Click += HandleReadOnlyClick; properties.DropDownItems.Add (ReadOnlyButton); } // // // APPEARANCE // // AppearanceSet = new ToolStripMenuItem (); ContextMenuStrip AppearanceMenu = new ContextMenuStrip (); ToolStripLabel empty = new ToolStripLabel ("BB"); AppearanceMenu.Items.Add (empty); AppearanceSet.DropDown = AppearanceMenu; AppearanceMenu.Opening += HandleAppearanceMenuOpening; properties.DropDownItems.Add (AppearanceSet); // // // DOCK STYLE // // ToolStripComboBox DockPicker = new ToolStripComboBox (); DockPicker.ToolTipText = Loc.Instance.GetString ("Set Docking Behavior For Note"); DockPicker.DropDownStyle = ComboBoxStyle.DropDownList; //DockPicker.DropDown+= HandleDockDropDown; (DockPicker).Items.Clear (); int found = -1; int count = -1; // this loop does not affect performance foreach (string s in Enum.GetNames(typeof(DockStyle))) { count++; (DockPicker).Items.Add (s); if (s == this.Dock.ToString ()) { found = count; } } if (found > -1) DockPicker.SelectedIndex = found; DockPicker.SelectedIndexChanged += HandleDockStyleSelectedIndexChanged; properties.DropDownItems.Add (DockPicker); // // // LOCK // // ToolStripButton LockState = new ToolStripButton (); LockState.Text = Loc.Instance.GetString ("Lock"); LockState.Checked = this.LockState; LockState.CheckOnClick = true; LockState.Click += HandleLockStateClick; properties.DropDownItems.Add (LockState); // // // FOLDER // // if (false == IsSystemNote) { ToolStripMenuItem menuFolder = new ToolStripMenuItem (); menuFolder.Text = Loc.Instance.Cat.GetString ("Folder"); properties.DropDownItems.Add (menuFolder); // just here to make sure that there's a dropdown singal before populating menuFolder.DropDownItems.Add (""); menuFolder.DropDownOpening += HandleFolderDropDownOpening; // menuFolder.MouseEnter += HandleMenuFolderMouseEnter; } if (false == IsSystemNote) { ToolStripButton deleteNote = new ToolStripButton (); deleteNote.Text = Loc.Instance.GetString ("Delete This Note"); properties.DropDownItems.Add (deleteNote); deleteNote.Click += HandleDeleteNoteClick; } else if (true == IsSystemNote) { // add a way to DELETE a Layout? ToolStripButton deleteNote = new ToolStripButton (); deleteNote.Text = Loc.Instance.GetString ("Delete This Layout"); properties.DropDownItems.Add (deleteNote); deleteNote.Click += HandleDeleteLayoutClick; } if (true == IsLinkable) { ToolStripButton linkNote = new ToolStripButton (); linkNote.Text = Loc.Instance.GetString ("Create a Link To This Note"); properties.DropDownItems.Add (linkNote); linkNote.Click += HandleLinkNoteClick; } ToolStripButton copyNote = new ToolStripButton (); copyNote.Text = Loc.Instance.GetString ("Copy Note"); properties.DropDownItems.Add (copyNote); copyNote.Click += (object sender, EventArgs e) => Layout.CopyNote (this); properties.DropDownItems.Add (new ToolStripSeparator ()); ToolStripButton menuProperties = new ToolStripButton (); menuProperties.Text = Loc.Instance.Cat.GetString ("Properties"); properties.DropDownItems.Add (menuProperties); menuProperties.Click += HandlePropertiesClick; // 04/11/2014 // TODO REMOVE // If I ever build a cleaner system for setting up notedocks this can be removed // but for now we display the GUID as a clickable button // that puts in on the clipboard ToolStripButton menuGUIDButton = new ToolStripButton(); menuGUIDButton.Text = this.GuidForNote; menuGUIDButton.Click+= (object sender, EventArgs e) => { Clipboard.SetText(this.GuidForNote); }; properties.DropDownItems.Add (menuGUIDButton); PropertyPanel = new Panel (); PropertyPanel.Visible = false; PropertyPanel.Parent = ParentNotePanel; PropertyPanel.Height = 300; PropertyPanel.Dock = DockStyle.Top; PropertyPanel.AutoScroll = true; Button CommitChanges = new Button (); CommitChanges.Text = Loc.Instance.Cat.GetString ("Update Note"); CommitChanges.Parent = PropertyPanel; CommitChanges.Dock = DockStyle.Bottom; CommitChanges.Click += HandleCommitChangesClick; CommitChanges.BringToFront (); ParentNotePanel.Visible = this.Visible; // CaptionLabel.ResumeLayout(); this did not seem to help // ParentNotePanel.ResumeLayout(); // Set up delegates GetAvailableFolders = _Layout.GetAvailableFolders; MoveNote = _Layout.MoveNote; SetSaveRequired = _Layout.SetSaveRequired; DeleteNote = _Layout.DeleteNote; Layout = _Layout; ToolStripMenuItem TokenItem = LayoutDetails.BuildMenuPropertyEdit (Loc.Instance.GetString("Note Dock String: {0}"), this.Notedocks, Loc.Instance.GetString ("example: note1*44159e01-b2c6-4b1f-9b68-8d3c85755f14*[[chapter1]]."), HandleTokenChange,25 ); properties.DropDownItems.Add (TokenItem); BuildNoteDocks(); // February 17 2013 - needed to ensure that children build their controls before Updateappearance is called DoBuildChildren(_Layout); UpdateAppearance (); } /// <summary> /// Builds the notedocks. /// </summary> void BuildNoteDocks () { try { // step 1: delete any existing notedocks if (CaptionLabel != null && CaptionLabel.Items != null && CaptionLabel.Items.Count > 0) for (int i = CaptionLabel.Items.Count-1; i >=0; i--) { ToolStripItem control = (ToolStripItem)CaptionLabel.Items [i]; if (control.Tag != null) { if (control.Tag.ToString () == "NoteDock") { CaptionLabel.Items.Remove ((ToolStripItem)control); } } } // // 03/11/2014 // // Add custom button links (to give user ability to pair development notes with chapters) // //string customNoteLinks = "note1*44159e01-b2c6-4b1f-9b68-8d3c85755f14*chapter1;[[wordcount]]*44159e01-b2c6-4b1f-9b68-8d3c85755f14*chapter1"; // quick test just fake it //foreach (string link in customNoteLinks) { // breakdown strings string[] links = this.Notedocks.Split (new char[1]{';'}, StringSplitOptions.RemoveEmptyEntries); if (links != null && links.Length > 0) { foreach (string link_unit in links) { string[] units = link_unit.Split (new char[1]{'*'}, StringSplitOptions.RemoveEmptyEntries); // anchor optional if (units != null && units.Length >= 2) { ToolStripButton noteLink = new ToolStripButton (); noteLink.Text = units [0]; // // tag contains GUID plus anchor reference. // noteLink.Tag = units[1]; // // // final anchor is optional // if (units.Length == 3) // { // noteLink.Tag = units[1] + "*" + units[2]; // } noteLink.Tag = "NoteDock"; if (units [0] == "[[wordcount]]") { noteLink.Text = "<press for word count>"; noteLink.Click += (object sender, EventArgs e) => { if (this.IsPanel) { int maxwords = 0; int maxwords2=0; // able to show three numbers. Document 0/2309 (next stage) / 99999 max Int32.TryParse (units [1], out maxwords); if (units.Length == 3) { Int32.TryParse (units [2], out maxwords2); } int words = 0; //NewMessage.Show ("boo"); // iterate through all notes foreach (NoteDataInterface note_ in this.ListOfSubnotesAsNotes()) { //NewMessage.Show (note_.Caption); if (note_ is NoteDataXML_RichText) { // fetch word count //((NoteDataXML_RichText)note_).GetRichTextBox(). if (LayoutDetails.Instance.WordSystemInUse != null) { try{ // we fetch data1 because the actual rich text box is NOT loaded // but I found the word count quite excessive so we load it instead RichTextBox faker = new RichTextBox(); faker.Rtf = ((NoteDataXML_RichText)note_).Data1; string ftext = faker.Text; faker.Dispose (); words = words + LayoutDetails.Instance.WordSystemInUse.CountWords(ftext); } catch(System.Exception) { NewMessage.Show (Loc.GetStr("ERROR: Internal Word System Word Counting Error")); } } else { NewMessage.Show (Loc.GetStr("Is there a Word system installed for counting words?")); } } } if (maxwords2 > 0) { noteLink.Text = String.Format ("{0}/{1}/{2}", words, maxwords, maxwords2); } else if (maxwords > 0) { noteLink.Text = String.Format ("{0}/{1}", words, maxwords); } else { noteLink.Text = String.Format ("{0}", words); } } else { NewMessage.Show (Loc.Instance.GetString ("Word Count only works if attached to a Layout Note")); } }; } else noteLink.Click += (object sender, EventArgs e) => { string theNoteGuid = units [1]; string linkanchor = ""; if (units.Length == 3) { linkanchor = units [2]; } LayoutPanelBase SuperParent = null; if (this.Layout.GetIsChild == true) SuperParent = this.Layout.GetAbsoluteParent (); else SuperParent = this.Layout; NoteDataInterface theNote = this.Layout.GetNoteOnSameLayout (theNoteGuid, false); //NewMessage.Show ("hi " + theNoteGuid); // GetNonteOnSameLayout always returns a valid note. if (theNote != null && theNote.Caption != "findme") { // // Toggle Visibility State // if (theNote.Visible == true) { //NewMessage.Show ("Hide"); theNote.Visible = false; theNote.UpdateLocation (); } else { //NewMessage.Show ("Show"); int theNewX = this.Location.X; int theNewY = this.Location.Y; if (this.Layout.GetIsChild) { //NewMessage.Show ("child"); //ok this seems convulted but I need to get the Note containing this layout // and there does not seem to be a short cut for it. string GuidOfLayoutNote = this.Layout.GUID; NoteDataInterface parentNote = SuperParent.GetNoteOnSameLayout (GuidOfLayoutNote, false); if (parentNote != null) { //NewMessage.Show (GuidOfLayoutNote); // if we are a child then use the coordinates of the layoutpanel itself theNewX = parentNote.Location.X; theNewY = parentNote.Location.Y; theNote.Height = Math.Max (0, parentNote.Height / 2); theNote.Width = Math.Max (0, parentNote.Width - 4); } else { NewMessage.Show ("Parent note with GUID was blank " + GuidOfLayoutNote); } } else { // get width and height from non-layout enclosed note theNote.Height = Math.Max (0, this.Height / 2); theNote.Width = Math.Max (0, this.Width - 4); } // now offset a bit theNewX = theNewX + 25; theNewY = theNewY + 100; theNote.Location = new Point (theNewX, theNewY); theNote.Visible = true; theNote.UpdateLocation (); // so size changes stick //theNote.BringToFrontAndShow (); theNote = this.Layout.GetNoteOnSameLayout (theNoteGuid, true, linkanchor); } // this.Layout.GoToNote(theNote); } else { NewMessage.Show (Loc.Instance.GetStringFmt ("The guid {0} was null", theNoteGuid)); } }; // The click CaptionLabel.Items.Add (noteLink); // do this after adding to INHERIT the proper styles from TOOLBAR // reverse color scheme // coloring should happen in UPDATE apeparance // Color foreC = CaptionLabel.BackColor; // Color backC = CaptionLabel.ForeColor; noteLink.Font = new Font (noteLink.Font.FontFamily, noteLink.Font.Size - 1); // noteLink.BackColor = app.captionBackground;; // noteLink.ForeColor = backC; } } } } } catch (System.Exception ex) { NewMessage.Show (ex.ToString ()); } } /// <summary> /// Handles the token change. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleTokenChange (object sender, KeyEventArgs e) { string tablecaption = Notedocks; LayoutDetails.HandleMenuLabelEdit (sender, e, ref tablecaption, SetSaveRequired); Notedocks = tablecaption; // whenever this changes we rebuild the notedocks BuildNoteDocks(); } protected virtual void DoBuildChildren(LayoutPanelBase _Layout) { // children ned to modify this (basically it is their version of CreatePraent) } void HandleAppearanceMenuOpening (object sender, System.ComponentModel.CancelEventArgs e) { (sender as ContextMenuStrip).Items.Clear (); // build list from list of appearances in database System.Collections.Generic.List<string> list = LayoutDetails.Instance.GetListOfAppearances (); foreach (string s in list) { ToolStripButton button = new ToolStripButton(); button.CheckOnClick=true; button.Text = s; if (s == this.Appearance) button.Checked= true; button.Click+= HandleChooseNewAppearanceClick; (sender as ContextMenuStrip).Items.Add (button); } } void HandleChooseNewAppearanceClick (object sender, EventArgs e) { this.Appearance = (sender as ToolStripButton).Text; UpdateAppearance(); } void HandleLockStateClick (object sender, EventArgs e) { this.LockState = (sender as ToolStripButton).Checked; SetSaveRequired(true); } void HandleDockStyleSelectedIndexChanged (object sender, EventArgs e) { string value = (sender as ToolStripComboBox).SelectedItem.ToString (); this.Dock = (DockStyle)Enum.Parse (typeof(DockStyle), value); ParentNotePanel.Dock = this.Dock; SetSaveRequired(true); } // void HandleDockDropDown (object sender, EventArgs e) // { // // fill the Dock Style Drop Down // (sender as ToolStripComboBox).Items.Clear(); // foreach (string s in Enum.GetNames(typeof(DockStyle))){ // (sender as ToolStripComboBox).Items.Add (s); // } // // } void HandleLinkNoteClick (object sender, EventArgs e) { string SourceContainerGUIDToUse = Layout.GUID; // - Shouldn't the notes store the GUID of the Master Note (not the panel? they are in?) May 2013 //cannot use Layout.ParentGUIDFromNote -- it was blank // OK: I was testing on a non-panel. So the issue becomes, can I use // one of these with a panel and fall back when not? if (Layout.ParentGuidFromNotes != Constants.BLANK) { SourceContainerGUIDToUse = Layout.ParentGuidFromNotes; } //NewMessage.Show(Layout.ParentGUID + " - " + Layout.GUID); // May 2013 - adding the caption to the string encoding. This is pulled off of with SetLink LayoutDetails.Instance.PushLink(String.Format (CoreUtilities.Links.LinkTableRecord.PageLinkFormatString, SourceContainerGUIDToUse, GuidForNote)+"*"+this.Caption); } /// <summary> /// Will be overridden in children (i.e., a RichEdit set to readonly and whatnot /// </summary> protected virtual void RespondToReadOnlyChange() { } protected virtual void HandleReadOnlyClick (object sender, EventArgs e) { this.ReadOnly = !this.ReadOnly; RespondToReadOnlyChange(); } /// <summary> /// Handles the delete layout click for a SYSTEM NOTE /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleDeleteLayoutClick (object sender, EventArgs e) { if (NewMessage.Show (Loc.Instance.GetString ("Delete?"), Loc.Instance.GetStringFmt ("Do you REALLY want to delete Layout '{0}'?", ((NoteDataXML_SystemOnly) this).GetLayoutName()), MessageBoxButtons.YesNo, null) == DialogResult.Yes) { // delete // then dispose MasterOfLayouts.DeleteLayout(((NoteDataXML_SystemOnly) this).GetLayoutGUID()); // close this one final time wihtout saving since we are now gone ((NoteDataXML_SystemOnly) this).DoCloseNote(false); } } void HandleCaptionLabelDoubleClick (object sender, EventArgs e) { if (sender != null ) { Maximize (!IsMaximized); } } /// <summary> /// Handles the delete click. SHOULD DO NOTHING IN ALL CLASSES EXCEPT THE SYSTEM NOTE /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> protected virtual void HandleCloseClick (object sender, EventArgs e) { // actual code is in the SystemOnly noet } void HandleMinimizeButtonClick (object sender, EventArgs e) { // if just click then we UnMaximize // doubleclick does a mnimize Minimize (); //Maximize (false); } void HandleMaximizeButtonClick (object sender, EventArgs e) { Maximize(true); } /// <summary> /// Brings to front and show. /// </summary> public void BringToFrontAndShow () { if (ParentNotePanel == null) { NewMessage.Show (Loc.Instance.GetStringFmt ("The note {0} with guid={1} does not have a valid parent.", this.Caption, this.GuidForNote)); } else { // 20/04/2014 -- we enable note if disabled DID NOT WORK. // if (this.Layout != null) // { // // disable false means ACTIVE // this.Layout.DisableLayout(false); // } // we always make the note visible if showing this.Visible = true; ParentNotePanel.Visible = true; ParentNotePanel.BringToFront (); if (this.Layout != null) { // // MAJOR // 05/11/2014 // This might have side-effects but the CurrentTextNote as only being set when OnEnter fired on the NoteDamaXML_RichText.cs // THE PROBLEM? // - this did not fire under most circumstances! Clicking a link to go to a note, for example. The cursor changed to the new text note // but things like Word Count/Text Operations DID NOT. // if (this is NoteDataXML_RichText) { ((NoteDataXML_RichText)this).GetRichTextBox().Focus (); Layout.CurrentTextNote = (NoteDataXML_RichText)this; } if (this.Layout.GetIsChild == true) { // get its Panel note somehow? if (this.Layout.Parent is NotePanel) { ((NotePanel)Layout.Parent).BringToFrontChild(); //this.Layout.Parent.BringToFront(); } } } //MOVE THIS TO BRINGTOFRONT override... basically whenever you want to bring a note to front, if system, we will amke the active note RespondToNoteSelection(); } } /// <summary> /// Handles the bring to front click. /// /// Will use this sort of thing more sparingly than in previous version because it caused more confusion than it helped, I think /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleBringToFrontClick (object sender, EventArgs e) { BringToFrontAndShow(); } /// <summary> /// Handles the delete note click. This is the true deleting of the note /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleDeleteNoteClick (object sender, EventArgs e) { if (Caption == CoreUtilities.Links.LinkTable.STICKY_TABLE) { NewMessage.Show (Loc.Instance.GetStringFmt ("{0} is a protected note. It cannot be renamed or deleted.", Caption)); return; } if (NewMessage.Show (Loc.Instance.GetString ("Delete?"), Loc.Instance.GetStringFmt ("Do you REALLY want to delete Note {0}?", this.Caption), MessageBoxButtons.YesNo, null) == DialogResult.Yes) { if (DeleteNote != null) { DeleteNote(this); if (Layout != null) { // getting tabs to update when the label is changed Layout.RefreshTabs(); SetSaveRequired(true); } } } } /// <summary> /// Override this method to have child classes respond to a change of Caption /// </summary> /// <param name='cap'> /// Cap. /// </param> protected virtual void CaptionChanged(string cap) { } void HandleCaptionEditorKeyDown (object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (Caption == CoreUtilities.Links.LinkTable.STICKY_TABLE) { NewMessage.Show (Loc.Instance.GetStringFmt("{0} is a protected note. It cannot be renamed or deleted.", Caption)); } else { // commit the change to the caption Caption = (sender as ToolStripTextBox).Text; CaptionChanged(Caption); SetSaveRequired (true); // so we don't need to call update for such a simple change captionLabel.Text = Caption; if (Layout != null) { // getting tabs to update when the label is changed Layout.RefreshTabs(); } } // supress key beep from pressing enter e.SuppressKeyPress = true; } } void HandleCaptionTextChanged (object sender, EventArgs e) { } void HandleCommitChangesClick (object sender, EventArgs e) { ParentNotePanel.AutoScroll = false; // ((NoteDataXML)propertyGrid.SelectedObject).Update(Layout); ((NoteDataXML)propertyGrid.SelectedObject).UpdateLocation(); SetSaveRequired(true); // close the Property View after pressing this button (July 2013) TogglePropertyView (); } void TogglePropertyView () { PropertyPanel.Visible = !PropertyPanel.Visible; if (PropertyPanel.Visible == true) { if (propertyGrid == null) { propertyGrid = new PropertyGrid (); propertyGrid.SelectedObject = this; // propertyGrid.PropertyValueChanged+= HandlePropertyValueChanged; propertyGrid.Parent = PropertyPanel; propertyGrid.Dock = DockStyle.Fill; } ParentNotePanel.AutoScroll = true; PropertyPanel.AutoScroll = true; //PropertyPanel.SendToBack(); //CaptionLabel.BringToFront(); CaptionLabel.SendToBack (); } else { ParentNotePanel.AutoScroll = false; } } void HandlePropertiesClick (object sender, EventArgs e) { TogglePropertyView (); } /// <summary> /// Handles the popup menu folder. /// Draws in list of all the FOLDERs at the current level /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> // void HandleMenuFolderMouseEnter (object sender, EventArgs e) // { // // Draw Potential Folders // (sender as ToolStripMenuItem).DropDownItems.Clear (); // ToolStripMenuItem up = (ToolStripMenuItem)(sender as ToolStripMenuItem).DropDownItems.Add (Loc.Instance.Cat.GetString ("Out of Folder")); // up.Tag = "up"; // up.Click += HandleMenuFolderClick; // // foreach (NoteDataInterface note in GetAvailableFolders()) { // // we do not add ourselves // if (note.GuidForNote != this.GuidForNote) { // ToolStripMenuItem item = (ToolStripMenuItem)(sender as ToolStripMenuItem).DropDownItems.Add (note.Caption); // item.Click += HandleMenuFolderClick; // item.Tag = note.GuidForNote; // } // } // // } void HandleFolderDropDownOpening (object sender, EventArgs e) { // Draw Potential Folders (sender as ToolStripMenuItem).DropDownItems.Clear (); ToolStripMenuItem up = (ToolStripMenuItem)(sender as ToolStripMenuItem).DropDownItems.Add (Loc.Instance.Cat.GetString ("Out of Folder")); up.Tag = "up"; up.Click += HandleMenuFolderClick; foreach (NoteDataInterface note in GetAvailableFolders()) { // we do not add ourselves if (note.GuidForNote != this.GuidForNote) { ToolStripMenuItem item = (ToolStripMenuItem)(sender as ToolStripMenuItem).DropDownItems.Add (note.Caption); item.Click += HandleMenuFolderClick; item.Tag = note.GuidForNote; } } } /// <summary> /// Handles the menu folder click. /// /// Assigns to a Folder or to a New Folder /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleMenuFolderClick (object sender, EventArgs e) { if ((sender as ToolStripMenuItem).Tag == null) { lg.Instance.Line ("NoteDataXML.HandleMenuFolderCLikc", ProblemType.WARNING, "A GUID was not assigned to this folder menu option"); } else { MoveNote (this.GuidForNote, (sender as ToolStripMenuItem).Tag.ToString ()); SetSaveRequired(true); } } void HandlePopupMenuFolder (object sender, EventArgs e) { } // set to true if I am the note being dragged bool IAmDragging = false; Point PanelMouseDownLocation ; Color lastColor; void HandleMouseMove (object sender, MouseEventArgs e) { CaptionLabel.Cursor = Cursors.Hand; if (this.Dock == DockStyle.None) { if (e.Button == MouseButtons.Left) { if (false == Layout.IsDraggingANote ) { BringToFrontAndShow (); if (false == this.LockState) { // start drag mode Layout.IsDraggingANote = true; IAmDragging = true; lastColor = CaptionLabel.BackColor; CaptionLabel.BackColor = Color.Red; PanelMouseDownLocation = e.Location; } } if (true == Layout.IsDraggingANote && true == IAmDragging) { int X = this.location.X + e.X - PanelMouseDownLocation.X; int Y = this.location.Y += e.Y - PanelMouseDownLocation.Y; // do not allow to drag off screen into non-scrollable terrain if (X < 0) { X = 0; } if (Y < 0) { Y = 0; } this.Location = new Point (X, Y); //this.location.X += e.X - PanelMouseDownLocation.X; //this.location.Y += e.Y - PanelMouseDownLocation.Y; UpdateLocation (); } } } else { EndDrag(); } } public void EndDrag () { if (null != Layout) { if (Layout.IsDraggingANote && IAmDragging) { CaptionLabel.BackColor = lastColor; Layout.IsDraggingANote = false; IAmDragging = false; } } else { //UPDATE: We can't actually clear this because we do not have a reference to it! // Not a big deal. When we clear the drag state we don't actually load the // child notes (not fully). // Therefore they do not have layouts // so in this case we just clear backcolor and person dragging //NewMessage.Show (this.Caption + " has a null Layout? How?"); //if (IAmDragging) //{ // force the removal since IamDragging is not a stored flag // we do not actually know // CaptionLabel.BackColor = lastColor; // IAmDragging = false; //} } } void HandleMouseLeave (object sender, EventArgs e) { CaptionLabel.Cursor = Cursors.Default; // suppressing this so that you only stop dragging by lifting mouse up // if (this.Dock == DockStyle.None) { // EndDrag(); // } } void HandleMouseUp (object sender, MouseEventArgs e) { if (this.Dock == DockStyle.None) { EndDrag(); } } public virtual void RespondToNoteSelection() { // signaleld from NOTEPANEL.cs // intended only for the system note to override } void HandleMouseDown (object sender, MouseEventArgs e) { // going to try moving Dragging from here, so there's // no 'jerk' when clicking on a note // you have to be dragging for a bit to kick into dragmode // if (this.Dock == DockStyle.None) { // if (e.Button == MouseButtons.Left ) { // // start moving // Layout.IsDraggingANote = true; // lastColor = CaptionLabel.BackColor; // CaptionLabel.BackColor = Color.Red; // // PanelMouseDownLocation = e.Location; // CaptionLabel.Cursor = Cursors.Hand; // } // } } Color currentColor ; Timer myTimer; public void Flash () { if (ParentNotePanel != null) { currentColor = CaptionLabel.BackColor; CaptionLabel.BackColor = Color.Blue; ParentNotePanel.Invalidate (); myTimer = new Timer (); myTimer.Tick += new EventHandler (myTimer_Tick); myTimer.Interval = 200; myTimer.Start (); lg.Instance.Line ("myTimer_Tick done", ProblemType.TEMPORARY, "timer asked to START"); } } /// <summary> /// run by timer /// /// sets color back after GUIFlash /// and then it destroys the timer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void myTimer_Tick(object sender, EventArgs e) {lg.Instance.Line("myTimer_Tick done", ProblemType.TEMPORARY, "timer tick"); if (myTimer != null) { lg.Instance.Line("myTimer_Tick done", ProblemType.TEMPORARY, "timer asked to dispose"); myTimer.Stop(); myTimer.Dispose(); myTimer = null; CaptionLabel.BackColor = currentColor; } } public virtual void UpdateAfterLoad() { // some notes will override this. // They also need to add themselves to LayoutDetails.Instance.UpdateAfterLoadList } // for use with the F6 command in mainform (hiding the system panel) public void ToggleTemporaryVisibility () { // this is NOT the same as the Visiblity propery // it is a temporary (life of application) visiblity instead if (ParentNotePanel != null) { ParentNotePanel.Visible = !ParentNotePanel.Visible; } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Collisions; namespace OptionalProject { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // game objects. Using inheritance would make this // easier, but inheritance isn't a GDD 1200 topic Burger burger; List<TeddyBear> bears = new List<TeddyBear>(); static List<Projectile> projectiles = new List<Projectile>(); List<Explosion> explosions = new List<Explosion>(); // projectile and explosion sprites. Saved so they don't have to // be loaded every time projectiles or explosions are created static Texture2D frenchFriesSprite; static Texture2D teddyBearProjectileSprite; static Texture2D explosionSpriteStrip; // spawn location support const int SPAWN_BORDER_SIZE = 100; // scoring support int score = 0; string scoreString = GameConstants.SCORE_PREFIX + 0; // health support string healthString = GameConstants.HEALTH_PREFIX + GameConstants.BURGER_INITIAL_HEALTH; bool burgerDead = false; // text display support SpriteFont font; // audio components AudioEngine audioEngine; WaveBank waveBank; SoundBank soundBank; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = GameConstants.WINDOW_WIDTH; graphics.PreferredBackBufferHeight = GameConstants.WINDOW_HEIGHT; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { RandomNumberGenerator.Initialize(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load audio content // load sprite font // load projectile and explosion sprites // add initial game objects } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // update burger // update other game objects foreach (TeddyBear bear in bears) { bear.Update(gameTime, soundBank); } foreach (Projectile projectile in projectiles) { projectile.Update(gameTime); } foreach (Explosion explosion in explosions) { explosion.Update(gameTime); } // check and resolve collisions between teddy bears // check and resolve collisions between burger and teddy bears // check and resolve collisions between burger and projectiles // check and resolve collisions between teddy bears and projectiles // clean out inactive teddy bears and add new ones as necessary // clean out inactive projectiles // clean out finished explosions base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // draw game objects //burger.Draw(spriteBatch); foreach (TeddyBear bear in bears) { bear.Draw(spriteBatch); } foreach (Projectile projectile in projectiles) { projectile.Draw(spriteBatch); } foreach (Explosion explosion in explosions) { explosion.Draw(spriteBatch); } // draw score and health spriteBatch.End(); base.Draw(gameTime); } #region Public methods /// <summary> /// Gets the projectile sprite for the given projectile type /// </summary> /// <param name="type">the projectile type</param> /// <returns>the projectile sprite for the type</returns> public static Texture2D GetProjectileSprite(ProjectileType type) { // replace with code to return correct projectile sprite based on projectile type return frenchFriesSprite; } /// <summary> /// Adds the given projectile to the game /// </summary> /// <param name="projectile">the projectile to add</param> public static void AddProjectile(Projectile projectile) { } #endregion #region Private methods /// <summary> /// Spawns a new teddy bear at a random location /// </summary> private void SpawnBear() { // generate random location // generate random velocity // create new bear // make sure we don't spawn into a collision // add new bear to list } /// <summary> /// Gets a random location using the given min and range /// </summary> /// <param name="min">the minimum</param> /// <param name="range">the range</param> /// <returns>the random location</returns> private int GetRandomLocation(int min, int range) { return min + RandomNumberGenerator.Next(range); } /// <summary> /// Gets a list of collision rectangles for all the objects in the game world /// </summary> /// <returns>the list of collision rectangles</returns> private List<Rectangle> GetCollisionRectangles() { List<Rectangle> collisionRectangles = new List<Rectangle>(); collisionRectangles.Add(burger.CollisionRectangle); foreach (TeddyBear bear in bears) { collisionRectangles.Add(bear.CollisionRectangle); } foreach (Projectile projectile in projectiles) { collisionRectangles.Add(projectile.CollisionRectangle); } foreach (Explosion explosion in explosions) { collisionRectangles.Add(explosion.CollisionRectangle); } return collisionRectangles; } /// <summary> /// Checks to see if the burger has just been killed /// </summary> private void CheckBurgerKill() { } #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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Transactions { public sealed partial class CommittableTransaction : System.Transactions.Transaction, System.IAsyncResult, System.IDisposable, System.Runtime.Serialization.ISerializable { public CommittableTransaction() { } public CommittableTransaction(System.TimeSpan timeout) { } public CommittableTransaction(System.Transactions.TransactionOptions options) { } object System.IAsyncResult.AsyncState { get { return default(object); } } System.Threading.WaitHandle System.IAsyncResult.AsyncWaitHandle { get { return default(System.Threading.WaitHandle); } } bool System.IAsyncResult.CompletedSynchronously { get { return default(bool); } } bool System.IAsyncResult.IsCompleted { get { return default(bool); } } public System.IAsyncResult BeginCommit(System.AsyncCallback asyncCallback, object asyncState) { return default(System.IAsyncResult); } public void Commit() { } public void EndCommit(System.IAsyncResult ar) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public enum DependentCloneOption { BlockCommitUntilComplete = 0, RollbackIfNotComplete = 1, } public sealed partial class DependentTransaction : System.Transactions.Transaction, System.Runtime.Serialization.ISerializable { internal DependentTransaction() { } public void Complete() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class Enlistment { internal Enlistment() { } public void Done() { } } [System.FlagsAttribute] public enum EnlistmentOptions { EnlistDuringPrepareRequired = 1, None = 0, } public enum EnterpriseServicesInteropOption { Automatic = 1, Full = 2, None = 0, } public delegate System.Transactions.Transaction HostCurrentTransactionCallback(); //[System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] // TODO: Put back when available public partial interface IDtcTransaction { void Abort(System.IntPtr reason, int retaining, int async); void Commit(int retaining, int commitType, int reserved); void GetTransactionInfo(System.IntPtr transactionInformation); } public partial interface IEnlistmentNotification { void Commit(System.Transactions.Enlistment enlistment); void InDoubt(System.Transactions.Enlistment enlistment); void Prepare(System.Transactions.PreparingEnlistment preparingEnlistment); void Rollback(System.Transactions.Enlistment enlistment); } public partial interface IPromotableSinglePhaseNotification : System.Transactions.ITransactionPromoter { void Initialize(); void Rollback(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); } public partial interface ISimpleTransactionSuperior : System.Transactions.ITransactionPromoter { void Rollback(); } public partial interface ISinglePhaseNotification : System.Transactions.IEnlistmentNotification { void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); } public enum IsolationLevel { Chaos = 5, ReadCommitted = 2, ReadUncommitted = 3, RepeatableRead = 1, Serializable = 0, Snapshot = 4, Unspecified = 6, } public partial interface ITransactionPromoter { byte[] Promote(); } public partial class PreparingEnlistment : System.Transactions.Enlistment { internal PreparingEnlistment() { } public void ForceRollback() { } public void ForceRollback(System.Exception e) { } public void Prepared() { } public byte[] RecoveryInformation() { return default(byte[]); } } public partial class SinglePhaseEnlistment : System.Transactions.Enlistment { internal SinglePhaseEnlistment() { } public void Aborted() { } public void Aborted(System.Exception e) { } public void Committed() { } public void InDoubt() { } public void InDoubt(System.Exception e) { } } public sealed partial class SubordinateTransaction : System.Transactions.Transaction { public SubordinateTransaction(System.Transactions.IsolationLevel isoLevel, System.Transactions.ISimpleTransactionSuperior superior) { } } public partial class Transaction : System.IDisposable, System.Runtime.Serialization.ISerializable { internal Transaction() { } public static System.Transactions.Transaction Current { get { return default(System.Transactions.Transaction); } set { } } public System.Transactions.IsolationLevel IsolationLevel { get { return default(System.Transactions.IsolationLevel); } } public System.Guid PromoterType { get; } public System.Transactions.TransactionInformation TransactionInformation { get { return default(System.Transactions.TransactionInformation); } } public event System.Transactions.TransactionCompletedEventHandler TransactionCompleted { add { } remove { } } public System.Transactions.Transaction Clone() { return default(System.Transactions.Transaction); } public System.Transactions.DependentTransaction DependentClone(System.Transactions.DependentCloneOption cloneOption) { return default(System.Transactions.DependentTransaction); } public void Dispose() { } public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { return default(System.Transactions.Enlistment); } public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { return default(System.Transactions.Enlistment); } public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { return default(bool); } public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification, System.Guid promoterType) { return default(bool); } public System.Transactions.Enlistment EnlistVolatile(System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { return default(System.Transactions.Enlistment); } public System.Transactions.Enlistment EnlistVolatile(System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { return default(System.Transactions.Enlistment); } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public byte[] GetPromotedToken() { return default(byte[]); } public static bool operator ==(System.Transactions.Transaction x, System.Transactions.Transaction y) { return default(bool); } public static bool operator !=(System.Transactions.Transaction x, System.Transactions.Transaction y) { return default(bool); } public System.Transactions.Enlistment PromoteAndEnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Transactions.ISinglePhaseNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { return default(System.Transactions.Enlistment); } public void Rollback() { } public void Rollback(System.Exception e) { } public void SetDistributedTransactionIdentifier(System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Guid distributedTransactionIdentifier) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class TransactionAbortedException : System.Transactions.TransactionException { public TransactionAbortedException() { } protected TransactionAbortedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionAbortedException(string message) { } public TransactionAbortedException(string message, System.Exception innerException) { } } public delegate void TransactionCompletedEventHandler(object sender, System.Transactions.TransactionEventArgs e); public partial class TransactionEventArgs : System.EventArgs { public TransactionEventArgs() { } public System.Transactions.Transaction Transaction { get { return default(System.Transactions.Transaction); } } } public partial class TransactionException : System.Exception //System.SystemException // TODO: Put back when available { protected TransactionException() { } protected TransactionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionException(string message) { } public TransactionException(string message, System.Exception innerException) { } } public partial class TransactionInDoubtException : System.Transactions.TransactionException { protected TransactionInDoubtException() { } protected TransactionInDoubtException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionInDoubtException(string message) { } public TransactionInDoubtException(string message, System.Exception innerException) { } } public partial class TransactionInformation { internal TransactionInformation() { } public System.DateTime CreationTime { get { return default(System.DateTime); } } public System.Guid DistributedIdentifier { get { return default(System.Guid); } } public string LocalIdentifier { get { return default(string); } } public System.Transactions.TransactionStatus Status { get { return default(System.Transactions.TransactionStatus); } } } public static partial class TransactionInterop { public static readonly System.Guid PromoterTypeDtc; public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction) { return default(System.Transactions.IDtcTransaction); } public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] whereabouts) { return default(byte[]); } public static System.Transactions.Transaction GetTransactionFromDtcTransaction(System.Transactions.IDtcTransaction transactionNative) { return default(System.Transactions.Transaction); } public static System.Transactions.Transaction GetTransactionFromExportCookie(byte[] cookie) { return default(System.Transactions.Transaction); } public static System.Transactions.Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { return default(System.Transactions.Transaction); } public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction) { return default(byte[]); } public static byte[] GetWhereabouts() { return default(byte[]); } } public static partial class TransactionManager { public static System.TimeSpan DefaultTimeout { get { return default(System.TimeSpan); } } public static System.Transactions.HostCurrentTransactionCallback HostCurrentCallback { get { return default(System.Transactions.HostCurrentTransactionCallback); } set { } } public static System.TimeSpan MaximumTimeout { get { return default(System.TimeSpan); } } public static event System.Transactions.TransactionStartedEventHandler DistributedTransactionStarted { add { } remove { } } public static void RecoveryComplete(System.Guid resourceManagerIdentifier) { } public static System.Transactions.Enlistment Reenlist(System.Guid resourceManagerIdentifier, byte[] recoveryInformation, System.Transactions.IEnlistmentNotification enlistmentNotification) { return default(System.Transactions.Enlistment); } } public partial class TransactionManagerCommunicationException : System.Transactions.TransactionException { protected TransactionManagerCommunicationException() { } protected TransactionManagerCommunicationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionManagerCommunicationException(string message) { } public TransactionManagerCommunicationException(string message, System.Exception innerException) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { public System.Transactions.IsolationLevel IsolationLevel { get { return default(System.Transactions.IsolationLevel); } set { } } public System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Transactions.TransactionOptions o1, System.Transactions.TransactionOptions o2) { return default(bool); } public static bool operator !=(System.Transactions.TransactionOptions o1, System.Transactions.TransactionOptions o2) { return default(bool); } } public partial class TransactionPromotionException : System.Transactions.TransactionException { protected TransactionPromotionException() { } protected TransactionPromotionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionPromotionException(string message) { } public TransactionPromotionException(string message, System.Exception innerException) { } } public sealed partial class TransactionScope : System.IDisposable { public TransactionScope() { } public TransactionScope(System.Transactions.Transaction transactionToUse) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.EnterpriseServicesInteropOption interopOption) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(Transaction transactionToUse, TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.EnterpriseServicesInteropOption interopOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public void Complete() { } public void Dispose() { } } public enum TransactionScopeAsyncFlowOption { Enabled = 1, Suppress = 0, } public enum TransactionScopeOption { Required = 0, RequiresNew = 1, Suppress = 2, } public delegate void TransactionStartedEventHandler(object sender, System.Transactions.TransactionEventArgs e); public enum TransactionStatus { Aborted = 2, Active = 0, Committed = 1, InDoubt = 3, } }
// // support.cs: Support routines to work around the fact that System.Reflection.Emit // can not introspect types that are being constructed // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2009 Novell, Inc // using System; using System.IO; using System.Text; using System.Collections.Generic; namespace Mono.CSharp { sealed class ReferenceEquality<T> : IEqualityComparer<T> where T : class { public static readonly IEqualityComparer<T> Default = new ReferenceEquality<T> (); private ReferenceEquality () { } public bool Equals (T x, T y) { return ReferenceEquals (x, y); } public int GetHashCode (T obj) { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode (obj); } } public class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>> { public Tuple (T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } public T1 Item1 { get; private set; } public T2 Item2 { get; private set; } public override int GetHashCode () { return Item1.GetHashCode () ^ Item2.GetHashCode (); } #region IEquatable<Tuple<T1,T2>> Members public bool Equals (Tuple<T1, T2> other) { return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) && EqualityComparer<T2>.Default.Equals (Item2, other.Item2); } #endregion } public class Tuple<T1, T2, T3> : IEquatable<Tuple<T1, T2, T3>> { public Tuple (T1 item1, T2 item2, T3 item3) { Item1 = item1; Item2 = item2; Item3 = item3; } public T1 Item1 { get; private set; } public T2 Item2 { get; private set; } public T3 Item3 { get; private set; } public override int GetHashCode () { return Item1.GetHashCode () ^ Item2.GetHashCode () ^ Item3.GetHashCode (); } #region IEquatable<Tuple<T1,T2>> Members public bool Equals (Tuple<T1, T2, T3> other) { return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) && EqualityComparer<T2>.Default.Equals (Item2, other.Item2) && EqualityComparer<T3>.Default.Equals (Item3, other.Item3); } #endregion } static class Tuple { public static Tuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2) { return new Tuple<T1, T2> (item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3> (T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3> (item1, item2, item3); } } static class ArrayComparer { public static bool IsEqual<T> (T[] array1, T[] array2) { if (array1 == null || array2 == null) return array1 == array2; var eq = EqualityComparer<T>.Default; for (int i = 0; i < array1.Length; ++i) { if (!eq.Equals (array1[i], array2[i])) { return false; } } return true; } } /// <summary> /// This is an arbitrarily seekable StreamReader wrapper. /// /// It uses a self-tuning buffer to cache the seekable data, /// but if the seek is too far, it may read the underly /// stream all over from the beginning. /// </summary> public class SeekableStreamReader : IDisposable { StreamReader reader; Stream stream; static char[] buffer; int read_ahead_length; // the length of read buffer int buffer_start; // in chars int char_count; // count of filled characters in buffer[] int pos; // index into buffer[] public SeekableStreamReader (Stream stream, Encoding encoding) { this.stream = stream; const int default_read_ahead = 2048; InitializeStream (default_read_ahead); reader = new StreamReader (stream, encoding, true); } public void Dispose () { // Needed to release stream reader buffers reader.Dispose (); } void InitializeStream (int read_length_inc) { read_ahead_length += read_length_inc; int required_buffer_size = read_ahead_length * 2; if (buffer == null || buffer.Length < required_buffer_size) buffer = new char [required_buffer_size]; stream.Position = 0; buffer_start = char_count = pos = 0; } /// <remarks> /// This value corresponds to the current position in a stream of characters. /// The StreamReader hides its manipulation of the underlying byte stream and all /// character set/decoding issues. Thus, we cannot use this position to guess at /// the corresponding position in the underlying byte stream even though there is /// a correlation between them. /// </remarks> public int Position { get { return buffer_start + pos; } set { // // If the lookahead was too small, re-read from the beginning. Increase the buffer size while we're at it // This should never happen until we are parsing some weird source code // if (value < buffer_start) { InitializeStream (read_ahead_length); // // Discard buffer data after underlying stream changed position // Cannot use handy reader.DiscardBufferedData () because it for // some strange reason resets encoding as well // reader = new StreamReader (stream, reader.CurrentEncoding, true); } while (value > buffer_start + char_count) { pos = char_count; if (!ReadBuffer ()) throw new InternalErrorException ("Seek beyond end of file: " + (buffer_start + char_count - value)); } pos = value - buffer_start; } } bool ReadBuffer () { int slack = buffer.Length - char_count; // // read_ahead_length is only half of the buffer to deal with // reads ahead and moves back without re-reading whole buffer // if (slack <= read_ahead_length) { // // shift the buffer to make room for read_ahead_length number of characters // int shift = read_ahead_length - slack; Array.Copy (buffer, shift, buffer, 0, char_count - shift); // Update all counters pos -= shift; char_count -= shift; buffer_start += shift; slack += shift; } char_count += reader.Read (buffer, char_count, slack); return pos < char_count; } public int Peek () { if ((pos >= char_count) && !ReadBuffer ()) return -1; return buffer [pos]; } public int Read () { if ((pos >= char_count) && !ReadBuffer ()) return -1; return buffer [pos++]; } } public class UnixUtils { [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")] extern static int _isatty (int fd); public static bool isatty (int fd) { try { return _isatty (fd) == 1; } catch { return false; } } } /// <summary> /// An exception used to terminate the compiler resolution phase and provide completions /// </summary> /// <remarks> /// This is thrown when we want to return the completions or /// terminate the completion process by AST nodes used in /// the completion process. /// </remarks> public class CompletionResult : Exception { string [] result; string base_text; public CompletionResult (string base_text, string [] res) { if (base_text == null) throw new ArgumentNullException ("base_text"); this.base_text = base_text; result = res; Array.Sort (result); } public string [] Result { get { return result; } } public string BaseText { get { return base_text; } } } }
// -------------------------------- // <copyright file="ObjectGenerator.cs"> // Copyright (c) 2015 All rights reserved. // </copyright> // <author>dallesho</author> // <date>05/30/2015</date> // --------------------------------- namespace RelativeStrengthCalculator.Api.Areas.HelpPage.SampleGeneration { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator _simpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) => this.GenerateObject(type, new Dictionary<Type, object>()); [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return this._simpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) => genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return ((IEnumerable)list).AsQueryable(); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); private long _index; [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() => new Dictionary<Type, Func<long, object>> { { typeof(bool), index => true }, { typeof(byte), index => (byte)64 }, { typeof(char), index => (char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(decimal), index => (decimal)index }, { typeof(double), index => index + 0.1 }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(short), index => (short)(index % short.MaxValue) }, { typeof(int), index => (int)(index % int.MaxValue) }, { typeof(long), index => index }, { typeof(object), index => new object() }, { typeof(sbyte), index => (sbyte)64 }, { typeof(float), index => (float)(index + 0.1) }, { typeof(string), index => { return string.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(ushort), index => (ushort)(index % ushort.MaxValue) }, { typeof(uint), index => (uint)(index % uint.MaxValue) }, { typeof(ulong), index => (ulong)index }, { typeof(Uri), index => { return new Uri( string.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } } } ; public static bool CanGenerateObject(Type type) => DefaultGenerators.ContainsKey(type); public object GenerateObject(Type type) => DefaultGenerators[type](++this._index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.IO { /// <summary>Provides an implementation of FileSystem for Unix systems.</summary> internal sealed partial class UnixFileSystem : FileSystem { internal const int DefaultBufferSize = 4096; public override int MaxPath { get { return Interop.Sys.MaxPath; } } public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } } public override FileStream Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new FileStream(fullPath, mode, access, share, bufferSize, options); } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { // The destination path may just be a directory into which the file should be copied. // If it is, append the filename from the source onto the destination directory if (DirectoryExists(destFullPath)) { destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath)); } // Copy the contents of the file from the source to the destination, creating the destination in the process using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.None)) using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultBufferSize, FileOptions.None)) { Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle)); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { if (destBackupFullPath != null) { // We're backing up the destination file to the backup file, so we need to first delete the backup // file, if it exists. If deletion fails for a reason other than the file not existing, fail. if (Interop.Sys.Unlink(destBackupFullPath) != 0) { Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo(); if (errno.Error != Interop.Error.ENOENT) { throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath); } } // Now that the backup is gone, link the backup to point to the same file as destination. // This way, we don't lose any data in the destination file, no copy is necessary, etc. Interop.CheckIo(Interop.Sys.Link(destFullPath, destBackupFullPath), destFullPath); } else { // There is no backup file. Just make sure the destination file exists, throwing if it doesn't. Interop.Sys.FileStatus ignored; if (Interop.Sys.Stat(destFullPath, out ignored) != 0) { Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo(); if (errno.Error == Interop.Error.ENOENT) { throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath); } } } // Finally, rename the source to the destination, overwriting the destination. Interop.CheckIo(Interop.Sys.Rename(sourceFullPath, destFullPath)); } public override void MoveFile(string sourceFullPath, string destFullPath) { // The desired behavior for Move(source, dest) is to not overwrite the destination file // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists, // link/unlink are used instead. However, if the source path and the dest path refer to // the same file, then do a rename rather than a link and an unlink. This is important // for case-insensitive file systems (e.g. renaming a file in a way that just changes casing), // so that we support changing the casing in the naming of the file. If this fails in any // way (e.g. source file doesn't exist, dest file doesn't exist, rename fails, etc.), we // just fall back to trying the link/unlink approach and generating any exceptional messages // from there as necessary. Interop.Sys.FileStatus sourceStat, destStat; if (Interop.Sys.LStat(sourceFullPath, out sourceStat) == 0 && // source file exists Interop.Sys.LStat(destFullPath, out destStat) == 0 && // dest file exists sourceStat.Dev == destStat.Dev && // source and dest are on the same device sourceStat.Ino == destStat.Ino && // and source and dest are the same file on that device Interop.Sys.Rename(sourceFullPath, destFullPath) == 0) // try the rename { // Renamed successfully. return; } if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0) { // If link fails, we can fall back to doing a full copy, but we'll only do so for // cases where we expect link could fail but such a copy could succeed. We don't // want to do so for all errors, because the copy could incur a lot of cost // even if we know it'll eventually fail, e.g. EROFS means that the source file // system is read-only and couldn't support the link being added, but if it's // read-only, then the move should fail any way due to an inability to delete // the source file. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file { CopyFile(sourceFullPath, destFullPath, overwrite: false); } else { // The operation failed. Within reason, try to determine which path caused the problem // so we can throw a detailed exception. string path = null; bool isDirectory = false; if (errorInfo.Error == Interop.Error.ENOENT) { if (!Directory.Exists(Path.GetDirectoryName(destFullPath))) { // The parent directory of destFile can't be found. // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundexception. path = destFullPath; isDirectory = true; } else { path = sourceFullPath; } } else if (errorInfo.Error == Interop.Error.EEXIST) { path = destFullPath; } throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory); } } DeleteFile(sourceFullPath); } public override void DeleteFile(string fullPath) { if (Interop.Sys.Unlink(fullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // ENOENT means it already doesn't exist; nop if (errorInfo.Error != Interop.Error.ENOENT) { if (errorInfo.Error == Interop.Error.EISDIR) errorInfo = Interop.Error.EACCES.Info(); throw Interop.GetExceptionForIoErrno(errorInfo, fullPath); } } } public override void CreateDirectory(string fullPath) { // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory. int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) { length--; } // For paths that are only // or /// if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1])) { throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath)); } // We can save a bunch of work if the directory we want to create already exists. if (DirectoryExists(fullPath)) { return; } // Attempt to figure out which directories don't exist, and only create the ones we need. bool somepathexists = false; Stack<string> stackDir = new Stack<string>(); int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing { stackDir.Push(dir); } else { somepathexists = true; } while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) { i--; } i--; } } int count = stackDir.Count; if (count == 0 && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } return; } // Create all the directories int result = 0; Interop.ErrorInfo firstError = default(Interop.ErrorInfo); string errorString = fullPath; while (stackDir.Count > 0) { string name = stackDir.Pop(); if (name.Length >= MaxDirectoryPath) { throw new PathTooLongException(SR.IO_PathTooLong); } // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally). // We do the same. result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask); if (result < 0 && firstError.Error == 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // While we tried to avoid creating directories that don't // exist above, there are a few cases that can fail, e.g. // a race condition where another process or thread creates // the directory first, or there's a file at the location. if (errorInfo.Error != Interop.Error.EEXIST) { firstError = errorInfo; } else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES)) { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. firstError = errorInfo; errorString = name; } } } // Only throw an exception if creating the exact directory we wanted failed to work correctly. if (result < 0 && firstError.Error != 0) { throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true); } } public override void MoveDirectory(string sourceFullPath, string destFullPath) { // Windows doesn't care if you try and copy a file via "MoveDirectory"... if (FileExists(sourceFullPath)) { // ... but it doesn't like the source to have a trailing slash ... // On Windows we end up with ERROR_INVALID_NAME, which is // "The filename, directory name, or volume label syntax is incorrect." // // This surfaces as a IOException, if we let it go beyond here it would // give DirectoryNotFound. if (PathHelpers.EndsInDirectorySeparator(sourceFullPath)) throw new IOException(SR.Format(SR.IO_PathNotFound_Path, sourceFullPath)); // ... but it doesn't care if the destination has a trailing separator. destFullPath = PathHelpers.TrimEndingDirectorySeparator(destFullPath); } if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: // match Win32 exception throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno); default: throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true); } } } public override void RemoveDirectory(string fullPath, bool recursive) { var di = new DirectoryInfo(fullPath); if (!di.Exists) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true); } private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound) { Exception firstException = null; if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { DeleteFile(directory.FullName); return; } if (recursive) { try { foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { if (!ShouldIgnoreDirectory(Path.GetFileName(item))) { try { var childDirectory = new DirectoryInfo(item); if (childDirectory.Exists) { RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false); } else { DeleteFile(item); } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } } } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } if (firstException != null) { throw firstException; } } if (Interop.Sys.RmDir(directory.FullName) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: case Interop.Error.EPERM: case Interop.Error.EROFS: case Interop.Error.EISDIR: throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception case Interop.Error.ENOENT: if (!throwOnTopLevelDirectoryNotFound) { return; } goto default; default: throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true); } } } public override bool DirectoryExists(string fullPath) { Interop.ErrorInfo ignored; return DirectoryExists(fullPath, out ignored); } private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo) { return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo); } public override bool FileExists(string fullPath) { Interop.ErrorInfo ignored; // Windows doesn't care about the trailing separator return FileExists(PathHelpers.TrimEndingDirectorySeparator(fullPath), Interop.Sys.FileTypes.S_IFREG, out ignored); } private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo) { Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR); Interop.Sys.FileStatus fileinfo; errorInfo = default(Interop.ErrorInfo); // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate // based on the symlink itself. if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 && Interop.Sys.LStat(fullPath, out fileinfo) < 0) { errorInfo = Interop.Sys.GetLastErrorInfo(); return false; } // Something exists at this path. If the caller is asking for a directory, return true if it's // a directory and false for everything else. If the caller is asking for a file, return false for // a directory and true for everything else. return (fileType == Interop.Sys.FileTypes.S_IFDIR) == ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); } public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Files: return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new FileInfo(path, null)); case SearchTarget.Directories: return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new DirectoryInfo(path, null)); default: return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ? (FileSystemInfo)new DirectoryInfo(path, null) : (FileSystemInfo)new FileInfo(path, null)); } } private sealed class FileSystemEnumerable<T> : IEnumerable<T> { private readonly PathPair _initialDirectory; private readonly string _searchPattern; private readonly SearchOption _searchOption; private readonly bool _includeFiles; private readonly bool _includeDirectories; private readonly Func<string, bool, T> _translateResult; private IEnumerator<T> _firstEnumerator; internal FileSystemEnumerable( string userPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget, Func<string, bool, T> translateResult) { // Basic validation of the input path if (userPath == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrWhiteSpace(userPath)) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } // Validate and normalize the search pattern. If after doing so it's empty, // matching Win32 behavior we can skip all additional validation and effectively // return an empty enumerable. searchPattern = NormalizeSearchPattern(searchPattern); if (searchPattern.Length > 0) { PathHelpers.CheckSearchPattern(searchPattern); PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern); // If the search pattern contains any paths, make sure we factor those into // the user path, and then trim them off. int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar); if (lastSlash >= 0) { if (lastSlash >= 1) { userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash)); } searchPattern = searchPattern.Substring(lastSlash + 1); } string fullPath = Path.GetFullPath(userPath); // Store everything for the enumerator _initialDirectory = new PathPair(userPath, fullPath); _searchPattern = searchPattern; _searchOption = searchOption; _includeFiles = (searchTarget & SearchTarget.Files) != 0; _includeDirectories = (searchTarget & SearchTarget.Directories) != 0; _translateResult = translateResult; } // Open the first enumerator so that any errors are propagated synchronously. _firstEnumerator = Enumerate(); } public IEnumerator<T> GetEnumerator() { return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerator<T> Enumerate() { return Enumerate( _initialDirectory.FullPath != null ? OpenDirectory(_initialDirectory.FullPath) : null); } private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle) { if (dirHandle == null) { // Empty search yield break; } Debug.Assert(!dirHandle.IsInvalid); Debug.Assert(!dirHandle.IsClosed); // Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories // Lazily-initialized only if we find subdirectories that will be explored. Stack<PathPair> toExplore = null; PathPair dirPath = _initialDirectory; while (dirHandle != null) { try { // Read each entry from the enumerator Interop.Sys.DirectoryEntry dirent; while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0) { // Get from the dir entry whether the entry is a file or directory. // We classify everything as a file unless we know it to be a directory. bool isDir; if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR) { // We know it's a directory. isDir = true; } else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN) { // It's a symlink or unknown: stat to it to see if we can resolve it to a directory. // If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file. Interop.ErrorInfo errnoIgnored; isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored); } else { // Otherwise, treat it as a file. This includes regular files, FIFOs, etc. isDir = false; } // Yield the result if the user has asked for it. In the case of directories, // always explore it by pushing it onto the stack, regardless of whether // we're returning directories. if (isDir) { if (!ShouldIgnoreDirectory(dirent.InodeName)) { string userPath = null; if (_searchOption == SearchOption.AllDirectories) { if (toExplore == null) { toExplore = new Stack<PathPair>(); } userPath = Path.Combine(dirPath.UserPath, dirent.InodeName); toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName))); } if (_includeDirectories && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true); } } } else if (_includeFiles && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false); } } } finally { // Close the directory enumerator dirHandle.Dispose(); dirHandle = null; } if (toExplore != null && toExplore.Count > 0) { // Open the next directory. dirPath = toExplore.Pop(); dirHandle = OpenDirectory(dirPath.FullPath); } } } private static string NormalizeSearchPattern(string searchPattern) { if (searchPattern == "." || searchPattern == "*.*") { searchPattern = "*"; } else if (PathHelpers.EndsInDirectorySeparator(searchPattern)) { searchPattern += "*"; } return searchPattern; } private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath) { Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath); if (handle.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true); } return handle; } } /// <summary>Determines whether the specified directory name should be ignored.</summary> /// <param name="name">The name to evaluate.</param> /// <returns>true if the name is "." or ".."; otherwise, false.</returns> private static bool ShouldIgnoreDirectory(string name) { return name == "." || name == ".."; } public override string GetCurrentDirectory() { return Interop.Sys.GetCwd(); } public override void SetCurrentDirectory(string fullPath) { Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true); } public override FileAttributes GetAttributes(string fullPath) { return new FileInfo(fullPath, null).Attributes; } public override void SetAttributes(string fullPath, FileAttributes attributes) { new FileInfo(fullPath, null).Attributes = attributes; } public override DateTimeOffset GetCreationTime(string fullPath) { return new FileInfo(fullPath, null).CreationTime; } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.CreationTime = time; } public override DateTimeOffset GetLastAccessTime(string fullPath) { return new FileInfo(fullPath, null).LastAccessTime; } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastAccessTime = time; } public override DateTimeOffset GetLastWriteTime(string fullPath) { return new FileInfo(fullPath, null).LastWriteTime; } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastWriteTime = time; } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
using System; using System.Collections; using Server.Network; using Server.Items; using Server.Mobiles; namespace Server.Items.Crops { //naga public class OnaxSeed : BaseCrop { // return true to allow planting on Dirt Item (ItemID 0x32C9) // See CropHelper.cs for other overriddable types public override bool CanGrowGarden { get { return true; } } [Constructable] public OnaxSeed() : this(1) { } [Constructable] public OnaxSeed(int amount) : base(0xF27) { Stackable = true; Weight = .5; Hue = 0x5E2; Movable = true; Amount = amount; Name = AgriTxt.Seed + " de Tolonax"; } public override void OnDoubleClick(Mobile from) { if (from.Mounted && !CropHelper.CanWorkMounted) { from.SendMessage(AgriTxt.CannotWorkMounted); return; } Point3D m_pnt = from.Location; Map m_map = from.Map; if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1042010); //You must have the object in your backpack to use it. return; } else if (!CropHelper.CheckCanGrow(this, m_map, m_pnt.X, m_pnt.Y)) { from.SendMessage(AgriTxt.CannotGrowHere); return; } //check for BaseCrop on this tile ArrayList cropshere = CropHelper.CheckCrop(m_pnt, m_map, 0); if (cropshere.Count > 0) { from.SendMessage(AgriTxt.AlreadyCrop); return; } //check for over planting prohibt if 4 maybe 3 neighboring crops ArrayList cropsnear = CropHelper.CheckCrop(m_pnt, m_map, 2);//1 if ((cropsnear.Count > 1) || ((cropsnear.Count == 1) && Utility.RandomBool()))//3 { from.SendMessage(AgriTxt.TooMuchCrops); return; } if (this.BumpZ) ++m_pnt.Z; if (!from.Mounted) from.Animate(32, 5, 1, true, false, 0); // Bow from.SendMessage(AgriTxt.CropPlanted); this.Consume(); Item item = new OnaxSapling();// from ); item.Location = m_pnt; item.Map = m_map; } public OnaxSeed(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } //naga public class OnaxSapling : BaseCrop { public Timer thisTimer; public DateTime treeTime; [CommandProperty(AccessLevel.GameMaster)] public String FullGrown { get { return treeTime.ToString("T"); } } [Constructable] public OnaxSapling() : base(Utility.RandomList(0xCA6, 0xCA6)) { Movable = false; Name = AgriTxt.Seedling + " de Tolonax"; init(this); } public static void init(OnaxSapling plant) { TimeSpan delay = TreeHelper.SaplingTime; plant.treeTime = DateTime.Now + delay; plant.thisTimer = new TreeHelper.TreeTimer(plant, typeof(OnaxTree), delay); plant.thisTimer.Start(); } public OnaxSapling(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); init(this); } } public class OnaxTree : BaseTree { public Item i_trunk; private Timer chopTimer; private const int max = 12; private DateTime lastpicked; private int m_yield; public Timer regrowTimer; [CommandProperty(AccessLevel.GameMaster)] public int Yield { get { return m_yield; } set { m_yield = value; } } public int Capacity { get { return max; } } public DateTime LastPick { get { return lastpicked; } set { lastpicked = value; } } [Constructable] public OnaxTree(Point3D pnt, Map map) : base(Utility.RandomList(0xC9E, 0xC9E)) // leaves { Movable = false; MoveToWorld(pnt, map); Name = "Tolonax"; int trunkID = 0x1B1F; // ((Item)this).ItemID - 2; i_trunk = new TreeTrunk(trunkID, this); i_trunk.MoveToWorld(pnt, map); init(this, false); } public static void init(OnaxTree plant, bool full) { plant.LastPick = DateTime.Now; plant.regrowTimer = new FruitTimer(plant); if (full) { plant.Yield = plant.Capacity; } else { plant.Yield = 0; plant.regrowTimer.Start(); } } public override void OnAfterDelete() { if ((i_trunk != null) && (!i_trunk.Deleted)) i_trunk.Delete(); base.OnAfterDelete(); } public override void OnDoubleClick(Mobile from) { if (from.Mounted && !TreeHelper.CanPickMounted) { from.SendMessage(AgriTxt.CannotWorkMounted); return; } if (DateTime.Now > lastpicked.AddSeconds(3)) // 3 seconds between picking { lastpicked = DateTime.Now; int lumberValue = (int)from.Skills[SkillName.Lumberjacking].Value / 5; if (from.Mounted) ++lumberValue; if (lumberValue < 7) { from.SendMessage(AgriTxt.DunnoHowTo); return; } if (from.InRange(this.GetWorldLocation(), 2)) { if (m_yield < 1) { from.SendMessage(AgriTxt.NoCrop); } else //check skill { from.Direction = from.GetDirectionTo(this); from.Animate(from.Mounted ? 26 : 17, 7, 1, true, false, 0); if (lumberValue > m_yield) lumberValue = m_yield + 1; int pick = Utility.Random(lumberValue); if (pick == 0) { from.SendMessage(AgriTxt.ZeroPicked); return; } m_yield -= pick; from.SendMessage(AgriTxt.YouPick + " {0} Onax{1}!", pick, (pick == 1 ? "" : "s")); //PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", m_yield )); Onax crop = new Onax(pick); // naga fruit from.AddToBackpack(crop); if (!regrowTimer.Running) { regrowTimer.Start(); } } } else { from.SendLocalizedMessage(500446); // That is too far away. } } } private class FruitTimer : Timer { private OnaxTree i_plant; public FruitTimer(OnaxTree plant) : base(TimeSpan.FromSeconds(900), TimeSpan.FromSeconds(30)) { Priority = TimerPriority.OneSecond; i_plant = plant; } protected override void OnTick() { if ((i_plant != null) && (!i_plant.Deleted)) { int current = i_plant.Yield; if (++current >= i_plant.Capacity) { current = i_plant.Capacity; Stop(); } else if (current <= 0) current = 1; i_plant.Yield = current; //i_plant.PublicOverheadMessage( MessageType.Regular, 0x22, false, string.Format( "{0}", current )); } else Stop(); } } public void Chop(Mobile from) { if (from.InRange(this.GetWorldLocation(), 2)) { if ((chopTimer == null) || (!chopTimer.Running)) { if ((TreeHelper.TreeOrdinance) && (from.AccessLevel == AccessLevel.Player)) { if (from.Region is Regions.GuardedRegion) from.CriminalAction(true); } chopTimer = new TreeHelper.ChopAction(from); Point3D pnt = this.Location; Map map = this.Map; from.Direction = from.GetDirectionTo(this); chopTimer.Start(); double lumberValue = from.Skills[SkillName.Lumberjacking].Value / 100; if ((lumberValue > .5) && (Utility.RandomDouble() <= lumberValue)) { Onax fruit = new Onax((int)Utility.Random(13) + m_yield); from.AddToBackpack(fruit); int cnt = Utility.Random((int)(lumberValue * 10) + 1); Log logs = new Log(cnt); // Fruitwood Logs ?? from.AddToBackpack(logs); FruitTreeStump i_stump = new FruitTreeStump(typeof(OnaxTree)); Timer poof = new StumpTimer(this, i_stump, from); poof.Start(); } else from.SendLocalizedMessage(500495); // You hack at the tree for a while, but fail to produce any useable wood. //PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", lumberValue )); } } else from.SendLocalizedMessage(500446); // That is too far away. } private class StumpTimer : Timer { private OnaxTree i_tree; private FruitTreeStump i_stump; private Mobile m_chopper; public StumpTimer(OnaxTree Tree, FruitTreeStump Stump, Mobile from) : base(TimeSpan.FromMilliseconds(5500)) { Priority = TimerPriority.TenMS; i_tree = Tree; i_stump = Stump; m_chopper = from; } protected override void OnTick() { i_stump.MoveToWorld(i_tree.Location, i_tree.Map); i_tree.Delete(); m_chopper.SendMessage(AgriTxt.LogsAndFruits); } } public override void OnChop(Mobile from) { if (!this.Deleted) Chop(from); } public OnaxTree(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); writer.Write((Item)i_trunk); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); Item item = reader.ReadItem(); if (item != null) i_trunk = item; init(this, true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // Description: // This class represents a PackageRelationshipSelector. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; // for Debug.Assert namespace System.IO.Packaging { /// <summary> /// This class is used to represent a PackageRelationship selector. PackageRelationships can be /// selected based on their Type or ID. This class will specify what the selection is based on and /// what the actual criteria is. </summary> public sealed class PackageRelationshipSelector { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ #region Public Constructor /// <summary> /// Constructor /// </summary> /// <param name="sourceUri">Source Uri of the PackagePart or PackageRoot ("/") that owns the relationship</param> /// <param name="selectorType">PackageRelationshipSelectorType enum representing the type of the selectionCriteria</param> /// <param name="selectionCriteria">The actual string that is used to select the relationships</param> /// <exception cref="ArgumentNullException">If sourceUri is null</exception> /// <exception cref="ArgumentNullException">If selectionCriteria is null</exception> /// <exception cref="ArgumentOutOfRangeException">If selectorType Enumeration does not have a valid value</exception> /// <exception cref="System.Xml.XmlException">If PackageRelationshipSelectorType.Id and selection criteria is not valid Xsd Id</exception> /// <exception cref="ArgumentException">If PackageRelationshipSelectorType.Type and selection criteria is not valid relationship type</exception> /// <exception cref="ArgumentException">If sourceUri is not "/" to indicate the PackageRoot, then it must conform to the /// valid PartUri syntax</exception> public PackageRelationshipSelector(Uri sourceUri, PackageRelationshipSelectorType selectorType, string selectionCriteria) { if (sourceUri == null) throw new ArgumentNullException(nameof(sourceUri)); if (selectionCriteria == null) throw new ArgumentNullException(nameof(selectionCriteria)); //If the sourceUri is not equal to "/", it must be a valid part name. if (Uri.Compare(sourceUri, PackUriHelper.PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal) != 0) sourceUri = PackUriHelper.ValidatePartUri(sourceUri); //selectionCriteria is tested here as per the value of the selectorType. //If selectionCriteria is empty string we will throw the appropriate error message. if (selectorType == PackageRelationshipSelectorType.Type) InternalRelationshipCollection.ThrowIfInvalidRelationshipType(selectionCriteria); else if (selectorType == PackageRelationshipSelectorType.Id) InternalRelationshipCollection.ThrowIfInvalidXsdId(selectionCriteria); else throw new ArgumentOutOfRangeException(nameof(selectorType)); _sourceUri = sourceUri; _selectionCriteria = selectionCriteria; _selectorType = selectorType; } #endregion Public Constructor //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// This is a uri to the parent PackagePart to which this relationship belongs. /// </summary> /// <value>PackagePart</value> public Uri SourceUri { get { return _sourceUri; } } /// <summary> /// Enumeration value indicating the interpretations of the SelectionCriteria. /// </summary> /// <value></value> public PackageRelationshipSelectorType SelectorType { get { return _selectorType; } } /// <summary> /// Selection Criteria - actual value (could be ID or type) on which the selection is based /// </summary> /// <value></value> public string SelectionCriteria { get { return _selectionCriteria; } } #endregion Public Properties //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// This method returns the list of selected PackageRelationships as per the /// given criteria, from a part in the Package provided /// </summary> /// <param name="package">Package object from which we get the relationsips</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If package parameter is null</exception> public List<PackageRelationship> Select(Package package) { if (package == null) { throw new ArgumentNullException(nameof(package)); } List<PackageRelationship> relationships = new List<PackageRelationship>(0); switch (SelectorType) { case PackageRelationshipSelectorType.Id: if (SourceUri.Equals(PackUriHelper.PackageRootUri)) { if (package.RelationshipExists(SelectionCriteria)) relationships.Add(package.GetRelationship(SelectionCriteria)); } else { if (package.PartExists(SourceUri)) { PackagePart part = package.GetPart(SourceUri); if (part.RelationshipExists(SelectionCriteria)) relationships.Add(part.GetRelationship(SelectionCriteria)); } } break; case PackageRelationshipSelectorType.Type: if (SourceUri.Equals(PackUriHelper.PackageRootUri)) { foreach (PackageRelationship r in package.GetRelationshipsByType(SelectionCriteria)) relationships.Add(r); } else { if (package.PartExists(SourceUri)) { foreach (PackageRelationship r in package.GetPart(SourceUri).GetRelationshipsByType(SelectionCriteria)) relationships.Add(r); } } break; default: //Debug.Assert is fine here since the parameters have already been validated. And all the properties are //readonly Debug.Assert(false, "This option should never be called"); break; } return relationships; } #endregion Public Methods //------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private Uri _sourceUri; private string _selectionCriteria; private PackageRelationshipSelectorType _selectorType; #endregion Private Members } }
(>= (f108 (var x4)) (var x4)) (>= (f109 (var x4)) (f108 (var x4))) (>= (f110 (var x2)) (var x2)) (>= (f111 (var x4)) (f109 (var x4))) (>= (f112 (var x50)) (var x50)) (>= (f113 (var x51)) (var x51)) (>= (f7 (var x50) (f114 (var x2))) (f1 (f110 (var x2)) (f112 (var x50)))) (>= (+ (f8 (var x50) (f114 (var x2))) (var x51)) (+ (f2 (f110 (var x2)) (f112 (var x50))) (f113 (var x51)))) (>= (f115 (var x2) (var x4) (var x50) (var x51)) (+ (f3 (f110 (var x2)) (f112 (var x50)) (f113 (var x51))) (f111 (var x4)))) (>= (f116 (var x3)) (var x3)) (>= (f117 (var x2) (var x3) (var x4) (var x50) (var x51)) (+ (f11 (f114 (var x2)) (f116 (var x3)) (f117 (var x2) (var x3) (var x4) (var x50) (var x51))) (f115 (var x2) (var x4) (var x50) (var x51)))) (>= (f118 (var x2) (var x3) (var x4) (var x50) (var x51)) (+ (f10 (f114 (var x2)) (f116 (var x3))) (f117 (var x2) (var x3) (var x4) (var x50) (var x51)))) (>= (f4 (var x2) (var x3)) (f9 (f114 (var x2)) (f116 (var x3)))) (>= (+ (f5 (var x2) (var x3)) (var x4)) (+ (f118 (var x2) (var x3) (var x4) (var x50) (var x51)) 1)) (>= (f119 (var x8)) (var x8)) (>= (f120 (var x8)) (f119 (var x8))) (>= (f121 (var x8)) (f120 (var x8))) (>= (f122 (var x10)) (var x10)) (>= (f123 (var x8)) (f121 (var x8))) (>= (f124 (var x7)) (var x7)) (>= (f125 (var x7) (var x8) (var x10)) (+ (f3 (f122 (var x10)) (f124 (var x7)) (f125 (var x7) (var x8) (var x10))) (f123 (var x8)))) (>= (f126 (var x7) (var x10)) (f1 (f122 (var x10)) (f124 (var x7)))) (>= (f127 (var x7) (var x8) (var x10)) (+ (f2 (f122 (var x10)) (f124 (var x7))) (f125 (var x7) (var x8) (var x10)))) (>= (f128 (var x7) (var x8) (var x10)) (f127 (var x7) (var x8) (var x10))) (>= (f1 (+ (var x10) 1) (var x7)) (+ (f126 (var x7) (var x10)) 1)) (>= (+ (f2 (+ (var x10) 1) (var x7)) (var x8)) (+ (f128 (var x7) (var x8) (var x10)) 1)) (>= (f129 (var x14)) (var x14)) (>= (f1 0 (var x13)) (var x13)) (>= (+ (f2 0 (var x13)) (var x14)) (+ (f129 (var x14)) 1)) (>= (f130 (var x18)) (var x18)) (>= (f131 (var x19)) (var x19)) (>= (f132 (var x17) (var x18)) (f7 (f130 (var x18)) (var x17))) (>= (f133 (var x17) (var x18) (var x19)) (+ (f8 (f130 (var x18)) (var x17)) (f131 (var x19)))) (>= (f134 (var x17) (var x18) (var x19)) (+ (f8 (f132 (var x17) (var x18)) (var x17)) (f133 (var x17) (var x18) (var x19)))) (>= (f9 (var x17) (var x18)) (f7 (f132 (var x17) (var x18)) (var x17))) (>= (+ (f10 (var x17) (var x18)) (var x19)) (+ (f134 (var x17) (var x18) (var x19)) 1))
/* * 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. */ // ReSharper disable UnusedVariable // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedAutoPropertyAccessor.Local namespace Apache.Ignite.Core.Tests { using System; using System.CodeDom.Compiler; using System.Collections.Generic; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Tests for executable. /// </summary> public class ExecutableTest { /** Spring configuration path. */ private static readonly string SpringCfgPath = "config\\compute\\compute-standalone.xml"; /** Min memory Java task. */ private const string MinMemTask = "org.apache.ignite.platform.PlatformMinMemoryTask"; /** Max memory Java task. */ private const string MaxMemTask = "org.apache.ignite.platform.PlatformMaxMemoryTask"; /** Grid. */ private IIgnite _grid; /// <summary> /// Test fixture set-up routine. /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { TestUtils.KillProcesses(); _grid = Ignition.Start(Configuration(SpringCfgPath)); } /// <summary> /// Test fixture tear-down routine. /// </summary> [TestFixtureTearDown] public void TestFixtureTearDown() { Ignition.StopAll(true); TestUtils.KillProcesses(); } /// <summary> /// Set-up routine. /// </summary> [SetUp] public void SetUp() { TestUtils.KillProcesses(); Assert.IsTrue(_grid.WaitTopology(1)); IgniteProcess.SaveConfigurationBackup(); } /// <summary> /// Tear-down routine. /// </summary> [TearDown] public void TearDown() { IgniteProcess.RestoreConfigurationBackup(); } /// <summary> /// Test data pass through configuration file. /// </summary> [Test] public void TestConfig() { IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test"); GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath() ); Assert.IsTrue(_grid.WaitTopology(2)); var cfg = RemoteConfig(); Assert.AreEqual(SpringCfgPath, cfg.SpringConfigUrl); Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2")); Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll")); Assert.AreEqual(601, cfg.JvmInitialMemoryMb); Assert.AreEqual(702, cfg.JvmMaxMemoryMb); } /// <summary> /// Test assemblies passing through command-line. /// </summary> [Test] public void TestAssemblyCmd() { GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-assembly=test-1.dll", "-assembly=test-2.dll" ); Assert.IsTrue(_grid.WaitTopology(2)); var cfg = RemoteConfig(); Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll")); } /// <summary> /// Test JVM options passing through command-line. /// </summary> [Test] public void TestJvmOptsCmd() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-DOPT1", "-J-DOPT2" ); Assert.IsTrue(_grid.WaitTopology(2)); var cfg = RemoteConfig(); Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2")); } /// <summary> /// Test JVM memory options passing through command-line: raw java options. /// </summary> [Test] public void TestJvmMemoryOptsCmdRaw() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-Xms506m", "-J-Xmx607m" ); Assert.IsTrue(_grid.WaitTopology(2)); var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 506*1024*1024, minMem); var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 607*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing through command-line: custom options. /// </summary> [Test] public void TestJvmMemoryOptsCmdCustom() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-JvmInitialMemoryMB=615", "-JvmMaxMemoryMB=863" ); Assert.IsTrue(_grid.WaitTopology(2)); var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 615*1024*1024, minMem); var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 863*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing from application configuration. /// </summary> [Test] public void TestJvmMemoryOptsAppConfig( [Values("config\\Apache.Ignite.exe.config.test", "config\\Apache.Ignite.exe.config.test2")] string config) { IgniteProcess.ReplaceConfiguration(config); GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath()); Assert.IsTrue(_grid.WaitTopology(2)); var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 601*1024*1024, minMem); var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 702*1024*1024, maxMem); proc.Kill(); Assert.IsTrue(_grid.WaitTopology(1)); // Command line options overwrite config file options // ReSharper disable once RedundantAssignment proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-J-Xms605m", "-J-Xmx706m"); Assert.IsTrue(_grid.WaitTopology(2)); minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 605*1024*1024, minMem); maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 706*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing through command-line: custom options + raw options. /// </summary> [Test] public void TestJvmMemoryOptsCmdCombined() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-Xms555m", "-J-Xmx666m", "-JvmInitialMemoryMB=128", "-JvmMaxMemoryMB=256" ); Assert.IsTrue(_grid.WaitTopology(2)); // Raw JVM options (Xms/Xmx) should override custom options var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 555*1024*1024, minMem); var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 666*1024*1024, maxMem); } /// <summary> /// Tests the .NET XML configuration specified in app.config. /// </summary> [Test] public void TestXmlConfigurationAppConfig() { IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test3"); var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath()); Assert.IsTrue(_grid.WaitTopology(2)); var remoteCfg = RemoteConfig(); Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25")); proc.Kill(); Assert.IsTrue(_grid.WaitTopology(1)); } /// <summary> /// Tests the .NET XML configuration specified in command line. /// </summary> [Test] public void TestXmlConfigurationCmd() { var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-configFileName=config\\ignite-dotnet-cfg.xml"); Assert.IsTrue(_grid.WaitTopology(2)); var remoteCfg = RemoteConfig(); Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25")); proc.Kill(); Assert.IsTrue(_grid.WaitTopology(1)); } /// <summary> /// Get remote node configuration. /// </summary> /// <returns>Configuration.</returns> private RemoteConfiguration RemoteConfig() { return _grid.GetCluster().ForRemotes().GetCompute().Call(new RemoteConfigurationClosure()); } /// <summary> /// Configuration for node. /// </summary> /// <param name="path">Path to Java XML configuration.</param> /// <returns>Node configuration.</returns> private static IgniteConfiguration Configuration(string path) { var cfg = new IgniteConfiguration(); var portCfg = new BinaryConfiguration(); ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>(); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof (RemoteConfiguration))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof (RemoteConfigurationClosure))); portCfg.TypeConfigurations = portTypeCfgs; cfg.BinaryConfiguration = portCfg; cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = new List<string> { "-ea", "-Xcheck:jni", "-Xms4g", "-Xmx4g", "-DIGNITE_QUIET=false", "-Xnoagent", "-Djava.compiler=NONE", "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005", "-XX:+HeapDumpOnOutOfMemoryError" }; cfg.SpringConfigUrl = path; return cfg; } /// <summary> /// /// </summary> /// <param name="outputPath"></param> private static void GenerateDll(string outputPath) { var parameters = new CompilerParameters { GenerateExecutable = false, OutputAssembly = outputPath }; var src = "namespace Apache.Ignite.Client.Test { public class Foo {}}"; var results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, src); Assert.False(results.Errors.HasErrors); } /// <summary> /// Asserts that JVM maximum memory corresponds to Xmx parameter value. /// </summary> private static void AssertJvmMaxMemory(long expected, long actual) { // allow 20% tolerance because max memory in Java is not exactly equal to Xmx parameter value Assert.LessOrEqual(actual, expected); Assert.Greater(actual, expected/5*4); } /// <summary> /// Closure which extracts configuration and passes it back. /// </summary> private class RemoteConfigurationClosure : IComputeFunc<RemoteConfiguration> { #pragma warning disable 0649 /** Grid. */ [InstanceResource] private IIgnite _grid; #pragma warning restore 0649 /** <inheritDoc /> */ public RemoteConfiguration Invoke() { var grid0 = (Ignite) ((IgniteProxy) _grid).Target; var cfg = grid0.Configuration; var res = new RemoteConfiguration { IgniteHome = cfg.IgniteHome, SpringConfigUrl = cfg.SpringConfigUrl, JvmDll = cfg.JvmDllPath, JvmClasspath = cfg.JvmClasspath, JvmOptions = cfg.JvmOptions, Assemblies = cfg.Assemblies, JvmInitialMemoryMb = cfg.JvmInitialMemoryMb, JvmMaxMemoryMb = cfg.JvmMaxMemoryMb }; Console.WriteLine("RETURNING CFG: " + cfg); return res; } } /// <summary> /// Configuration. /// </summary> private class RemoteConfiguration { /// <summary> /// GG home. /// </summary> public string IgniteHome { get; set; } /// <summary> /// Spring config URL. /// </summary> public string SpringConfigUrl { get; set; } /// <summary> /// JVM DLL. /// </summary> public string JvmDll { get; set; } /// <summary> /// JVM classpath. /// </summary> public string JvmClasspath { get; set; } /// <summary> /// JVM options. /// </summary> public ICollection<string> JvmOptions { get; set; } /// <summary> /// Assemblies. /// </summary> public ICollection<string> Assemblies { get; set; } /// <summary> /// Minimum JVM memory (Xms). /// </summary> public int JvmInitialMemoryMb { get; set; } /// <summary> /// Maximum JVM memory (Xms). /// </summary> public int JvmMaxMemoryMb { get; set; } } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using MatterHackers.Agg.Image; namespace MatterHackers.Agg { public interface IImageBufferAccessor { byte[] span(int x, int y, int len, out int bufferIndex); byte[] next_x(out int bufferByteOffset); byte[] next_y(out int bufferByteOffset); IImageByte SourceImage { get; } }; public class ImageBufferAccessorCommon : IImageBufferAccessor { protected IImageByte m_SourceImage; protected int m_x, m_x0, m_y, m_DistanceBetweenPixelsInclusive; protected byte[] m_Buffer; protected int m_CurrentBufferOffset = -1; private int m_Width; public ImageBufferAccessorCommon(IImageByte pixf) { attach(pixf); } private void attach(IImageByte pixf) { m_SourceImage = pixf; m_Buffer = m_SourceImage.GetBuffer(); m_Width = m_SourceImage.Width; m_DistanceBetweenPixelsInclusive = m_SourceImage.GetBytesBetweenPixelsInclusive(); } public IImageByte SourceImage { get { return m_SourceImage; } } private byte[] pixel(out int bufferByteOffset) { int x = m_x; int y = m_y; unchecked { if ((uint)x >= (uint)m_SourceImage.Width) { if (x < 0) { x = 0; } else { x = (int)m_SourceImage.Width - 1; } } if ((uint)y >= (uint)m_SourceImage.Height) { if (y < 0) { y = 0; } else { y = (int)m_SourceImage.Height - 1; } } } bufferByteOffset = m_SourceImage.GetBufferOffsetXY(x, y); return m_SourceImage.GetBuffer(); } public byte[] span(int x, int y, int len, out int bufferOffset) { m_x = m_x0 = x; m_y = y; unchecked { if ((uint)y < (uint)m_SourceImage.Height && x >= 0 && x + len <= (int)m_SourceImage.Width) { bufferOffset = m_SourceImage.GetBufferOffsetXY(x, y); m_Buffer = m_SourceImage.GetBuffer(); m_CurrentBufferOffset = bufferOffset; return m_Buffer; } } m_CurrentBufferOffset = -1; return pixel(out bufferOffset); } public byte[] next_x(out int bufferOffset) { // this is the code (managed) that the original agg used. // It looks like it doesn't check x but, It should be a bit faster and is valid // because "span" checked the whole length for good x. if (m_CurrentBufferOffset != -1) { m_CurrentBufferOffset += m_DistanceBetweenPixelsInclusive; bufferOffset = m_CurrentBufferOffset; return m_Buffer; } ++m_x; return pixel(out bufferOffset); } public byte[] next_y(out int bufferOffset) { ++m_y; m_x = m_x0; if (m_CurrentBufferOffset != -1 && (uint)m_y < (uint)m_SourceImage.Height) { m_CurrentBufferOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y); m_SourceImage.GetBuffer(); bufferOffset = m_CurrentBufferOffset; ; return m_Buffer; } m_CurrentBufferOffset = -1; return pixel(out bufferOffset); } }; public sealed class ImageBufferAccessorClip : ImageBufferAccessorCommon { private byte[] m_OutsideBufferColor; public ImageBufferAccessorClip(IImageByte sourceImage, RGBA_Bytes bk) : base(sourceImage) { m_OutsideBufferColor = new byte[4]; m_OutsideBufferColor[0] = bk.red; m_OutsideBufferColor[1] = bk.green; m_OutsideBufferColor[2] = bk.blue; m_OutsideBufferColor[3] = bk.alpha; } private byte[] pixel(out int bufferByteOffset) { unchecked { if (((uint)m_x < (uint)m_SourceImage.Width) && ((uint)m_y < (uint)m_SourceImage.Height)) { bufferByteOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y); return m_SourceImage.GetBuffer(); } } bufferByteOffset = 0; return m_OutsideBufferColor; } }; /* //--------------------------------------------------image_accessor_no_clip template<class PixFmt> class image_accessor_no_clip { public: typedef PixFmt pixfmt_type; typedef typename pixfmt_type::color_type color_type; typedef typename pixfmt_type::order_type order_type; typedef typename pixfmt_type::value_type value_type; enum pix_width_e { pix_width = pixfmt_type::pix_width }; image_accessor_no_clip() {} explicit image_accessor_no_clip(pixfmt_type& pixf) : m_pixf(&pixf) {} void attach(pixfmt_type& pixf) { m_pixf = &pixf; } byte* span(int x, int y, int) { m_x = x; m_y = y; return m_pix_ptr = m_pixf->pix_ptr(x, y); } byte* next_x() { return m_pix_ptr += pix_width; } byte* next_y() { ++m_y; return m_pix_ptr = m_pixf->pix_ptr(m_x, m_y); } private: pixfmt_type* m_pixf; int m_x, m_y; byte* m_pix_ptr; }; */ public sealed class ImageBufferAccessorClamp : ImageBufferAccessorCommon { public ImageBufferAccessorClamp(IImageByte pixf) : base(pixf) { } private byte[] pixel(out int bufferByteOffset) { int x = m_x; int y = m_y; unchecked { if ((uint)x >= (uint)m_SourceImage.Width) { if (x < 0) { x = 0; } else { x = (int)m_SourceImage.Width - 1; } } if ((uint)y >= (uint)m_SourceImage.Height) { if (y < 0) { y = 0; } else { y = (int)m_SourceImage.Height - 1; } } } bufferByteOffset = m_SourceImage.GetBufferOffsetXY(x, y); return m_SourceImage.GetBuffer(); } }; /* //-----------------------------------------------------image_accessor_wrap template<class PixFmt, class WrapX, class WrapY> class image_accessor_wrap { public: typedef PixFmt pixfmt_type; typedef typename pixfmt_type::color_type color_type; typedef typename pixfmt_type::order_type order_type; typedef typename pixfmt_type::value_type value_type; enum pix_width_e { pix_width = pixfmt_type::pix_width }; image_accessor_wrap() {} explicit image_accessor_wrap(pixfmt_type& pixf) : m_pixf(&pixf), m_wrap_x(pixf.Width), m_wrap_y(pixf.Height) {} void attach(pixfmt_type& pixf) { m_pixf = &pixf; } byte* span(int x, int y, int) { m_x = x; m_row_ptr = m_pixf->row_ptr(m_wrap_y(y)); return m_row_ptr + m_wrap_x(x) * pix_width; } byte* next_x() { int x = ++m_wrap_x; return m_row_ptr + x * pix_width; } byte* next_y() { m_row_ptr = m_pixf->row_ptr(++m_wrap_y); return m_row_ptr + m_wrap_x(m_x) * pix_width; } private: pixfmt_type* m_pixf; byte* m_row_ptr; int m_x; WrapX m_wrap_x; WrapY m_wrap_y; }; //--------------------------------------------------------wrap_mode_repeat class wrap_mode_repeat { public: wrap_mode_repeat() {} wrap_mode_repeat(int size) : m_size(size), m_add(size * (0x3FFFFFFF / size)), m_value(0) {} int operator() (int v) { return m_value = (int(v) + m_add) % m_size; } int operator++ () { ++m_value; if(m_value >= m_size) m_value = 0; return m_value; } private: int m_size; int m_add; int m_value; }; //---------------------------------------------------wrap_mode_repeat_pow2 class wrap_mode_repeat_pow2 { public: wrap_mode_repeat_pow2() {} wrap_mode_repeat_pow2(int size) : m_value(0) { m_mask = 1; while(m_mask < size) m_mask = (m_mask << 1) | 1; m_mask >>= 1; } int operator() (int v) { return m_value = int(v) & m_mask; } int operator++ () { ++m_value; if(m_value > m_mask) m_value = 0; return m_value; } private: int m_mask; int m_value; }; //----------------------------------------------wrap_mode_repeat_auto_pow2 class wrap_mode_repeat_auto_pow2 { public: wrap_mode_repeat_auto_pow2() {} wrap_mode_repeat_auto_pow2(int size) : m_size(size), m_add(size * (0x3FFFFFFF / size)), m_mask((m_size & (m_size-1)) ? 0 : m_size-1), m_value(0) {} int operator() (int v) { if(m_mask) return m_value = int(v) & m_mask; return m_value = (int(v) + m_add) % m_size; } int operator++ () { ++m_value; if(m_value >= m_size) m_value = 0; return m_value; } private: int m_size; int m_add; int m_mask; int m_value; }; //-------------------------------------------------------wrap_mode_reflect class wrap_mode_reflect { public: wrap_mode_reflect() {} wrap_mode_reflect(int size) : m_size(size), m_size2(size * 2), m_add(m_size2 * (0x3FFFFFFF / m_size2)), m_value(0) {} int operator() (int v) { m_value = (int(v) + m_add) % m_size2; if(m_value >= m_size) return m_size2 - m_value - 1; return m_value; } int operator++ () { ++m_value; if(m_value >= m_size2) m_value = 0; if(m_value >= m_size) return m_size2 - m_value - 1; return m_value; } private: int m_size; int m_size2; int m_add; int m_value; }; //--------------------------------------------------wrap_mode_reflect_pow2 class wrap_mode_reflect_pow2 { public: wrap_mode_reflect_pow2() {} wrap_mode_reflect_pow2(int size) : m_value(0) { m_mask = 1; m_size = 1; while(m_mask < size) { m_mask = (m_mask << 1) | 1; m_size <<= 1; } } int operator() (int v) { m_value = int(v) & m_mask; if(m_value >= m_size) return m_mask - m_value; return m_value; } int operator++ () { ++m_value; m_value &= m_mask; if(m_value >= m_size) return m_mask - m_value; return m_value; } private: int m_size; int m_mask; int m_value; }; //---------------------------------------------wrap_mode_reflect_auto_pow2 class wrap_mode_reflect_auto_pow2 { public: wrap_mode_reflect_auto_pow2() {} wrap_mode_reflect_auto_pow2(int size) : m_size(size), m_size2(size * 2), m_add(m_size2 * (0x3FFFFFFF / m_size2)), m_mask((m_size2 & (m_size2-1)) ? 0 : m_size2-1), m_value(0) {} int operator() (int v) { m_value = m_mask ? int(v) & m_mask : (int(v) + m_add) % m_size2; if(m_value >= m_size) return m_size2 - m_value - 1; return m_value; } int operator++ () { ++m_value; if(m_value >= m_size2) m_value = 0; if(m_value >= m_size) return m_size2 - m_value - 1; return m_value; } private: int m_size; int m_size2; int m_add; int m_mask; int m_value; }; */ public interface IImageBufferAccessorFloat { float[] span(int x, int y, int len, out int bufferIndex); float[] next_x(out int bufferFloatOffset); float[] next_y(out int bufferFloatOffset); IImageFloat SourceImage { get; } }; public class ImageBufferAccessorCommonFloat : IImageBufferAccessorFloat { protected IImageFloat m_SourceImage; protected int m_x, m_x0, m_y, m_DistanceBetweenPixelsInclusive; protected float[] m_Buffer; protected int m_CurrentBufferOffset = -1; private int m_Width; public ImageBufferAccessorCommonFloat(IImageFloat pixf) { attach(pixf); } private void attach(IImageFloat pixf) { m_SourceImage = pixf; m_Buffer = m_SourceImage.GetBuffer(); m_Width = m_SourceImage.Width; m_DistanceBetweenPixelsInclusive = m_SourceImage.GetFloatsBetweenPixelsInclusive(); } public IImageFloat SourceImage { get { return m_SourceImage; } } private float[] pixel(out int bufferFloatOffset) { int x = m_x; int y = m_y; unchecked { if ((uint)x >= (uint)m_SourceImage.Width) { if (x < 0) { x = 0; } else { x = (int)m_SourceImage.Width - 1; } } if ((uint)y >= (uint)m_SourceImage.Height) { if (y < 0) { y = 0; } else { y = (int)m_SourceImage.Height - 1; } } } bufferFloatOffset = m_SourceImage.GetBufferOffsetXY(x, y); return m_SourceImage.GetBuffer(); } public float[] span(int x, int y, int len, out int bufferOffset) { m_x = m_x0 = x; m_y = y; unchecked { if ((uint)y < (uint)m_SourceImage.Height && x >= 0 && x + len <= (int)m_SourceImage.Width) { bufferOffset = m_SourceImage.GetBufferOffsetXY(x, y); m_Buffer = m_SourceImage.GetBuffer(); m_CurrentBufferOffset = bufferOffset; return m_Buffer; } } m_CurrentBufferOffset = -1; return pixel(out bufferOffset); } public float[] next_x(out int bufferOffset) { // this is the code (managed) that the original agg used. // It looks like it doesn't check x but, It should be a bit faster and is valid // because "span" checked the whole length for good x. if (m_CurrentBufferOffset != -1) { m_CurrentBufferOffset += m_DistanceBetweenPixelsInclusive; bufferOffset = m_CurrentBufferOffset; return m_Buffer; } ++m_x; return pixel(out bufferOffset); } public float[] next_y(out int bufferOffset) { ++m_y; m_x = m_x0; if (m_CurrentBufferOffset != -1 && (uint)m_y < (uint)m_SourceImage.Height) { m_CurrentBufferOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y); bufferOffset = m_CurrentBufferOffset; return m_Buffer; } m_CurrentBufferOffset = -1; return pixel(out bufferOffset); } }; public sealed class ImageBufferAccessorClipFloat : ImageBufferAccessorCommonFloat { private float[] m_OutsideBufferColor; public ImageBufferAccessorClipFloat(IImageFloat sourceImage, RGBA_Floats bk) : base(sourceImage) { m_OutsideBufferColor = new float[4]; m_OutsideBufferColor[0] = bk.red; m_OutsideBufferColor[1] = bk.green; m_OutsideBufferColor[2] = bk.blue; m_OutsideBufferColor[3] = bk.alpha; } private float[] pixel(out int bufferFloatOffset) { unchecked { if (((uint)m_x < (uint)m_SourceImage.Width) && ((uint)m_y < (uint)m_SourceImage.Height)) { bufferFloatOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y); return m_SourceImage.GetBuffer(); } } bufferFloatOffset = 0; return m_OutsideBufferColor; } //public void background_color(IColorType bk) //{ // m_pixf.make_pix(m_pBackBufferColor, bk); //} }; }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.Localization; using OpenLiveWriter.CoreServices.Layout; namespace OpenLiveWriter.PostEditor.ContentSources.Common { public class LoginStatusControl : UserControl { private Label labelStatus; private LinkLabel linkLabelAction; private IAuth _auth; public LoginStatusControl() { InitializeComponent(); linkLabelAction.LinkColor = SystemInformation.HighContrast ? SystemColors.HotTrack : Color.FromArgb(0, 102, 204); linkLabelAction.FlatStyle = FlatStyle.System; } public IAuth Auth { set { DisposeOldAuth(); _auth = value; // If the hosting control doesnt have an IAuth, we should hide ourselves // because there is no way to manage authenication. This will happen when // we Mail is using the photo album feature and authenication is controlled by Mail if(_auth == null) { this.Visible = false; return; } else { Visible = true; } _auth.LoginStatusChanged += _videoAuth_LoginStatusChanged; UpdateStatus(); if (!_auth.IsLoggedIn) TimerHelper.CallbackOnDelay(AutoLogin, 200); } } /// <summary> /// True to show the login hyperlink when the user is no logged in, false to hide it, most commonly because there is /// an external panel login on the tab /// </summary> private bool _showLoginButton = true; public bool ShowLoginButton { get { return _showLoginButton; } set { _showLoginButton = value; } } void AutoLogin() { if (_auth == null) return; _auth.Login(false, FindForm()); UpdateStatus(); } private void DisposeOldAuth() { if (_auth != null) { _auth.LoginStatusChanged -= _videoAuth_LoginStatusChanged; _auth = null; } } public event EventHandler LoginStatusChanged; public event EventHandler LoginClicked; public event EventHandler SwitchUserClicked; protected virtual void OnLoginStatusChanged() { if (LoginStatusChanged != null) LoginStatusChanged(this, EventArgs.Empty); } protected virtual void OnLoginClicked() { if (LoginClicked != null) LoginClicked(this, EventArgs.Empty); } protected virtual void OnSwitchUserClicked() { if (SwitchUserClicked != null) SwitchUserClicked(this, EventArgs.Empty); } void _videoAuth_LoginStatusChanged(object sender, EventArgs e) { UpdateStatus(); OnLoginStatusChanged(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); DisposeOldAuth(); } public void UpdateStatus() { if (_auth == null) { labelStatus.Text = ""; return; } if (_auth.IsLoggedIn) { labelStatus.Text = _auth.Username; linkLabelAction.Text = Res.Get(StringId.Plugin_Video_Soapbox_Switch_User); linkLabelAction.Visible = true; } else { labelStatus.Text = Res.Get(StringId.Plugin_Video_Soapbox_Not_Logged_In); linkLabelAction.Text = Res.Get(StringId.Plugin_Video_Soapbox_Publish_Login); linkLabelAction.Visible = ShowLoginButton; } // Changing the width of the label in RTL mode after its already been // laid out causes UI issues, so we'll only do this in automation mode. if (ApplicationDiagnostics.AutomationMode) { linkLabelAction.Width = this.Width - 7; LayoutHelper.NaturalizeHeight(linkLabelAction); } } private void InitializeComponent() { this.labelStatus = new System.Windows.Forms.Label(); this.linkLabelAction = new System.Windows.Forms.LinkLabel(); this.SuspendLayout(); // // labelStatus // this.labelStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelStatus.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelStatus.Location = new System.Drawing.Point(2, 0); this.labelStatus.Name = "labelStatus"; this.labelStatus.Size = new System.Drawing.Size(154, 16); this.labelStatus.TabIndex = 0; this.labelStatus.Text = "Not Logged In"; // // linkLabelAction // this.linkLabelAction.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.linkLabelAction.Location = new System.Drawing.Point(0, 16); this.linkLabelAction.Name = "linkLabelAction"; this.linkLabelAction.Size = new System.Drawing.Size(154, 16); this.linkLabelAction.TabIndex = 1; this.linkLabelAction.TextAlign = System.Drawing.ContentAlignment.BottomLeft; this.linkLabelAction.LinkColor = SystemColors.HotTrack; this.linkLabelAction.LinkBehavior = LinkBehavior.HoverUnderline; this.linkLabelAction.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelAction_LinkClicked); this.linkLabelAction.UseCompatibleTextRendering = false; // // LoginStatusControl // this.Controls.Add(this.linkLabelAction); this.Controls.Add(this.labelStatus); this.Name = "LoginStatusControl"; this.Size = new System.Drawing.Size(161, 32); this.ResumeLayout(false); } private void linkLabelAction_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { _auth.Logout(); if (_auth.IsLoggedIn) { OnSwitchUserClicked(); } else { OnLoginClicked(); } } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetTapeDensityDirectivesSpectraS3Request : Ds3Request { private TapeDriveType? _density; public TapeDriveType? Density { get { return _density; } set { WithDensity(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private string _partitionId; public string PartitionId { get { return _partitionId; } set { WithPartitionId(value); } } private string _tapeType; public string TapeType { get { return _tapeType; } set { WithTapeType(value); } } public GetTapeDensityDirectivesSpectraS3Request WithDensity(TapeDriveType? density) { this._density = density; if (density != null) { this.QueryParams.Add("density", density.ToString()); } else { this.QueryParams.Remove("density"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPartitionId(Guid? partitionId) { this._partitionId = partitionId.ToString(); if (partitionId != null) { this.QueryParams.Add("partition_id", partitionId.ToString()); } else { this.QueryParams.Remove("partition_id"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithPartitionId(string partitionId) { this._partitionId = partitionId; if (partitionId != null) { this.QueryParams.Add("partition_id", partitionId); } else { this.QueryParams.Remove("partition_id"); } return this; } public GetTapeDensityDirectivesSpectraS3Request WithTapeType(string tapeType) { this._tapeType = tapeType; if (tapeType != null) { this.QueryParams.Add("tape_type", tapeType); } else { this.QueryParams.Remove("tape_type"); } return this; } public GetTapeDensityDirectivesSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/tape_density_directive"; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if !(PORTABLE || PORTABLE40 || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT) using System.Numerics; #endif using System.Reflection; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; #if NET20 using uWebshop.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using uWebshop.Newtonsoft.Json.Serialization; namespace uWebshop.Newtonsoft.Json.Utilities { #if (NETFX_CORE || PORTABLE || PORTABLE40) internal enum MemberTypes { Property, Field, Event, Method, Other } #endif #if NETFX_CORE || PORTABLE [Flags] internal enum BindingFlags { Default = 0, IgnoreCase = 1, DeclaredOnly = 2, Instance = 4, Static = 8, Public = 16, NonPublic = 32, FlattenHierarchy = 64, InvokeMethod = 256, CreateInstance = 512, GetField = 1024, SetField = 2048, GetProperty = 4096, SetProperty = 8192, PutDispProperty = 16384, ExactBinding = 65536, PutRefDispProperty = 32768, SuppressChangeType = 131072, OptionalParamBinding = 262144, IgnoreReturn = 16777216 } #endif internal static class ReflectionUtils { public static readonly Type[] EmptyTypes; static ReflectionUtils() { #if !(NETFX_CORE || PORTABLE40 || PORTABLE) EmptyTypes = Type.EmptyTypes; #else EmptyTypes = new Type[0]; #endif } public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) return true; m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) return true; return false; } public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null) return m.GetBaseDefinition(); m = propertyInfo.GetSetMethod(); if (m != null) return m.GetBaseDefinition(); return null; } public static bool IsPublic(PropertyInfo property) { if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) return true; if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) return true; return false; } public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) { string fullyQualifiedTypeName; #if !(NET20 || NET35) if (binder != null) { string assemblyName, typeName; binder.BindToName(t, out assemblyName, out typeName); fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName); } else { fullyQualifiedTypeName = t.AssemblyQualifiedName; } #else fullyQualifiedTypeName = t.AssemblyQualifiedName; #endif switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return RemoveAssemblyDetails(fullyQualifiedTypeName); case FormatterAssemblyStyle.Full: return fullyQualifiedTypeName; default: throw new ArgumentOutOfRangeException(); } } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) { var builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) bindingFlags = bindingFlags | BindingFlags.NonPublic; return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof (Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition) { if (!type.IsGenericType()) return false; Type t = type.GetGenericTypeDefinition(); return (t == genericInterfaceDefinition); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface()) { if (type.IsGenericType()) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (var i in type.GetInterfaces()) { if (i.IsGenericType()) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType()) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType() == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof (IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof (IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof (IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof (IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo) member).FieldType; case MemberTypes.Property: return ((PropertyInfo) member).PropertyType; case MemberTypes.Event: return ((EventInfo) member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); var propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo) member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo) member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: ((FieldInfo) member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo) member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType()) { case MemberTypes.Field: var fieldInfo = (FieldInfo) member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: var propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { switch (member.MemberType()) { case MemberTypes.Field: var fieldInfo = (FieldInfo) member; if (fieldInfo.IsInitOnly && !canSetReadOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: var propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { var targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/ // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... var distinctMembers = new List<MemberInfo>(targetMembers.Count); foreach (var groupedMember in targetMembers.GroupBy(m => m.Name)) { int count = groupedMember.Count(); IList<MemberInfo> members = groupedMember.ToList(); if (count == 1) { distinctMembers.Add(members.First()); } else { var resolvedMembers = members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item"); distinctMembers.AddRange(resolvedMembers); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { MemberTypes memberType = memberInfo.MemberType(); if (memberType != MemberTypes.Field && memberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; if (!declaringType.IsGenericType()) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(object attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return (attributes != null) ? attributes.SingleOrDefault() : null; } #if !(NETFX_CORE || PORTABLE) public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); object provider = attributeProvider; // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (provider is Type) return (T[]) ((Type) provider).GetCustomAttributes(typeof (T), inherit); if (provider is Assembly) return (T[]) Attribute.GetCustomAttributes((Assembly) provider, typeof (T)); if (provider is MemberInfo) return (T[]) Attribute.GetCustomAttributes((MemberInfo) provider, typeof (T), inherit); #if !PORTABLE40 if (provider is Module) return (T[]) Attribute.GetCustomAttributes((Module) provider, typeof (T), inherit); #endif if (provider is ParameterInfo) return (T[]) Attribute.GetCustomAttributes((ParameterInfo) provider, typeof (T), inherit); #if !PORTABLE40 return (T[]) ((ICustomAttributeProvider) attributeProvider).GetCustomAttributes(typeof (T), inherit); #endif throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #else public static T[] GetAttributes<T>(object provider, bool inherit) where T : Attribute { if (provider is Type) return ((Type)provider).GetTypeInfo().GetCustomAttributes<T>(inherit).ToArray(); if (provider is Assembly) return ((Assembly)provider).GetCustomAttributes<T>().ToArray(); if (provider is MemberInfo) return ((MemberInfo)provider).GetCustomAttributes<T>(inherit).ToArray(); if (provider is Module) return ((Module)provider).GetCustomAttributes<T>().ToArray(); if (provider is ParameterInfo) return ((ParameterInfo)provider).GetCustomAttributes<T>(inherit).ToArray(); throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #endif public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType()) { case MemberTypes.Property: var propertyInfo = (PropertyInfo) memberInfo; Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); } } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); var fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); #if !(NETFX_CORE || PORTABLE) // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); #endif return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); var propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { var declaredMember = (PropertyInfo) GetMemberInfoFromType(member.DeclaringType, member); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result // also find base properties that have been hidden by subtype properties with the same name while ((targetType = targetType.BaseType()) != null) { foreach (var propertyInfo in targetType.GetProperties(bindingAttr)) { PropertyInfo subTypeProperty = propertyInfo; if (!IsPublic(subTypeProperty)) { // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name); if (index == -1) { initialProperties.Add(subTypeProperty); } else { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = subTypeProperty; } } else { if (!subTypeProperty.IsVirtual()) { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.DeclaringType == subTypeProperty.DeclaringType); if (index == -1) initialProperties.Add(subTypeProperty); } else { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.IsVirtual() && p.GetBaseDefinition() != null && p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.DeclaringType)); if (index == -1) initialProperties.Add(subTypeProperty); } } } } } public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) { bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Any(info => info.Name == method &&// check that the method overrides the original on DynamicObjectProxy info.DeclaringType != methodDeclaringType && info.GetBaseDefinition().DeclaringType == methodDeclaringType); return isMethodOverriden; } public static object GetDefaultValue(Type type) { if (!type.IsValueType()) return null; switch (ConvertUtils.GetTypeCode(type)) { case PrimitiveTypeCode.Boolean: return false; case PrimitiveTypeCode.Char: case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: return 0; case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return 0L; case PrimitiveTypeCode.Single: return 0f; case PrimitiveTypeCode.Double: return 0.0; case PrimitiveTypeCode.Decimal: return 0m; case PrimitiveTypeCode.DateTime: return new DateTime(); #if !(PORTABLE || PORTABLE40 || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT) case PrimitiveTypeCode.BigInteger: return new BigInteger(); #endif case PrimitiveTypeCode.Guid: return new Guid(); #if !NET20 case PrimitiveTypeCode.DateTimeOffset: return new DateTimeOffset(); #endif } if (IsNullable(type)) return null; // possibly use IL initobj for perf here? return Activator.CreateInstance(type); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FarseerPhysics; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using FarseerPhysics.Controllers; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Contacts; using FarseerPhysics.Dynamics.Joints; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Nez.Farseer { /// <summary> /// A debug view shows you what happens inside the physics engine. You can view /// bodies, joints, fixtures and more. /// </summary> public class FSDebugView : RenderableComponent, IDisposable { public override RectangleF Bounds => _bounds; /// <summary> /// Gets or sets the debug view flags /// </summary> public DebugViewFlags Flags; /// <summary> /// the World we are drawing /// </summary> protected World world; //Shapes public Color DefaultShapeColor = new Color(0.9f, 0.7f, 0.7f); public Color InactiveShapeColor = new Color(0.5f, 0.5f, 0.3f); public Color KinematicShapeColor = new Color(0.5f, 0.5f, 0.9f); public Color SleepingShapeColor = new Color(0.6f, 0.6f, 0.6f); public Color StaticShapeColor = new Color(0.5f, 0.9f, 0.5f); public Color TextColor = Color.White; //Drawing PrimitiveBatch _primitiveBatch; Vector2[] _tempVertices = new Vector2[Settings.MaxPolygonVertices]; List<StringData> _stringData = new List<StringData>(); Matrix _localProjection; Matrix _localView; //Contacts int _pointCount; const int maxContactPoints = 2048; ContactPoint[] _points = new ContactPoint[maxContactPoints]; //Debug panel public Vector2 DebugPanelPosition = new Vector2(5, 5); float _max; float _avg; float _min; StringBuilder _debugPanelSb = new StringBuilder(); //Performance graph public bool AdaptiveLimits = true; public int ValuesToGraph = 500; public float MinimumValue; public float MaximumValue = 10; public Rectangle PerformancePanelBounds = new Rectangle(Screen.Width - 300, 5, 200, 100); List<float> _graphValues = new List<float>(500); Vector2[] _background = new Vector2[4]; public const int CircleSegments = 24; public FSDebugView() { _bounds = RectangleF.MaxRect; //Default flags AppendFlags(DebugViewFlags.Shape); AppendFlags(DebugViewFlags.Controllers); AppendFlags(DebugViewFlags.Joint); } public FSDebugView(World world) : this() { this.world = world; } /// <summary> /// Append flags to the current flags /// </summary> /// <param name="flags">Flags.</param> public void AppendFlags(DebugViewFlags flags) { this.Flags |= flags; } /// <summary> /// Remove flags from the current flags /// </summary> /// <param name="flags">Flags.</param> public void RemoveFlags(DebugViewFlags flags) { this.Flags &= ~flags; } #region IDisposable Members public void Dispose() { world.ContactManager.OnPreSolve -= PreSolve; } #endregion public override void OnAddedToEntity() { if (world == null) world = Entity.Scene.GetOrCreateSceneComponent<FSWorld>(); world.ContactManager.OnPreSolve += PreSolve; Transform.SetPosition(new Vector2(-float.MaxValue, -float.MaxValue) * 0.5f); _primitiveBatch = new PrimitiveBatch(1000); _localProjection = Matrix.CreateOrthographicOffCenter(0f, Core.GraphicsDevice.Viewport.Width, Core.GraphicsDevice.Viewport.Height, 0f, 0f, 1f); _localView = Matrix.Identity; } void PreSolve(Contact contact, ref Manifold oldManifold) { if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { Manifold manifold = contact.Manifold; if (manifold.PointCount == 0) return; Fixture fixtureA = contact.FixtureA; FixedArray2<PointState> state1, state2; FarseerPhysics.Collision.Collision.GetPointStates(out state1, out state2, ref oldManifold, ref manifold); FixedArray2<Vector2> points; Vector2 normal; contact.GetWorldManifold(out normal, out points); for (int i = 0; i < manifold.PointCount && _pointCount < maxContactPoints; ++i) { if (fixtureA == null) _points[i] = new ContactPoint(); ContactPoint cp = _points[_pointCount]; cp.Position = points[i]; cp.Normal = normal; cp.State = state2[i]; _points[_pointCount] = cp; ++_pointCount; } } } /// <summary> /// Call this to draw shapes and other debug draw data. /// </summary> void DrawDebugData() { if ((Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape) { foreach (Body b in world.BodyList) { FarseerPhysics.Common.Transform xf; b.GetTransform(out xf); foreach (Fixture f in b.FixtureList) { if (b.Enabled == false) DrawShape(f, xf, InactiveShapeColor); else if (b.BodyType == BodyType.Static) DrawShape(f, xf, StaticShapeColor); else if (b.BodyType == BodyType.Kinematic) DrawShape(f, xf, KinematicShapeColor); else if (b.IsAwake == false) DrawShape(f, xf, SleepingShapeColor); else DrawShape(f, xf, DefaultShapeColor); } } } if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { const float axisScale = 0.3f; for (int i = 0; i < _pointCount; ++i) { ContactPoint point = _points[i]; if (point.State == PointState.Add) DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.95f, 0.3f)); else if (point.State == PointState.Persist) DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.3f, 0.95f)); if ((Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals) { Vector2 p1 = point.Position; Vector2 p2 = p1 + axisScale * point.Normal; DrawSegment(p1, p2, new Color(0.4f, 0.9f, 0.4f)); } } _pointCount = 0; } if ((Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints) { foreach (Body body in world.BodyList) { foreach (Fixture f in body.FixtureList) { var polygon = f.Shape as PolygonShape; if (polygon != null) { FarseerPhysics.Common.Transform xf; body.GetTransform(out xf); for (int i = 0; i < polygon.Vertices.Count; i++) { Vector2 tmp = MathUtils.Mul(ref xf, polygon.Vertices[i]); DrawPoint(tmp, 0.1f, Color.Red); } } } } } if ((Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint) { foreach (var j in world.JointList) FSDebugView.DrawJoint(this, j); } if ((Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB) { var color = new Color(0.9f, 0.3f, 0.9f); var bp = world.ContactManager.BroadPhase; foreach (var body in world.BodyList) { if (body.Enabled == false) continue; foreach (var f in body.FixtureList) { for (var t = 0; t < f.ProxyCount; ++t) { var proxy = f.Proxies[t]; AABB aabb; bp.GetFatAABB(proxy.ProxyId, out aabb); DrawAABB(ref aabb, color); } } } } if ((Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass) { foreach (Body b in world.BodyList) { FarseerPhysics.Common.Transform xf; b.GetTransform(out xf); xf.P = b.WorldCenter; DrawTransform(ref xf); } } if ((Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers) { for (int i = 0; i < world.ControllerList.Count; i++) { Controller controller = world.ControllerList[i]; var buoyancy = controller as BuoyancyController; if (buoyancy != null) { AABB container = buoyancy.Container; DrawAABB(ref container, Color.LightBlue); } } } if ((Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel) DrawDebugPanel(); } void DrawPerformanceGraph() { _graphValues.Add(world.UpdateTime / TimeSpan.TicksPerMillisecond); if (_graphValues.Count > ValuesToGraph + 1) _graphValues.RemoveAt(0); float x = PerformancePanelBounds.X; float deltaX = PerformancePanelBounds.Width / (float) ValuesToGraph; float yScale = PerformancePanelBounds.Bottom - (float) PerformancePanelBounds.Top; // we must have at least 2 values to start rendering if (_graphValues.Count > 2) { _max = _graphValues.Max(); _avg = _graphValues.Average(); _min = _graphValues.Min(); if (AdaptiveLimits) { MaximumValue = _max; MinimumValue = 0; } // start at last value (newest value added) // continue until no values are left for (int i = _graphValues.Count - 1; i > 0; i--) { float y1 = PerformancePanelBounds.Bottom - ((_graphValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = PerformancePanelBounds.Bottom - ((_graphValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); var x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); var x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(FSConvert.ToSimUnits(x1), FSConvert.ToSimUnits(x2), Color.LightGreen); x += deltaX; } } DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, string.Format("Max: {0} ms", _max)); DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Center.Y - 7, string.Format("Avg: {0} ms", _avg)); DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, string.Format("Min: {0} ms", _min)); //Draw background. _background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y); _background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y); _background[0] = FSConvert.ToSimUnits(_background[0]); _background[1] = FSConvert.ToSimUnits(_background[1]); _background[2] = FSConvert.ToSimUnits(_background[2]); _background[3] = FSConvert.ToSimUnits(_background[3]); DrawSolidPolygon(_background, 4, Color.DarkGray, true); } void DrawDebugPanel() { int fixtureCount = 0; for (int i = 0; i < world.BodyList.Count; i++) fixtureCount += world.BodyList[i].FixtureList.Count; var x = (int) DebugPanelPosition.X; var y = (int) DebugPanelPosition.Y; _debugPanelSb.Clear(); _debugPanelSb.AppendLine("Objects:"); _debugPanelSb.Append("- Bodies: ").AppendLine(world.BodyList.Count.ToString()); _debugPanelSb.Append("- Fixtures: ").AppendLine(fixtureCount.ToString()); _debugPanelSb.Append("- Contacts: ").AppendLine(world.ContactList.Count.ToString()); _debugPanelSb.Append("- Joints: ").AppendLine(world.JointList.Count.ToString()); _debugPanelSb.Append("- Controllers: ").AppendLine(world.ControllerList.Count.ToString()); _debugPanelSb.Append("- Proxies: ").AppendLine(world.ProxyCount.ToString()); DrawString(x, y, _debugPanelSb.ToString()); _debugPanelSb.Clear(); _debugPanelSb.AppendLine("Update time:"); _debugPanelSb.Append("- Body: ") .AppendLine(string.Format("{0} ms", world.SolveUpdateTime / TimeSpan.TicksPerMillisecond)); _debugPanelSb.Append("- Contact: ") .AppendLine(string.Format("{0} ms", world.ContactsUpdateTime / TimeSpan.TicksPerMillisecond)); _debugPanelSb.Append("- CCD: ") .AppendLine(string.Format("{0} ms", world.ContinuousPhysicsTime / TimeSpan.TicksPerMillisecond)); _debugPanelSb.Append("- Joint: ") .AppendLine(string.Format("{0} ms", world.Island.JointUpdateTime / TimeSpan.TicksPerMillisecond)); _debugPanelSb.Append("- Controller: ") .AppendLine(string.Format("{0} ms", world.ControllersUpdateTime / TimeSpan.TicksPerMillisecond)); _debugPanelSb.Append("- Total: ") .AppendLine(string.Format("{0} ms", world.UpdateTime / TimeSpan.TicksPerMillisecond)); DrawString(x + 110, y, _debugPanelSb.ToString()); } #region Drawing methods public void DrawAABB(ref AABB aabb, Color color) { Vector2[] verts = new Vector2[4]; verts[0] = new Vector2(aabb.LowerBound.X, aabb.LowerBound.Y); verts[1] = new Vector2(aabb.UpperBound.X, aabb.LowerBound.Y); verts[2] = new Vector2(aabb.UpperBound.X, aabb.UpperBound.Y); verts[3] = new Vector2(aabb.LowerBound.X, aabb.UpperBound.Y); DrawPolygon(verts, 4, color); } static void DrawJoint(FSDebugView instance, Joint joint) { if (!joint.Enabled) return; var b1 = joint.BodyA; var b2 = joint.BodyB; FarseerPhysics.Common.Transform xf1; b1.GetTransform(out xf1); var x2 = Vector2.Zero; if (b2 != null || !joint.IsFixedType()) { FarseerPhysics.Common.Transform xf2; b2.GetTransform(out xf2); x2 = xf2.P; } var p1 = joint.WorldAnchorA; var p2 = joint.WorldAnchorB; var x1 = xf1.P; var color = new Color(0.5f, 0.8f, 0.8f); switch (joint.JointType) { case JointType.Distance: { instance.DrawSegment(p1, p2, color); break; } case JointType.Pulley: { var pulley = (PulleyJoint) joint; var s1 = b1.GetWorldPoint(pulley.LocalAnchorA); var s2 = b2.GetWorldPoint(pulley.LocalAnchorB); instance.DrawSegment(p1, p2, color); instance.DrawSegment(p1, s1, color); instance.DrawSegment(p2, s2, color); break; } case JointType.FixedMouse: { instance.DrawPoint(p1, 0.2f, new Color(0.0f, 1.0f, 0.0f)); instance.DrawSegment(p1, p2, new Color(0.8f, 0.8f, 0.8f)); break; } case JointType.Revolute: { instance.DrawSegment(x1, p1, color); instance.DrawSegment(p1, p2, color); instance.DrawSegment(x2, p2, color); instance.DrawSolidCircle(p2, 0.1f, Vector2.Zero, Color.Red); instance.DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.Blue); break; } case JointType.Gear: { instance.DrawSegment(x1, x2, color); break; } default: { instance.DrawSegment(x1, p1, color); instance.DrawSegment(p1, p2, color); instance.DrawSegment(x2, p2, color); break; } } } public void DrawShape(Fixture fixture, FarseerPhysics.Common.Transform xf, Color color) { switch (fixture.Shape.ShapeType) { case ShapeType.Circle: { var circle = (CircleShape) fixture.Shape; Vector2 center = MathUtils.Mul(ref xf, circle.Position); float radius = circle.Radius; Vector2 axis = MathUtils.Mul(xf.Q, new Vector2(1.0f, 0.0f)); DrawSolidCircle(center, radius, axis, color); } break; case ShapeType.Polygon: { var poly = (PolygonShape) fixture.Shape; int vertexCount = poly.Vertices.Count; System.Diagnostics.Debug.Assert(vertexCount <= Settings.MaxPolygonVertices); if (vertexCount > _tempVertices.Length) _tempVertices = new Vector2[vertexCount]; for (int i = 0; i < vertexCount; ++i) { _tempVertices[i] = MathUtils.Mul(ref xf, poly.Vertices[i]); } DrawSolidPolygon(_tempVertices, vertexCount, color); } break; case ShapeType.Edge: { var edge = (EdgeShape) fixture.Shape; var v1 = MathUtils.Mul(ref xf, edge.Vertex1); var v2 = MathUtils.Mul(ref xf, edge.Vertex2); DrawSegment(v1, v2, color); } break; case ShapeType.Chain: { var chain = (ChainShape) fixture.Shape; for (int i = 0; i < chain.Vertices.Count - 1; ++i) { var v1 = MathUtils.Mul(ref xf, chain.Vertices[i]); var v2 = MathUtils.Mul(ref xf, chain.Vertices[i + 1]); DrawSegment(v1, v2, color); } } break; } } public void DrawPolygon(Vector2[] vertices, int count, float red, float green, float blue, bool closed = true) { DrawPolygon(vertices, count, new Color(red, green, blue), closed); } public void DrawPolygon(Vector2[] vertices, int count, Color color, bool closed = true) { for (int i = 0; i < count - 1; i++) { _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[i]), color, PrimitiveType.LineList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[i + 1]), color, PrimitiveType.LineList); } if (closed) { _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[count - 1]), color, PrimitiveType.LineList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[0]), color, PrimitiveType.LineList); } } public void DrawSolidPolygon(Vector2[] vertices, int count, float red, float green, float blue) { DrawSolidPolygon(vertices, count, new Color(red, green, blue)); } public void DrawSolidPolygon(Vector2[] vertices, int count, Color color, bool outline = true) { if (count == 2) { DrawPolygon(vertices, count, color); return; } var colorFill = color * (outline ? 0.5f : 1.0f); for (int i = 1; i < count - 1; i++) { _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[0]), colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[i]), colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(vertices[i + 1]), colorFill, PrimitiveType.TriangleList); } if (outline) DrawPolygon(vertices, count, color); } public void DrawCircle(Vector2 center, float radius, float red, float green, float blue) { DrawCircle(center, radius, new Color(red, green, blue)); } public void DrawCircle(Vector2 center, float radius, Color color) { const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; for (int i = 0; i < CircleSegments; i++) { Vector2 v1 = center + radius * new Vector2((float) Math.Cos(theta), (float) Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment)); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(v1), color, PrimitiveType.LineList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(v2), color, PrimitiveType.LineList); theta += increment; } } public void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, float red, float green, float blue) { DrawSolidCircle(center, radius, axis, new Color(red, green, blue)); } public void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, Color color) { const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; Color colorFill = color * 0.5f; Vector2 v0 = center + radius * new Vector2((float) Math.Cos(theta), (float) Math.Sin(theta)); FSConvert.ToDisplayUnits(ref v0, out v0); theta += increment; for (int i = 1; i < CircleSegments - 1; i++) { Vector2 v1 = center + radius * new Vector2((float) Math.Cos(theta), (float) Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment)); _primitiveBatch.AddVertex(v0, colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(v1), colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(FSConvert.ToDisplayUnits(v2), colorFill, PrimitiveType.TriangleList); theta += increment; } DrawCircle(center, radius, color); DrawSegment(center, center + axis * radius, color); } public void DrawSegment(Vector2 start, Vector2 end, float red, float green, float blue) { DrawSegment(start, end, new Color(red, green, blue)); } public void DrawSegment(Vector2 start, Vector2 end, Color color) { start = FSConvert.ToDisplayUnits(start); end = FSConvert.ToDisplayUnits(end); _primitiveBatch.AddVertex(start, color, PrimitiveType.LineList); _primitiveBatch.AddVertex(end, color, PrimitiveType.LineList); } public void DrawTransform(ref FarseerPhysics.Common.Transform transform) { const float axisScale = 0.4f; Vector2 p1 = transform.P; Vector2 p2 = p1 + axisScale * transform.Q.GetXAxis(); DrawSegment(p1, p2, Color.Red); p2 = p1 + axisScale * transform.Q.GetYAxis(); DrawSegment(p1, p2, Color.Green); } public void DrawPoint(Vector2 p, float size, Color color) { Vector2[] verts = new Vector2[4]; float hs = size / 2.0f; verts[0] = p + new Vector2(-hs, -hs); verts[1] = p + new Vector2(hs, -hs); verts[2] = p + new Vector2(hs, hs); verts[3] = p + new Vector2(-hs, hs); DrawSolidPolygon(verts, 4, color, true); } public void DrawString(int x, int y, string text) { DrawString(new Vector2(x, y), text); } public void DrawString(Vector2 position, string text) { _stringData.Add(new StringData(position, text, TextColor)); } public void DrawArrow(Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator, Color color) { // Draw connection segment between start- and end-point DrawSegment(start, end, color); // Precalculate halfwidth var halfWidth = width / 2; // Create directional reference var rotation = (start - end); Nez.Vector2Ext.Normalize(ref rotation); // Calculate angle of directional vector var angle = (float) Math.Atan2(rotation.X, -rotation.Y); // Create matrix for rotation var rotMatrix = Matrix.CreateRotationZ(angle); // Create translation matrix for end-point var endMatrix = Matrix.CreateTranslation(end.X, end.Y, 0); // Setup arrow end shape var verts = new Vector2[3]; verts[0] = new Vector2(0, 0); verts[1] = new Vector2(-halfWidth, -length); verts[2] = new Vector2(halfWidth, -length); // Rotate end shape Vector2.Transform(verts, ref rotMatrix, verts); // Translate end shape Vector2.Transform(verts, ref endMatrix, verts); // Draw arrow end shape DrawSolidPolygon(verts, 3, color, false); if (drawStartIndicator) { // Create translation matrix for start var startMatrix = Matrix.CreateTranslation(start.X, start.Y, 0); // Setup arrow start shape var baseVerts = new Vector2[4]; baseVerts[0] = new Vector2(-halfWidth, length / 4); baseVerts[1] = new Vector2(halfWidth, length / 4); baseVerts[2] = new Vector2(halfWidth, 0); baseVerts[3] = new Vector2(-halfWidth, 0); // Rotate start shape Vector2.Transform(baseVerts, ref rotMatrix, baseVerts); // Translate start shape Vector2.Transform(baseVerts, ref startMatrix, baseVerts); // Draw start shape DrawSolidPolygon(baseVerts, 4, color, false); } } #endregion public void BeginCustomDraw() { _primitiveBatch.Begin(Entity.Scene.Camera.ProjectionMatrix, Entity.Scene.Camera.TransformMatrix); } public void EndCustomDraw() { _primitiveBatch.End(); } public override void Render(Batcher batcher, Camera camera) { // nothing is enabled - don't draw the debug view. if (Flags == 0) return; Core.GraphicsDevice.RasterizerState = RasterizerState.CullNone; Core.GraphicsDevice.DepthStencilState = DepthStencilState.Default; _primitiveBatch.Begin(camera.ProjectionMatrix, camera.TransformMatrix); DrawDebugData(); _primitiveBatch.End(); if ((Flags & DebugViewFlags.PerformanceGraph) == DebugViewFlags.PerformanceGraph) { _primitiveBatch.Begin(ref _localProjection, ref _localView); DrawPerformanceGraph(); _primitiveBatch.End(); } // draw any strings we have for (int i = 0; i < _stringData.Count; i++) batcher.DrawString(Graphics.Instance.BitmapFont, _stringData[i].Text, _stringData[i].Position, _stringData[i].Color); _stringData.Clear(); } #region Nested types [Flags] public enum DebugViewFlags { /// <summary> /// Draw shapes. /// </summary> Shape = (1 << 0), /// <summary> /// Draw joint connections. /// </summary> Joint = (1 << 1), /// <summary> /// Draw axis aligned bounding boxes. /// </summary> AABB = (1 << 2), // Draw broad-phase pairs. //Pair = (1 << 3), /// <summary> /// Draw center of mass frame. /// </summary> CenterOfMass = (1 << 4), /// <summary> /// Draw useful debug data such as timings and number of bodies, joints, contacts and more. /// </summary> DebugPanel = (1 << 5), /// <summary> /// Draw contact points between colliding bodies. /// </summary> ContactPoints = (1 << 6), /// <summary> /// Draw contact normals. Need ContactPoints to be enabled first. /// </summary> ContactNormals = (1 << 7), /// <summary> /// Draws the vertices of polygons. /// </summary> PolygonPoints = (1 << 8), /// <summary> /// Draws the performance graph. /// </summary> PerformanceGraph = (1 << 9), /// <summary> /// Draws controllers. /// </summary> Controllers = (1 << 10) } struct ContactPoint { public Vector2 Normal; public Vector2 Position; public PointState State; } struct StringData { public Color Color; public string Text; public Vector2 Position; public StringData(Vector2 position, string text, Color color) { this.Position = position; this.Text = text; this.Color = color; } } #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.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public partial class ConcurrentBagTests : ProducerConsumerCollectionTests { protected override IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>() => new ConcurrentBag<T>(); protected override IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection) => new ConcurrentBag<int>(collection); protected override bool IsEmpty(IProducerConsumerCollection<int> pcc) => ((ConcurrentBag<int>)pcc).IsEmpty; protected override bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result) => ((ConcurrentBag<T>)pcc).TryPeek(out result); protected override IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection) => new BagOracle(collection); [Theory] [InlineData(1, 10)] [InlineData(3, 100)] [InlineData(8, 1000)] public static void AddThenPeek_LatestLocalItemReturned(int threadsCount, int itemsPerThread) { var bag = new ConcurrentBag<int>(); using (var b = new Barrier(threadsCount)) { WaitAllOrAnyFailed((Enumerable.Range(0, threadsCount).Select(_ => Task.Factory.StartNew(() => { b.SignalAndWait(); for (int i = 1; i < itemsPerThread + 1; i++) { bag.Add(i); int item; Assert.True(bag.TryPeek(out item)); // ordering implementation detail that's not guaranteed Assert.Equal(i, item); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default))).ToArray()); } Assert.Equal(itemsPerThread * threadsCount, bag.Count); } [Fact] public static void AddOnOneThread_PeekOnAnother_EnsureWeCanTakeOnTheOriginal() { var bag = new ConcurrentBag<int>(Enumerable.Range(1, 5)); Task.Factory.StartNew(() => { int item; for (int i = 1; i <= 5; i++) { Assert.True(bag.TryPeek(out item)); Assert.Equal(1, item); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).GetAwaiter().GetResult(); Assert.Equal(5, bag.Count); for (int i = 5; i > 0; i--) { int item; Assert.True(bag.TryPeek(out item)); Assert.Equal(i, item); // ordering implementation detail that's not guaranteed Assert.Equal(i, bag.Count); Assert.True(bag.TryTake(out item)); Assert.Equal(i - 1, bag.Count); Assert.Equal(i, item); // ordering implementation detail that's not guaranteed } } [Fact] public static void AddManyItems_ThenTakeOnDifferentThread_ItemsOutputInExpectedOrder() { var bag = new ConcurrentBag<int>(Enumerable.Range(0, 100000)); Task.Factory.StartNew(() => { for (int i = 0; i < 100000; i++) { int item; Assert.True(bag.TryTake(out item)); Assert.Equal(i, item); // Testing an implementation detail rather than guaranteed ordering } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).GetAwaiter().GetResult(); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(33)] public static void IterativelyAddOnOneThreadThenTakeOnAnother_OrderMaintained(int initialCount) { var bag = new ConcurrentBag<int>(Enumerable.Range(0, initialCount)); const int Iterations = 100; using (AutoResetEvent itemConsumed = new AutoResetEvent(false), itemProduced = new AutoResetEvent(false)) { Task t = Task.Run(() => { for (int i = 0; i < Iterations; i++) { itemProduced.WaitOne(); int item; Assert.True(bag.TryTake(out item)); Assert.Equal(i, item); // Testing an implementation detail rather than guaranteed ordering itemConsumed.Set(); } }); for (int i = initialCount; i < Iterations + initialCount; i++) { bag.Add(i); itemProduced.Set(); itemConsumed.WaitOne(); } t.GetAwaiter().GetResult(); } Assert.Equal(initialCount, bag.Count); } [Fact] public static void CopyTo_TypeMismatch() { const int Size = 10; var c = new ConcurrentBag<Exception>(Enumerable.Range(0, Size).Select(_ => new Exception())); c.CopyTo(new Exception[Size], 0); Assert.Throws<InvalidCastException>(() => c.CopyTo(new InvalidOperationException[Size], 0)); } [Fact] public static void ICollectionCopyTo_TypeMismatch() { const int Size = 10; ICollection c; c = new ConcurrentBag<Exception>(Enumerable.Range(0, Size).Select(_ => new Exception())); c.CopyTo(new Exception[Size], 0); Assert.Throws<InvalidCastException>(() => c.CopyTo(new InvalidOperationException[Size], 0)); c = new ConcurrentBag<ArgumentException>(Enumerable.Range(0, Size).Select(_ => new ArgumentException())); c.CopyTo(new Exception[Size], 0); c.CopyTo(new ArgumentException[Size], 0); Assert.Throws<InvalidCastException>(() => c.CopyTo(new ArgumentNullException[Size], 0)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] public static void ToArray_AddTakeDifferentThreads_ExpectedResultsAfterAddsAndTakes(int initialCount) { var bag = new ConcurrentBag<int>(Enumerable.Range(0, initialCount)); int items = 20 + initialCount; for (int i = 0; i < items; i++) { bag.Add(i + initialCount); ThreadFactory.StartNew(() => { int item; Assert.True(bag.TryTake(out item)); Assert.Equal(item, i); }).GetAwaiter().GetResult(); Assert.Equal(Enumerable.Range(i + 1, initialCount).Reverse(), bag.ToArray()); } } protected sealed class BagOracle : IProducerConsumerCollection<int> { private readonly Stack<int> _stack; public BagOracle(IEnumerable<int> collection) { _stack = new Stack<int>(collection); } public int Count => _stack.Count; public bool IsSynchronized => false; public object SyncRoot => null; public void CopyTo(Array array, int index) => _stack.ToArray().CopyTo(array, index); public void CopyTo(int[] array, int index) => _stack.ToArray().CopyTo(array, index); public IEnumerator<int> GetEnumerator() => _stack.GetEnumerator(); public int[] ToArray() => _stack.ToArray(); public bool TryAdd(int item) { _stack.Push(item); return true; } public bool TryTake(out int item) { if (_stack.Count > 0) { item = _stack.Pop(); return true; } else { item = 0; return false; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.CompilerServices; using System.Threading; using BTDB.StreamLayer; namespace BTDB.KVDBLayer { public class OnDiskMemoryMappedFileCollection : IFileCollection { public IDeleteFileCollectionStrategy DeleteFileCollectionStrategy { get => _deleteFileCollectionStrategy ??= new JustDeleteFileCollectionStrategy(); set => _deleteFileCollectionStrategy = value; } readonly string _directory; // disable invalid warning about using volatile inside Interlocked.CompareExchange #pragma warning disable 420 volatile Dictionary<uint, File> _files = new Dictionary<uint, File>(); int _maxFileId; IDeleteFileCollectionStrategy? _deleteFileCollectionStrategy; sealed unsafe class File : IFileCollectionFile { readonly OnDiskMemoryMappedFileCollection _owner; readonly uint _index; readonly string _fileName; long _trueLength; long _cachedLength; readonly FileStream _stream; readonly object _lock = new object(); readonly Writer _writer; MemoryMappedFile? _memoryMappedFile; MemoryMappedViewAccessor? _accessor; byte* _pointer; const long ResizeChunkSize = 4 * 1024 * 1024; public File(OnDiskMemoryMappedFileCollection owner, uint index, string fileName) { _owner = owner; _index = index; _fileName = fileName; _stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 1, FileOptions.None); _trueLength = _stream.Length; _cachedLength = _trueLength; _writer = new Writer(this); } internal void Dispose() { _writer.FlushBuffer(); UnmapContent(); _stream.SetLength(_trueLength); _stream.Dispose(); } public uint Index => _index; void MapContent() { if (_accessor != null) return; _memoryMappedFile = MemoryMappedFile.CreateFromFile(_stream, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true); _accessor = _memoryMappedFile!.CreateViewAccessor(); _accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref _pointer); } void UnmapContent() { if (_accessor == null) return; _accessor.SafeMemoryMappedViewHandle.ReleasePointer(); _accessor.Dispose(); _accessor = null; _memoryMappedFile!.Dispose(); _memoryMappedFile = null; } sealed class Reader : ISpanReader { readonly File _owner; readonly ulong _valueSize; ulong _ofs; public Reader(File owner) { _owner = owner; _valueSize = _owner.GetSize(); if (_valueSize != 0) { _owner.MapContent(); } _ofs = 0; } public void Init(ref SpanReader spanReader) { spanReader.Buf = new Span<byte>(_owner._pointer + _ofs, (int)Math.Min(_valueSize - _ofs, int.MaxValue)); spanReader.Original = spanReader.Buf; } public bool FillBufAndCheckForEof(ref SpanReader spanReader) { _ofs += (ulong)(spanReader.Original.Length - spanReader.Buf.Length); spanReader.Buf = new Span<byte>(_owner._pointer + _ofs, (int)Math.Min(_valueSize - _ofs, int.MaxValue)); spanReader.Original = spanReader.Buf; return 0 == spanReader.Buf.Length; } public long GetCurrentPosition(in SpanReader spanReader) { return (long)_ofs + spanReader.Original.Length - spanReader.Buf.Length; } public bool ReadBlock(ref SpanReader spanReader, ref byte buffer, uint length) { if (length <= _valueSize - _ofs) { Unsafe.CopyBlockUnaligned(ref buffer, ref Unsafe.AsRef<byte>(_owner._pointer + _ofs), length); _ofs += length; return false; } _ofs = _valueSize; return true; } public bool SkipBlock(ref SpanReader spanReader, uint length) { if (length <= _valueSize - _ofs) { _ofs += length; return false; } _ofs = _valueSize; return true; } public void SetCurrentPosition(ref SpanReader spanReader, long position) { throw new NotSupportedException(); } public void Sync(ref SpanReader spanReader) { _ofs += (uint)(spanReader.Original.Length - spanReader.Buf.Length); } } sealed class Writer : ISpanWriter { readonly File _file; internal ulong Ofs; public Writer(File file) { _file = file; Ofs = (ulong)_file._trueLength; } public void FlushBuffer() { lock (_file._lock) { _file._trueLength = (long)Ofs; } } void ExpandIfNeeded(long size) { if (_file._cachedLength < size) { _file.UnmapContent(); var newSize = ((size - 1) / ResizeChunkSize + 1) * ResizeChunkSize; _file._stream.SetLength(newSize); _file._cachedLength = newSize; } _file.MapContent(); } public void Init(ref SpanWriter spanWriter) { spanWriter.Buf = new Span<byte>(_file._pointer + Ofs, (int)Math.Min((ulong)_file._trueLength - Ofs, int.MaxValue)); spanWriter.InitialBuffer = spanWriter.Buf; } public void Sync(ref SpanWriter spanWriter) { Ofs += (ulong)(spanWriter.InitialBuffer.Length - spanWriter.Buf.Length); } public bool Flush(ref SpanWriter spanWriter) { Sync(ref spanWriter); ExpandIfNeeded((long)Ofs + ResizeChunkSize); Init(ref spanWriter); return true; } public long GetCurrentPosition(in SpanWriter spanWriter) { return (long)(Ofs + (ulong)(spanWriter.InitialBuffer.Length - spanWriter.Buf.Length)); } public long GetCurrentPositionWithoutWriter() { return (long)Ofs; } public void WriteBlock(ref SpanWriter spanWriter, ref byte buffer, uint length) { Sync(ref spanWriter); ExpandIfNeeded((long)Ofs + length); WriteBlockWithoutWriter(ref buffer, length); Init(ref spanWriter); } public void WriteBlockWithoutWriter(ref byte buffer, uint length) { Unsafe.CopyBlockUnaligned(ref buffer, ref Unsafe.AsRef<byte>(_file._pointer + Ofs), length); Ofs += length; } public void SetCurrentPosition(ref SpanWriter spanWriter, long position) { throw new NotSupportedException(); } } public ISpanReader GetExclusiveReader() { return new Reader(this); } public void AdvisePrefetch() { } public void RandomRead(Span<byte> data, ulong position, bool doNotCache) { lock (_lock) { if (data.Length > 0 && position < _writer.Ofs) { MapContent(); var read = data.Length; if (_writer.Ofs - position < (ulong)read) read = (int)(_writer.Ofs - position); new Span<byte>(_pointer + position, read).CopyTo(data); data = data.Slice(read); } if (data.Length == 0) return; throw new EndOfStreamException(); } } public ISpanWriter GetAppenderWriter() { return _writer; } public ISpanWriter GetExclusiveAppenderWriter() { return _writer; } public void Flush() { _writer.FlushBuffer(); } public void HardFlush() { Flush(); _stream.Flush(true); } public void SetSize(long size) { _writer.FlushBuffer(); lock (_lock) { _writer.Ofs = (ulong)size; _trueLength = size; } } public void Truncate() { UnmapContent(); _stream.SetLength(_trueLength); } public void HardFlushTruncateSwitchToReadOnlyMode() { HardFlush(); Truncate(); } public void HardFlushTruncateSwitchToDisposedMode() { HardFlush(); Truncate(); } public ulong GetSize() { lock (_lock) { return (ulong)_writer.GetCurrentPositionWithoutWriter(); } } public void Remove() { Dictionary<uint, File> newFiles; Dictionary<uint, File> oldFiles; do { oldFiles = _owner._files; if (!oldFiles!.TryGetValue(_index, out _)) return; newFiles = new Dictionary<uint, File>(oldFiles); newFiles.Remove(_index); } while (Interlocked.CompareExchange(ref _owner._files, newFiles, oldFiles) != oldFiles); UnmapContent(); _stream.Dispose(); _owner.DeleteFileCollectionStrategy.DeleteFile(_fileName); } } public OnDiskMemoryMappedFileCollection(string directory) { _directory = directory; _maxFileId = 0; foreach (var filePath in Directory.EnumerateFiles(directory)) { var id = GetFileId(Path.GetFileNameWithoutExtension(filePath)); if (id == 0) continue; var file = new File(this, id, filePath); _files.Add(id, file); if (id > _maxFileId) _maxFileId = (int)id; } } static uint GetFileId(string fileName) { return uint.TryParse(fileName, out var result) ? result : 0; } public IFileCollectionFile AddFile(string? humanHint) { var index = (uint)Interlocked.Increment(ref _maxFileId); var fileName = index.ToString("D8") + "." + (humanHint ?? ""); var file = new File(this, index, Path.Combine(_directory, fileName)); Dictionary<uint, File> newFiles; Dictionary<uint, File> oldFiles; do { oldFiles = _files; newFiles = new Dictionary<uint, File>(oldFiles!) { { index, file } }; } while (Interlocked.CompareExchange(ref _files, newFiles, oldFiles) != oldFiles); return file; } public uint GetCount() { return (uint)_files.Count; } public IFileCollectionFile? GetFile(uint index) { return _files.TryGetValue(index, out var value) ? value : null; } public IEnumerable<IFileCollectionFile> Enumerate() { return _files.Values; } public void ConcurrentTemporaryTruncate(uint index, uint offset) { // Nothing to do } public void Dispose() { foreach (var file in _files.Values) { file.Dispose(); } } } }
// // 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 { using System; using System.ComponentModel; using System.Diagnostics; #if !NET40 && !NET35 using System.Threading.Tasks; #endif using JetBrains.Annotations; /// <summary> /// Extensions for NLog <see cref="ILogger"/>. /// </summary> [CLSCompliant(false)] public static class ILoggerExtensions { /// <summary> /// Starts building a log event with the specified <see cref="LogLevel"/>. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <param name="logLevel">The log level. When not</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForLogEvent([NotNull] this ILogger logger, LogLevel logLevel = null) { return logLevel is null ? new LogEventBuilder(logger) : new LogEventBuilder(logger, logLevel); } /// <summary> /// Starts building a log event at the <c>Trace</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForTraceEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Trace); } /// <summary> /// Starts building a log event at the <c>Debug</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForDebugEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Debug); } /// <summary> /// Starts building a log event at the <c>Info</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForInfoEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Info); } /// <summary> /// Starts building a log event at the <c>Warn</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForWarnEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Warn); } /// <summary> /// Starts building a log event at the <c>Error</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForErrorEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Error); } /// <summary> /// Starts building a log event at the <c>Fatal</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForFatalEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Fatal); } /// <summary> /// Starts building a log event at the <c>Exception</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <param name="exception">The exception information of the logging event.</param> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event. Defaults to <see cref="LogLevel.Error"/> when not specified.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForExceptionEvent([NotNull] this ILogger logger, Exception exception, LogLevel logLevel = null) { return ForLogEvent(logger, logLevel ?? LogLevel.Error).Exception(exception); } #region ConditionalDebug /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalDebug<T>([NotNull] this ILogger logger, T value) { logger.Debug(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalDebug<T>([NotNull] this ILogger logger, IFormatProvider formatProvider, T value) { logger.Debug(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public static void ConditionalDebug([NotNull] this ILogger logger, LogMessageGenerator messageFunc) { logger.Debug(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public static void ConditionalDebug([NotNull] this ILogger logger, [Localizable(false)] string message) { logger.Debug(message, default(object[])); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument1, TArgument2>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument1, TArgument2, TArgument3>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument1, argument2, argument3 }); } } #endregion #region ConditionalTrace /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalTrace<T>([NotNull] this ILogger logger, T value) { logger.Trace(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalTrace<T>([NotNull] this ILogger logger, IFormatProvider formatProvider, T value) { logger.Trace(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public static void ConditionalTrace([NotNull] this ILogger logger, LogMessageGenerator messageFunc) { logger.Trace(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public static void ConditionalTrace([NotNull] this ILogger logger, [Localizable(false)] string message) { logger.Trace(message, default(object[])); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument1, TArgument2>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument1, TArgument2, TArgument3>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument1, argument2, argument3 }); } } #endregion /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Log([NotNull] this ILogger logger, LogLevel level, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsEnabled(level)) { logger.Log(level, exception, messageFunc(), null); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Trace([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsTraceEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Trace(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Debug([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsDebugEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Debug(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Info([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsInfoEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Info(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Warn([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsWarnEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Warn(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Error([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsErrorEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Error(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Fatal([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsFatalEnabled) { if (messageFunc is null) { throw new ArgumentNullException(nameof(messageFunc)); } logger.Fatal(exception, messageFunc()); } } } }
using System; using System.IO; using System.Linq; using Baseline; using Marten.Exceptions; using Marten.Schema; namespace Marten.Storage { public class TenantSchema: IDocumentSchema { private readonly StorageFeatures _features; private readonly Tenant _tenant; public TenantSchema(StoreOptions options, Tenant tenant) { _features = options.Storage; _tenant = tenant; StoreOptions = options; DdlRules = options.DdlRules; } public StoreOptions StoreOptions { get; } public DdlRules DdlRules { get; } public void WriteDDL(string filename, bool transactionalScript = true) { var sql = ToDDL(transactionalScript); new FileSystem().WriteStringToFile(filename, sql); } public void WriteDDLByType(string directory, bool transactionalScript = true) { var system = new FileSystem(); system.DeleteDirectory(directory); system.CreateDirectory(directory); var features = _features.AllActiveFeatures(_tenant).ToArray(); writeDatabaseSchemaGenerationScript(directory, system, features); foreach (var feature in features) { var writer = new StringWriter(); feature.Write(StoreOptions.DdlRules, writer); var file = directory.AppendPath(feature.Identifier + ".sql"); new SchemaPatch(StoreOptions.DdlRules).WriteFile(file, writer.ToString(), transactionalScript); } } private void writeDatabaseSchemaGenerationScript(string directory, FileSystem system, IFeatureSchema[] schemaObjects) { var allSchemaNames = StoreOptions.Storage.AllSchemaNames(); var script = DatabaseSchemaGenerator.GenerateScript(StoreOptions, allSchemaNames); var writer = new StringWriter(); if (script.IsNotEmpty()) { writer.WriteLine(script); writer.WriteLine(); } foreach (var feature in schemaObjects) { writer.WriteLine($"\\i {feature.Identifier}.sql"); } var filename = directory.AppendPath("all.sql"); system.WriteStringToFile(filename, writer.ToString()); } private SchemaPatch ToPatch(bool withSchemas, AutoCreate withAutoCreate) { var patch = new SchemaPatch(StoreOptions.DdlRules); if (withSchemas) { var allSchemaNames = StoreOptions.Storage.AllSchemaNames(); DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, patch.UpWriter); } var @objects = _features.AllActiveFeatures(_tenant).SelectMany(x => x.Objects).ToArray(); using (var conn = _tenant.CreateConnection()) { conn.Open(); patch.Apply(conn, withAutoCreate, @objects); } return patch; } public string ToDDL(bool transactionalScript = true) { var writer = new StringWriter(); new SchemaPatch(StoreOptions.DdlRules).WriteScript(writer, w => { var allSchemaNames = StoreOptions.Storage.AllSchemaNames(); DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, w); foreach (var feature in _features.AllActiveFeatures(_tenant)) { feature.Write(StoreOptions.DdlRules, writer); } }, transactionalScript); return writer.ToString(); } public void WritePatch(string filename, bool withSchemas = true, bool transactionalScript = true) { if (!Path.IsPathRooted(filename)) { filename = AppContext.BaseDirectory.AppendPath(filename); } var patch = ToPatch(withSchemas, withAutoCreateAll: true); patch.WriteUpdateFile(filename, transactionalScript); var dropFile = SchemaPatch.ToDropFileName(filename); patch.WriteRollbackFile(dropFile, transactionalScript); } public SchemaPatch ToPatch(bool withSchemas = true, bool withAutoCreateAll = false) { return ToPatch(withSchemas, withAutoCreateAll ? AutoCreate.All : StoreOptions.AutoCreateSchemaObjects); } public void AssertDatabaseMatchesConfiguration() { var patch = ToPatch(false, withAutoCreateAll: true); if (patch.UpdateDDL.Trim().IsNotEmpty()) { throw new SchemaValidationException(patch.UpdateDDL); } } public void ApplyAllConfiguredChangesToDatabase(AutoCreate? withCreateSchemaObjects = null) { var defaultAutoCreate = StoreOptions.AutoCreateSchemaObjects != AutoCreate.None ? StoreOptions.AutoCreateSchemaObjects : AutoCreate.CreateOrUpdate; var patch = ToPatch(true, withCreateSchemaObjects ?? defaultAutoCreate); var ddl = patch.UpdateDDL.Trim(); if (ddl.IsEmpty()) return; try { _tenant.RunSql(ddl); StoreOptions.Logger().SchemaChange(ddl); _tenant.MarkAllFeaturesAsChecked(); } catch (Exception e) { throw new MartenSchemaException("All Configured Changes", ddl, e); } } public SchemaPatch ToPatch(Type documentType) { var mapping = _features.MappingFor(documentType); var patch = new SchemaPatch(StoreOptions.DdlRules); using (var conn = _tenant.CreateConnection()) { conn.Open(); patch.Apply(conn, AutoCreate.CreateOrUpdate, mapping.As<IFeatureSchema>().Objects); } return patch; } public void WritePatchByType(string directory, bool transactionalScript = true) { var system = new FileSystem(); system.DeleteDirectory(directory); system.CreateDirectory(directory); var features = _features.AllActiveFeatures(_tenant).ToArray(); writeDatabaseSchemaGenerationScript(directory, system, features); using (var conn = _tenant.CreateConnection()) { conn.Open(); foreach (var feature in features) { var patch = new SchemaPatch(StoreOptions.DdlRules); patch.Apply(conn, AutoCreate.CreateOrUpdate, feature.Objects); if (patch.UpdateDDL.IsNotEmpty()) { var file = directory.AppendPath(feature.Identifier + ".sql"); patch.WriteUpdateFile(file, transactionalScript); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Xplore.Screens { public class GameplayScreen : Screen { private readonly Random _rand = new Random(); private readonly List<Enemy> _enemies = new List<Enemy>(); private readonly List<Boulder> _boulders = new List<Boulder>(); private MouseState _previousMouseState; private KeyboardState _previousKeyboardState; private MouseState _mouseState; private readonly Player _player; private SpatialGrid _spatialGrid; private const int MaxEnemyCount = 100; private const int MaxBoulderCount = 50; private Dictionary<string,ICollisionEntity> _collisionEntities = new Dictionary<string, ICollisionEntity>(); private const int GameSize = 8000; private Rectangle _gameBounds = new Rectangle(-(GameSize / 2), -(GameSize / 2), GameSize, GameSize); private KeyboardState _keyboardState; private Rectangle _backgroundRect => new Rectangle(_gameBounds.X-(_gameBounds.Width/2),_gameBounds.Y-(_gameBounds.Height/2),_gameBounds.Width*2,_gameBounds.Height*2); public override void LoadContent() { } public override void UnloadContent() { } private void EnemyShipDestroyed(object ship, EventArgs eventArgs) { _collisionEntities.Remove(((Enemy) ship).Guid.ToString()); _enemies.Remove((Enemy)ship); } public void SpawnEnemies() { //spawn an emeny if the count of total enemies is less than maxEnemyCount while (_enemies.Count < MaxEnemyCount) { float radius = (float)_rand.Next(_gameBounds.Width / 2, _gameBounds.Width) / 2; float angle = (float)_rand.NextDouble() * MathHelper.TwoPi; float x = _player.Center.X + radius * (float)Math.Cos(angle); float y = _player.Center.Y + radius * (float)Math.Sin(angle); var enemy = new Enemy(ContentProvider.EnemyShips[_rand.Next(ContentProvider.EnemyShips.Count)], new Vector2(x, y), ShipType.NpcEnemy); enemy.Wander(); _collisionEntities.Add(enemy.Guid.ToString(),enemy); enemy.Destroyed += EnemyShipDestroyed; _enemies.Add(enemy); } } public void SpawnBoulders() { while (_boulders.Count < MaxBoulderCount) { float radius = (float)_rand.Next(_gameBounds.Width / 2, _gameBounds.Width) / 2; float angle = (float)_rand.NextDouble() * MathHelper.TwoPi; float x = _player.Center.X + radius * (float)Math.Cos(angle); float y = _player.Center.Y + radius * (float)Math.Sin(angle); var boulder = new Boulder(ContentProvider.Boulder, new Vector2(x, y)); _collisionEntities.Add(boulder.Guid.ToString(), boulder); _boulders.Add(boulder); } } public void DespawnSprites() { var boulders = _boulders.ToArray(); var enemies = _enemies.ToArray(); foreach (var boulder in boulders) { if (IsSpriteOutSideGameBounds(boulder)) { _boulders.Remove(boulder); _collisionEntities.Remove(boulder.Guid.ToString()); } } foreach (var enemy in enemies) { if (IsSpriteOutSideGameBounds(enemy)) { //we need to cleanup the ship current particles enemy.CleanupParticles(); _collisionEntities.Remove(enemy.Guid.ToString()); _enemies.Remove(enemy); } } } public bool IsSpriteOutSideGameBounds(Sprite sprite) { return sprite.Position.X < _gameBounds.X || sprite.Position.X > _gameBounds.X + _gameBounds.Width || sprite.Position.Y < _gameBounds.Y || sprite.Position.Y > _gameBounds.Y + _gameBounds.Height; } public void ApplyMouseWheelZoom() { //zoom in/out if (_mouseState.ScrollWheelValue > _previousMouseState.ScrollWheelValue) { Camera.Zoom += 0.05f; } if (_mouseState.ScrollWheelValue < _previousMouseState.ScrollWheelValue) { Camera.Zoom -= 0.05f; } } public void UpdateGameBounds() { _gameBounds = new Rectangle((int)(_player.Position.X - GameSize/2f), (int)(_player.Position.Y - GameSize/2f),GameSize,GameSize); } //TODO there is an issue where either collision entities or sprites are not being correctly removed from the dictionary of objects requiring updates public override void Update(GameTime gameTime) { UpdateGameBounds(); _spatialGrid = new SpatialGrid(_gameBounds,200); _keyboardState = Keyboard.GetState(); _mouseState = Mouse.GetState(); if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) GameManager.PauseGame(); if (_keyboardState.IsKeyDown(Keys.K) && !_previousKeyboardState.IsKeyDown(Keys.K)) { GameManager.ToggleDebug(); } ApplyMouseWheelZoom(); Camera.Location = new Vector2(_player.Position.X, _player.Position.Y); UpdateLazersCollsions(); SpawnEnemies(); SpawnBoulders(); DespawnSprites(); _player.Update(gameTime); var enemies = _enemies.ToArray(); for (int i = 0; i < enemies.Length; i++) { var fleeDistance = 1000f; if ((_player.Center - enemies[i].Center).Length() < fleeDistance) { enemies[i].Flee(_player.Center, fleeDistance); } enemies[i].Update(gameTime); } foreach (var boulder in _boulders) { boulder.Update(gameTime); } CheckAndResolveCollisions(gameTime); _previousMouseState = _mouseState; _previousKeyboardState = _keyboardState; } private IEnumerable<Ship> GetAllShips() { var ships = new List<Ship>(); ships.AddRange(_enemies); ships.Add(_player); return ships; } private void UpdateLazersCollsions() { foreach (var ship in GetAllShips()) { foreach (var lazerBullet in ship.LazerBullets) { var guid = lazerBullet.Guid.ToString(); if (!_collisionEntities.ContainsKey(guid)) { _collisionEntities.Add(guid, lazerBullet); } } } var collisionEntityArray = _collisionEntities.ToArray(); for (int i = 0; i < collisionEntityArray.Length; i++) { if (!collisionEntityArray[i].Value.Active) { _collisionEntities.Remove(collisionEntityArray[i].Key); } } } /// <summary> /// we need to add a broad and narrow phase instead of checking O(n^2) /// </summary> private void CheckAndResolveCollisions(GameTime gameTime) { var loopCount = 0; foreach (var collisionEntity in _collisionEntities.Values) { _spatialGrid.Insert(collisionEntity.BoundingCircle.SourceRectangle,collisionEntity); } foreach (var gridBox in _spatialGrid.GetCollsionGrid().Values) { List<string> checkedCollisions = new List<string>(); if (gridBox.Count > 1) { foreach (var collisionEntity in gridBox) { foreach (var entity in gridBox) { var collisionIds = new string[] { collisionEntity.Guid.ToString(), entity.Guid.ToString() }.OrderBy( a => a); var value = string.Join("", collisionIds); //if we have already performed a collision check for these two objects skip check logic //also if the compare objects are the same don't bother checking... if (checkedCollisions.Contains(value) || entity == collisionEntity) { continue; } loopCount++; Vector2 collsionVector; if (CollisionHelper.IsCircleColliding(entity.BoundingCircle,collisionEntity.BoundingCircle,out collsionVector)) { if (collisionEntity.CollisionsWith == CollisionType.Lazer || entity.CollisionsWith == CollisionType.Lazer) { } else { _collisionEntities[entity.Guid.ToString()].ResolveSphereCollision(collsionVector); } var damage = 0; switch (entity.CollisionsWith) { case CollisionType.None: damage = 0; break; case CollisionType.Ship: damage = 1; break; case CollisionType.Boulder: damage = 3; break; case CollisionType.Lazer: damage = 4; break; default: throw new ArgumentOutOfRangeException(); } _collisionEntities[collisionEntity.Guid.ToString()].ApplyCollisionDamage(gameTime, damage); _collisionEntities[entity.Guid.ToString()].ApplyCollisionDamage(gameTime,0); //entity is colliding with collision entity so add it to the computed list of collisions } checkedCollisions.Add(value); } } } } Debug.WriteLine(loopCount); } public override void Draw(SpriteBatch spriteBatch, GameTime gameTime) { var backgroundRect = _backgroundRect; spriteBatch.Draw(ContentProvider.Background, new Vector2(backgroundRect.X, backgroundRect.Y), backgroundRect, Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0); _player.Draw(spriteBatch); //_spatialGrid.RenderGrid(spriteBatch); foreach (var enemy in _enemies) { enemy.Draw(spriteBatch); } foreach (var boulder in _boulders) { boulder.Draw(spriteBatch); } } public GameplayScreen(bool active, Main game) : base(active, game) { UserInterface = false; ScreenType = ScreenType.Gameplay; Camera.Bounds = Game.GraphicsDevice.Viewport.Bounds; _player = new Player(ContentProvider.Ship, new Vector2(0, 0), ShipType.Player); _collisionEntities.Add(_player.Guid.ToString(), _player); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository { /// <summary> /// Strongly-typed collection for the Customercustomerdemo class. /// </summary> [Serializable] public partial class CustomercustomerdemoCollection : RepositoryList<Customercustomerdemo, CustomercustomerdemoCollection> { public CustomercustomerdemoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>CustomercustomerdemoCollection</returns> public CustomercustomerdemoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Customercustomerdemo o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the customercustomerdemo table. /// </summary> [Serializable] public partial class Customercustomerdemo : RepositoryRecord<Customercustomerdemo>, IRecordBase { #region .ctors and Default Settings public Customercustomerdemo() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Customercustomerdemo(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("customercustomerdemo", TableType.Table, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema); colvarCustomerID.ColumnName = "CustomerID"; colvarCustomerID.DataType = DbType.AnsiStringFixedLength; colvarCustomerID.MaxLength = 5; colvarCustomerID.AutoIncrement = false; colvarCustomerID.IsNullable = false; colvarCustomerID.IsPrimaryKey = true; colvarCustomerID.IsForeignKey = false; colvarCustomerID.IsReadOnly = false; colvarCustomerID.DefaultSetting = @""; colvarCustomerID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCustomerID); TableSchema.TableColumn colvarCustomerTypeID = new TableSchema.TableColumn(schema); colvarCustomerTypeID.ColumnName = "CustomerTypeID"; colvarCustomerTypeID.DataType = DbType.AnsiStringFixedLength; colvarCustomerTypeID.MaxLength = 10; colvarCustomerTypeID.AutoIncrement = false; colvarCustomerTypeID.IsNullable = false; colvarCustomerTypeID.IsPrimaryKey = true; colvarCustomerTypeID.IsForeignKey = false; colvarCustomerTypeID.IsReadOnly = false; colvarCustomerTypeID.DefaultSetting = @""; colvarCustomerTypeID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCustomerTypeID); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("customercustomerdemo",schema); } } #endregion #region Props [XmlAttribute("CustomerID")] [Bindable(true)] public string CustomerID { get { return GetColumnValue<string>(Columns.CustomerID); } set { SetColumnValue(Columns.CustomerID, value); } } [XmlAttribute("CustomerTypeID")] [Bindable(true)] public string CustomerTypeID { get { return GetColumnValue<string>(Columns.CustomerTypeID); } set { SetColumnValue(Columns.CustomerTypeID, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region Typed Columns public static TableSchema.TableColumn CustomerIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CustomerTypeIDColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string CustomerID = @"CustomerID"; public static string CustomerTypeID = @"CustomerTypeID"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
//#define ASTAR_FAST_NO_EXCEPTIONS //Needs to be enabled for the iPhone build setting Fast But No Exceptions to work. using UnityEngine; using System.Collections; using System.Collections.Generic; //using Pathfinding; using Pathfinding.Util; namespace Pathfinding { [System.Serializable] /** Stores the navigation graphs for the A* Pathfinding System. * \ingroup relevant * * An instance of this class is assigned to AstarPath.astarData, from it you can access all graphs loaded through the #graphs variable.\n * This class also handles a lot of the high level serialization. */ public class AstarData { /** Shortcut to AstarPath.active */ public AstarPath active { get { return AstarPath.active; } } #region Fields [System.NonSerialized] public NavMeshGraph navmesh; /**< Shortcut to the first NavMeshGraph. Updated at scanning time. This is the only reference to NavMeshGraph in the core pathfinding scripts */ #if !ASTAR_NO_GRID_GRAPH [System.NonSerialized] public GridGraph gridGraph; /**< Shortcut to the first GridGraph. Updated at scanning time. This is the only reference to GridGraph in the core pathfinding scripts */ #endif #if !ASTAR_NO_POINT_GRAPH [System.NonSerialized] public PointGraph pointGraph; /**< Shortcut to the first PointGraph. Updated at scanning time. This is the only reference to PointGraph in the core pathfinding scripts */ #endif [System.NonSerialized] /** Shortcut to the first RecastGraph. Updated at scanning time. This is the only reference to RecastGraph in the core pathfinding scripts. * \astarpro */ public RecastGraph recastGraph; /** All supported graph types. Populated through reflection search */ public System.Type[] graphTypes = null; #if ASTAR_FAST_NO_EXCEPTIONS || NETFX_CORE /** Graph types to use when building with Fast But No Exceptions for iPhone. * If you add any custom graph types, you need to add them to this hard-coded list. */ public static readonly System.Type[] DefaultGraphTypes = new System.Type[] { #if !ASTAR_NO_GRID_GRAPH typeof(GridGraph), #endif #if !ASTAR_NO_POINT_GRAPH typeof(PointGraph), #endif typeof(NavMeshGraph), typeof(RecastGraph), typeof(LayerGridGraph) }; #endif [System.NonSerialized] /** All graphs this instance holds. * This will be filled only after deserialization has completed. * May contain null entries if graph have been removed. */ public NavGraph[] graphs = new NavGraph[0]; /** Links placed by the user in the scene view. */ [System.NonSerialized] public UserConnection[] userConnections = new UserConnection[0]; //Serialization Settings /** Has the data been reverted by an undo operation. * Used by the editor's undo logic to check if the AstarData has been reverted by an undo operation and should be deserialized */ public bool hasBeenReverted = false; [SerializeField] /** Serialized data for all graphs and settings. */ private byte[] data; public uint dataChecksum; /** Backup data if deserialization failed. */ public byte[] data_backup; /** Serialized data for cached startup */ public byte[] data_cachedStartup; public byte[] revertData; /** Should graph-data be cached. * Caching the startup means saving the whole graphs, not only the settings to an internal array (#data_cachedStartup) which can * be loaded faster than scanning all graphs at startup. This is setup from the editor. */ [SerializeField] public bool cacheStartup = false; public bool compress = false; //End Serialization Settings #endregion public byte[] GetData () { return data; } public void SetData (byte[] data, uint checksum) { this.data = data; dataChecksum = checksum; } /** Loads the graphs from memory, will load cached graphs if any exists */ public void Awake () { /* Set up default values, to not throw null reference errors */ userConnections = new UserConnection[0]; #if false graphs = new NavGraph[1] { CreateGraph (typeof(LinkGraph)) }; #else graphs = new NavGraph[0]; #endif /* End default values */ if (cacheStartup && data_cachedStartup != null) { LoadFromCache (); } else { DeserializeGraphs (); } } /** Updates shortcuts to the first graph of different types. * Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible. * But these references ease the use of the system, so I decided to keep them. It is the only reference to specific graph types in the pathfinding core.\n */ public void UpdateShortcuts () { navmesh = (NavMeshGraph)FindGraphOfType (typeof(NavMeshGraph)); #if !ASTAR_NO_GRID_GRAPH gridGraph = (GridGraph)FindGraphOfType (typeof(GridGraph)); #endif #if !ASTAR_NO_POINT_GRAPH pointGraph = (PointGraph)FindGraphOfType (typeof(PointGraph)); #endif recastGraph = (RecastGraph)FindGraphOfType (typeof(RecastGraph)); } public void LoadFromCache () { AstarPath.active.BlockUntilPathQueueBlocked(); if (data_cachedStartup != null && data_cachedStartup.Length > 0) { //AstarSerializer serializer = new AstarSerializer (active); //DeserializeGraphs (serializer,data_cachedStartup); DeserializeGraphs (data_cachedStartup); GraphModifier.TriggerEvent (GraphModifier.EventType.PostCacheLoad); } else { Debug.LogError ("Can't load from cache since the cache is empty"); } } public void SaveCacheData (Pathfinding.Serialization.SerializeSettings settings) { data_cachedStartup = SerializeGraphs (settings); cacheStartup = true; } #region Serialization /** Serializes all graphs settings to a byte array. * \see DeserializeGraphs(byte[]) */ public byte[] SerializeGraphs () { return SerializeGraphs (Pathfinding.Serialization.SerializeSettings.Settings); } /** Main serializer function. */ public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) { uint checksum; return SerializeGraphs (settings, out checksum); } /** Main serializer function. * Serializes all graphs to a byte array * A similar function exists in the AstarEditor.cs script to save additional info */ public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) { AstarPath.active.BlockUntilPathQueueBlocked(); Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this, settings); sr.OpenSerialize(); SerializeGraphsPart (sr); byte[] bytes = sr.CloseSerialize(); checksum = sr.GetChecksum (); #if ASTARDEBUG Debug.Log ("Got a whole bunch of data, "+bytes.Length+" bytes"); #endif return bytes; } /** Serializes common info to the serializer. * Common info is what is shared between the editor serialization and the runtime serializer. * This is mostly everything except the graph inspectors which serialize some extra data in the editor */ public void SerializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) { sr.SerializeGraphs(graphs); sr.SerializeUserConnections (userConnections); sr.SerializeNodes(); sr.SerializeExtraInfo(); } /** Deserializes graphs from #data */ public void DeserializeGraphs () { if (data != null) { DeserializeGraphs (data); } } /** Destroys all graphs and sets graphs to null */ void ClearGraphs () { if ( graphs == null ) return; for (int i=0;i<graphs.Length;i++) { if (graphs[i] != null) graphs[i].OnDestroy (); } graphs = null; UpdateShortcuts (); } public void OnDestroy () { ClearGraphs (); } /** Deserializes graphs from the specified byte array. * If an error ocurred, it will try to deserialize using the old deserializer. * A warning will be logged if all deserializers failed. */ public void DeserializeGraphs (byte[] bytes) { AstarPath.active.BlockUntilPathQueueBlocked(); try { if (bytes != null) { Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this); if (sr.OpenDeserialize(bytes)) { DeserializeGraphsPart (sr); sr.CloseDeserialize(); } else { Debug.Log ("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system"); } } else { throw new System.ArgumentNullException ("Bytes should not be null when passed to DeserializeGraphs"); } active.VerifyIntegrity (); } catch (System.Exception e) { Debug.LogWarning ("Caught exception while deserializing data.\n"+e); data_backup = bytes; } } /** Deserializes graphs from the specified byte array additively. * If an error ocurred, it will try to deserialize using the old deserializer. * A warning will be logged if all deserializers failed. * This function will add loaded graphs to the current ones */ public void DeserializeGraphsAdditive (byte[] bytes) { AstarPath.active.BlockUntilPathQueueBlocked(); try { if (bytes != null) { Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this); if (sr.OpenDeserialize(bytes)) { DeserializeGraphsPartAdditive (sr); sr.CloseDeserialize(); } else { Debug.Log ("Invalid data file (cannot read zip)."); } } else { throw new System.ArgumentNullException ("Bytes should not be null when passed to DeserializeGraphs"); } active.VerifyIntegrity (); } catch (System.Exception e) { Debug.LogWarning ("Caught exception while deserializing data.\n"+e); } } /** Deserializes common info. * Common info is what is shared between the editor serialization and the runtime serializer. * This is mostly everything except the graph inspectors which serialize some extra data in the editor */ public void DeserializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) { ClearGraphs (); graphs = sr.DeserializeGraphs (); if ( graphs != null ) for ( int i = 0; i<graphs.Length;i++ ) if ( graphs[i] != null ) graphs[i].graphIndex = (uint)i; userConnections = sr.DeserializeUserConnections(); //sr.DeserializeNodes(); sr.DeserializeExtraInfo(); sr.PostDeserialization(); } /** Deserializes common info additively * Common info is what is shared between the editor serialization and the runtime serializer. * This is mostly everything except the graph inspectors which serialize some extra data in the editor */ public void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) { if (graphs == null) graphs = new NavGraph[0]; if (userConnections == null) userConnections = new UserConnection[0]; List<NavGraph> gr = new List<NavGraph>(graphs); gr.AddRange (sr.DeserializeGraphs ()); graphs = gr.ToArray(); if ( graphs != null ) for ( int i = 0; i<graphs.Length;i++ ) if ( graphs[i] != null ) graphs[i].graphIndex = (uint)i; List<UserConnection> conns = new List<UserConnection>(userConnections); conns.AddRange (sr.DeserializeUserConnections()); userConnections = conns.ToArray (); sr.DeserializeNodes(); //Assign correct graph indices. Issue #21 for (int i=0;i<graphs.Length;i++) { if (graphs[i] == null) continue; graphs[i].GetNodes (delegate (GraphNode node) { //GraphNode[] nodes = graphs[i].nodes; node.GraphIndex = (uint)i; return true; }); } sr.DeserializeExtraInfo(); sr.PostDeserialization(); for (int i=0;i<graphs.Length;i++) { for (int j=i+1;j<graphs.Length;j++) { if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) { Debug.LogWarning ("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless."); graphs[i].guid = Pathfinding.Util.Guid.NewGuid (); break; } } } } #endregion /** Find all graph types supported in this build. * Using reflection, the assembly is searched for types which inherit from NavGraph. */ public void FindGraphTypes () { #if !ASTAR_FAST_NO_EXCEPTIONS && !NETFX_CORE System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly (typeof(AstarPath)); System.Type[] types = asm.GetTypes (); List<System.Type> graphList = new List<System.Type> (); foreach (System.Type type in types) { System.Type baseType = type.BaseType; while (baseType != null) { if (System.Type.Equals ( baseType, typeof(NavGraph) )) { graphList.Add (type); break; } // I hate Windows Store, this is just "baseType = baseType.BaseType;" baseType = baseType.BaseType; } } graphTypes = graphList.ToArray (); #if ASTARDEBUG Debug.Log ("Found "+graphTypes.Length+" graph types"); #endif #else graphTypes = DefaultGraphTypes; #endif } #region GraphCreation /** \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned */ public System.Type GetGraphType (string type) { for (int i=0;i<graphTypes.Length;i++) { if (graphTypes[i].Name == type) { return graphTypes[i]; } } return null; } /** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned * \returns The created graph * \see CreateGraph(System.Type) */ public NavGraph CreateGraph (string type) { Debug.Log ("Creating Graph of type '"+type+"'"); for (int i=0;i<graphTypes.Length;i++) { if (graphTypes[i].Name == type) { return CreateGraph (graphTypes[i]); } } Debug.LogError ("Graph type ("+type+") wasn't found"); return null; } /** Creates a new graph instance of type \a type * \see CreateGraph(string) */ public NavGraph CreateGraph (System.Type type) { NavGraph g = System.Activator.CreateInstance (type) as NavGraph; g.active = active; return g; } /** Adds a graph of type \a type to the #graphs array */ public NavGraph AddGraph (string type) { NavGraph graph = null; for (int i=0;i<graphTypes.Length;i++) { if (graphTypes[i].Name == type) { graph = CreateGraph (graphTypes[i]); } } if (graph == null) { Debug.LogError ("No NavGraph of type '"+type+"' could be found"); return null; } AddGraph (graph); return graph; } /** Adds a graph of type \a type to the #graphs array */ public NavGraph AddGraph (System.Type type) { NavGraph graph = null; for (int i=0;i<graphTypes.Length;i++) { if (System.Type.Equals (graphTypes[i], type)) { graph = CreateGraph (graphTypes[i]); } } if (graph == null) { Debug.LogError ("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable"); return null; } AddGraph (graph); return graph; } /** Adds the specified graph to the #graphs array */ public void AddGraph (NavGraph graph) { // Make sure to not interfere with pathfinding AstarPath.active.BlockUntilPathQueueBlocked(); //Try to fill in an empty position for (int i=0;i<graphs.Length;i++) { if (graphs[i] == null) { graphs[i] = graph; return; } } if (graphs != null && graphs.Length >= GraphNode.MaxGraphCount-1) { throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphCount + " graphs. Some compiler directives can change this limit, e.g ASTAR_MORE_AREAS, look under the " + "'Optimizations' tab in the A* Inspector"); } //Add a new entry to the list List<NavGraph> ls = new List<NavGraph> (graphs); ls.Add (graph); graphs = ls.ToArray (); UpdateShortcuts (); graph.active = active; graph.Awake (); graph.graphIndex = (uint)(graphs.Length-1); } /** Removes the specified graph from the #graphs array and Destroys it in a safe manner. * To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead * of actually removing it from the array. * The empty position will be reused if a new graph is added. * * \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise. * * \see NavGraph.SafeOnDestroy * * \version Changed in 3.2.5 to call SafeOnDestroy before removing * and nulling it in the array instead of removing the element completely in the #graphs array. * */ public bool RemoveGraph (NavGraph graph) { //Safe OnDestroy is called since there is a risk that the pathfinding is searching through the graph right now, //and if we don't wait until the search has completed we could end up with evil NullReferenceExceptions graph.SafeOnDestroy (); int i=0; for (;i<graphs.Length;i++) if (graphs[i] == graph) break; if (i == graphs.Length) { return false; } graphs[i] = null; UpdateShortcuts (); return true; } #endregion #region GraphUtility /** Returns the graph which contains the specified node. The graph must be in the #graphs array. * \returns Returns the graph which contains the node. Null if the graph wasn't found */ public static NavGraph GetGraph (GraphNode node) { if (node == null) return null; AstarPath script = AstarPath.active; if (script == null) return null; AstarData data = script.astarData; if (data == null) return null; if (data.graphs == null) return null; uint graphIndex = node.GraphIndex; if (graphIndex >= data.graphs.Length) { return null; } return data.graphs[(int)graphIndex]; } /** Returns the node at \a graphs[graphIndex].nodes[nodeIndex]. All kinds of error checking is done to make sure no exceptions are thrown. */ public GraphNode GetNode (int graphIndex, int nodeIndex) { return GetNode (graphIndex,nodeIndex, graphs); } /** Returns the node at \a graphs[graphIndex].nodes[nodeIndex]. The graphIndex refers to the specified graphs array.\n * All kinds of error checking is done to make sure no exceptions are thrown */ public GraphNode GetNode (int graphIndex, int nodeIndex, NavGraph[] graphs) { throw new System.NotImplementedException (); /* if (graphs == null) { return null; } if (graphIndex < 0 || graphIndex >= graphs.Length) { Debug.LogError ("Graph index is out of range"+graphIndex+ " [0-"+(graphs.Length-1)+"]"); return null; } NavGraph graph = graphs[graphIndex]; if (graph.nodes == null) { return null; } if (nodeIndex < 0 || nodeIndex >= graph.nodes.Length) { Debug.LogError ("Node index is out of range : "+nodeIndex+ " [0-"+(graph.nodes.Length-1)+"]"+" (graph "+graphIndex+")"); return null; } return graph.nodes[nodeIndex];*/ } /** Returns the first graph of type \a type found in the #graphs array. Returns null if none was found */ public NavGraph FindGraphOfType (System.Type type) { if ( graphs != null ) { for (int i=0;i<graphs.Length;i++) { if (graphs[i] != null && System.Type.Equals (graphs[i].GetType (), type)) { return graphs[i]; } } } return null; } /** Loop through this function to get all graphs of type 'type' * \code foreach (GridGraph graph in AstarPath.astarData.FindGraphsOfType (typeof(GridGraph))) { * //Do something with the graph * } \endcode * \see AstarPath.RegisterSafeNodeUpdate */ public IEnumerable FindGraphsOfType (System.Type type) { if (graphs == null) { yield break; } for (int i=0;i<graphs.Length;i++) { if (graphs[i] != null && System.Type.Equals (graphs[i].GetType (), type)) { yield return graphs[i]; } } } /** All graphs which implements the UpdateableGraph interface * \code foreach (IUpdatableGraph graph in AstarPath.astarData.GetUpdateableGraphs ()) { * //Do something with the graph * } \endcode * \see AstarPath.RegisterSafeNodeUpdate * \see Pathfinding.IUpdatableGraph */ public IEnumerable GetUpdateableGraphs () { if (graphs == null) { yield break; } for (int i=0;i<graphs.Length;i++) { if (graphs[i] != null && graphs[i] is IUpdatableGraph) { yield return graphs[i]; } } } /** All graphs which implements the UpdateableGraph interface * \code foreach (IRaycastableGraph graph in AstarPath.astarData.GetRaycastableGraphs ()) { * //Do something with the graph * } \endcode * \see Pathfinding.IRaycastableGraph*/ public IEnumerable GetRaycastableGraphs () { if (graphs == null) { yield break; } for (int i=0;i<graphs.Length;i++) { if (graphs[i] != null && graphs[i] is IRaycastableGraph) { yield return graphs[i]; } } } /** Gets the index of the NavGraph in the #graphs array */ public int GetGraphIndex (NavGraph graph) { if (graph == null) throw new System.ArgumentNullException ("graph"); if ( graphs != null ) { for (int i=0;i<graphs.Length;i++) { if (graph == graphs[i]) { return i; } } } Debug.LogError ("Graph doesn't exist"); return -1; } /** Tries to find a graph with the specified GUID in the #graphs array. * If a graph is found it returns its index, otherwise it returns -1 * \see GuidToGraph */ public int GuidToIndex (Guid guid) { if (graphs == null) { return -1; //CollectGraphs (); } for (int i=0;i<graphs.Length;i++) { if (graphs[i] == null) { continue; } if (graphs[i].guid == guid) { return i; } } return -1; } /** Tries to find a graph with the specified GUID in the #graphs array. Returns null if none is found * \see GuidToIndex */ public NavGraph GuidToGraph (Guid guid) { if (graphs == null) { return null; //CollectGraphs (); } for (int i=0;i<graphs.Length;i++) { if (graphs[i] == null) { continue; } if (graphs[i].guid == guid) { return graphs[i]; } } return null; } #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces.Internal; using System.Management.Automation.Remoting.Client; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet establishes a new Runspace either on the local machine or /// on the specified remote machine(s). The runspace established can be used /// to invoke expressions remotely. /// /// The cmdlet can be used in the following ways: /// /// Open a local runspace /// $rs = New-PSSession /// /// Open a runspace to a remote system. /// $rs = New-PSSession -Machine PowerShellWorld /// /// Create a runspace specifying that it is globally scoped. /// $global:rs = New-PSSession -Machine PowerShellWorld /// /// Create a collection of runspaces /// $runspaces = New-PSSession -Machine PowerShellWorld,PowerShellPublish,PowerShellRepo /// /// Create a set of Runspaces using the Secure Socket Layer by specifying the URI form. /// This assumes that an shell by the name of E12 exists on the remote server. /// $serverURIs = 1..8 | %{ "SSL://server${_}:443/E12" } /// $rs = New-PSSession -URI $serverURIs /// /// Create a runspace by connecting to port 8081 on servers s1, s2 and s3 /// $rs = New-PSSession -computername s1,s2,s3 -port 8081 /// /// Create a runspace by connecting to port 443 using ssl on servers s1, s2 and s3 /// $rs = New-PSSession -computername s1,s2,s3 -port 443 -useSSL /// /// Create a runspace by connecting to port 8081 on server s1 and run shell named E12. /// This assumes that a shell by the name E12 exists on the remote server /// $rs = New-PSSession -computername s1 -port 8061 -ShellName E12 /// </summary> /// [Cmdlet(VerbsCommon.New, "PSSession", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135237", RemotingCapability = RemotingCapability.OwnedByCommand)] [OutputType(typeof(PSSession))] public class NewPSSessionCommand : PSRemotingBaseCmdlet, IDisposable { #region Parameters /// <summary> /// This parameter represents the address(es) of the remote /// computer(s). The following formats are supported: /// (a) Computer name /// (b) IPv4 address : 132.3.4.5 /// (c) IPv6 address: 3ffe:8311:ffff:f70f:0:5efe:172.30.162.18 /// /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)] [Alias("Cn")] [ValidateNotNullOrEmpty] public override String[] ComputerName { get; set; } /// <summary> /// Specifies the credentials of the user to impersonate in the /// remote machine. If this parameter is not specified then the /// credentials of the current user process will be assumed. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)] [Credential()] public override PSCredential Credential { get { return base.Credential; } set { base.Credential = value; } } /// <summary> /// The PSSession object describing the remote runspace /// using which the specified cmdlet operation will be performed /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = NewPSSessionCommand.SessionParameterSet)] [ValidateNotNullOrEmpty] public override PSSession[] Session { get { return _remoteRunspaceInfos; } set { _remoteRunspaceInfos = value; } } private PSSession[] _remoteRunspaceInfos; /// <summary> /// Friendly names for the new PSSessions /// </summary> [Parameter()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Name { get; set; } /// <summary> /// When set and in loopback scenario (localhost) this enables creation of WSMan /// host process with the user interactive token, allowing PowerShell script network access, /// i.e., allows going off box. When this property is true and a PSSession is disconnected, /// reconnection is allowed only if reconnecting from a PowerShell session on the same box. /// </summary> [Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)] [Parameter(ParameterSetName = NewPSSessionCommand.SessionParameterSet)] [Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)] public SwitchParameter EnableNetworkAccess { get; set; } /// <summary> /// For WSMan sessions: /// If this parameter is not specified then the value specified in /// the environment variable DEFAULTREMOTESHELLNAME will be used. If /// this is not set as well, then Microsoft.PowerShell is used. /// /// For VM/Container sessions: /// If this parameter is not specified then no configuration is used. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.UriParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.ContainerIdParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.VMIdParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NewPSSessionCommand.VMNameParameterSet)] public String ConfigurationName { get; set; } #endregion Parameters #region Cmdlet Overrides /// <summary> /// The throttle limit will be set here as it needs to be done /// only once per cmdlet and not for every call /// </summary> protected override void BeginProcessing() { base.BeginProcessing(); _operationsComplete.Reset(); _throttleManager.ThrottleLimit = ThrottleLimit; _throttleManager.ThrottleComplete += new EventHandler<EventArgs>(HandleThrottleComplete); if (String.IsNullOrEmpty(ConfigurationName)) { if ((ParameterSetName == NewPSSessionCommand.ComputerNameParameterSet) || (ParameterSetName == NewPSSessionCommand.UriParameterSet)) { // set to default value for WSMan session ConfigurationName = ResolveShell(null); } else { // convert null to String.Empty for VM/Container session ConfigurationName = String.Empty; } } } // BeginProcessing /// <summary> /// The runspace objects will be created using OpenAsync. /// At the end, the method will check if any runspace /// opened has already become available. If so, then it /// will be written to the pipeline /// </summary> protected override void ProcessRecord() { List<RemoteRunspace> remoteRunspaces = null; List<IThrottleOperation> operations = new List<IThrottleOperation>(); switch (ParameterSetName) { case NewPSSessionCommand.SessionParameterSet: { remoteRunspaces = CreateRunspacesWhenRunspaceParameterSpecified(); } break; case "Uri": { remoteRunspaces = CreateRunspacesWhenUriParameterSpecified(); } break; case NewPSSessionCommand.ComputerNameParameterSet: { remoteRunspaces = CreateRunspacesWhenComputerNameParameterSpecified(); } break; case NewPSSessionCommand.VMIdParameterSet: case NewPSSessionCommand.VMNameParameterSet: { remoteRunspaces = CreateRunspacesWhenVMParameterSpecified(); } break; case NewPSSessionCommand.ContainerIdParameterSet: { remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified(); } break; case NewPSSessionCommand.SSHHostParameterSet: { remoteRunspaces = CreateRunspacesForSSHHostParameterSet(); } break; default: { Dbg.Assert(false, "Missing parameter set in switch statement"); remoteRunspaces = new List<RemoteRunspace>(); // added to avoid prefast warning } break; } // switch (ParameterSetName... foreach (RemoteRunspace remoteRunspace in remoteRunspaces) { remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; OpenRunspaceOperation operation = new OpenRunspaceOperation(remoteRunspace); // HandleRunspaceStateChanged callback is added before ThrottleManager complete // callback handlers so HandleRunspaceStateChanged will always be called first. operation.OperationComplete += new EventHandler<OperationStateEventArgs>(HandleRunspaceStateChanged); remoteRunspace.URIRedirectionReported += HandleURIDirectionReported; operations.Add(operation); } // submit list of operations to throttle manager to start opening // runspaces _throttleManager.SubmitOperations(operations); // Add to list for clean up. _allOperations.Add(operations); // If there are any runspaces opened asynchronously // that are ready now, check their status and do // necessary action. If there are any error records // or verbose messages write them as well Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action<Cmdlet>)streamObject); } // foreach }// ProcessRecord() /// <summary> /// OpenAsync would have been called from ProcessRecord. This method /// will wait until all runspaces are opened and then write them to /// the pipeline as and when they become available. /// </summary> protected override void EndProcessing() { // signal to throttle manager end of submit operations _throttleManager.EndSubmitOperations(); while (true) { // Keep reading objects until end of pipeline is encountered _stream.ObjectReader.WaitHandle.WaitOne(); if (!_stream.ObjectReader.EndOfPipeline) { Object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action<Cmdlet>)streamObject); } else { break; } } // while ... }// EndProcessing() /// <summary> /// This method is called when the user sends a stop signal to the /// cmdlet. The cmdlet will not exit until it has completed /// creating all the runspaces (basically the runspaces its /// waiting on OpenAsync is made available). However, when a stop /// signal is sent, CloseAsyn needs to be called to close all the /// pending runspaces /// </summary> /// <remarks>This is called from a separate thread so need to worry /// about concurrency issues /// </remarks> protected override void StopProcessing() { // close the outputStream so that further writes to the outputStream // are not possible _stream.ObjectWriter.Close(); // for all the runspaces that have been submitted for opening // call StopOperation on each object and quit _throttleManager.StopAllOperations(); }// StopProcessing() #endregion Cmdlet Overrides #region IDisposable Overrides /// <summary> /// Dispose method of IDisposable. Gets called in the following cases: /// 1. Pipeline explicitly calls dispose on cmdlets /// 2. Called by the garbage collector /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion IDisposable Overrides #region Private Methods /// <summary> /// Adds forwarded events to the local queue /// </summary> private void OnRunspacePSEventReceived(object sender, PSEventArgs e) { if (this.Events != null) this.Events.AddForwardedEvent(e); } /// <summary> /// When the client remote session reports a URI redirection, this method will report the /// message to the user as a Warning using Host method calls. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs) { string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString); Action<Cmdlet> warningWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteWarning(message); }; _stream.Write(warningWriter); } /// <summary> /// Handles state changes for Runspace /// </summary> /// <param name="sender">Sender of this event</param> /// <param name="stateEventArgs">Event information object which describes /// the event which triggered this method</param> private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { if (sender == null) { throw PSTraceSource.NewArgumentNullException("sender"); } if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException("stateEventArgs"); } RunspaceStateEventArgs runspaceStateEventArgs = stateEventArgs.BaseEvent as RunspaceStateEventArgs; RunspaceStateInfo stateInfo = runspaceStateEventArgs.RunspaceStateInfo; RunspaceState state = stateInfo.State; OpenRunspaceOperation operation = sender as OpenRunspaceOperation; RemoteRunspace remoteRunspace = operation.OperatedRunspace; // since we got state changed event..we dont need to listen on // URI redirections anymore if (null != remoteRunspace) { remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported; } PipelineWriter writer = _stream.ObjectWriter; Exception reason = runspaceStateEventArgs.RunspaceStateInfo.Reason; switch (state) { case RunspaceState.Opened: { // Indicates that runspace is successfully opened // Write it to PipelineWriter to be handled in // HandleRemoteRunspace PSSession remoteRunspaceInfo = new PSSession(remoteRunspace); this.RunspaceRepository.Add(remoteRunspaceInfo); Action<Cmdlet> outputWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteObject(remoteRunspaceInfo); }; if (writer.IsOpen) { writer.Write(outputWriter); } } break; case RunspaceState.Broken: { // Open resulted in a broken state. Extract reason // and write an error record // set the transport message in the error detail so that // the user can directly get to see the message without // having to mine through the error record details PSRemotingTransportException transException = reason as PSRemotingTransportException; String errorDetails = null; int transErrorCode = 0; if (transException != null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; transErrorCode = transException.ErrorCode; if (senderAsOp != null) { String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; if (transException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) { // Handling a special case for redirection..we should talk about // AllowRedirection parameter and WSManMaxRedirectionCount preference // variables string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.URIRedirectionReported, transException.Message, "MaximumConnectionRedirectionCount", Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, "AllowRedirection"); errorDetails = "[" + host + "] " + message; } else { errorDetails = "[" + host + "] "; if (!String.IsNullOrEmpty(transException.Message)) { errorDetails += transException.Message; } else if (!String.IsNullOrEmpty(transException.TransportMessage)) { errorDetails += transException.TransportMessage; } } } } // add host identification information in data structure handler message PSRemotingDataStructureException protoException = reason as PSRemotingDataStructureException; if (protoException != null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; if (senderAsOp != null) { String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; errorDetails = "[" + host + "] " + protoException.Message; } } if (reason == null) { reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); } string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError( transErrorCode, _defaultFQEID); if (WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST == transErrorCode) { errorDetails += System.Environment.NewLine + String.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist); } ErrorRecord errorRecord = new ErrorRecord(reason, remoteRunspace, fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { // // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // if ((errorRecord.Exception != null) && (errorRecord.Exception.InnerException != null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; if (ex != null) { errorRecord = new ErrorRecord(errorRecord.Exception.InnerException, errorRecord.FullyQualifiedErrorId, errorRecord.CategoryInfo.Category, errorRecord.TargetObject); } } cmdlet.WriteError(errorRecord); }; if (writer.IsOpen) { writer.Write(errorWriter); } _toDispose.Add(remoteRunspace); } break; case RunspaceState.Closed: { // The runspace was closed possibly because the user // hit ctrl-C when runspaces were being opened or Dispose has been // called when there are open runspaces Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo, "ConnectionUri", null); String message = GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, (connectionUri != null) ? connectionUri.AbsoluteUri : string.Empty); Action<Cmdlet> verboseWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteVerbose(message); }; if (writer.IsOpen) { writer.Write(verboseWriter); } // runspace may not have been opened in certain cases // like when the max memory is set to 25MB, in such // cases write an error record if (reason != null) { ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, remoteRunspace); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; if (writer.IsOpen) { writer.Write(errorWriter); } } } break; }// switch } // HandleRunspaceStateChanged /// <summary> /// Creates the remote runspace objects when PSSession /// parameter is specified /// It now supports PSSession based on VM/container connection info as well. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] private List<RemoteRunspace> CreateRunspacesWhenRunspaceParameterSpecified() { List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>(); // validate the runspaces specified before processing them. // The function will result in terminating errors, if any // validation failure is encountered ValidateRemoteRunspacesSpecified(); int rsIndex = 0; foreach (PSSession remoteRunspaceInfo in _remoteRunspaceInfos) { if (remoteRunspaceInfo == null || remoteRunspaceInfo.Runspace == null) { ThrowTerminatingError(new ErrorRecord( new ArgumentNullException("PSSession"), "PSSessionArgumentNull", ErrorCategory.InvalidArgument, null)); } else { // clone the object based on what's specified in the input parameter try { RemoteRunspace remoteRunspace = (RemoteRunspace)remoteRunspaceInfo.Runspace; RunspaceConnectionInfo newConnectionInfo = null; if (remoteRunspace.ConnectionInfo is VMConnectionInfo) { newConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy(); } else if (remoteRunspace.ConnectionInfo is ContainerConnectionInfo) { ContainerConnectionInfo newContainerConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy() as ContainerConnectionInfo; newContainerConnectionInfo.CreateContainerProcess(); newConnectionInfo = newContainerConnectionInfo; } else { // WSMan case WSManConnectionInfo originalWSManConnectionInfo = remoteRunspace.ConnectionInfo as WSManConnectionInfo; WSManConnectionInfo newWSManConnectionInfo = null; if (null != originalWSManConnectionInfo) { newWSManConnectionInfo = originalWSManConnectionInfo.Copy(); newWSManConnectionInfo.EnableNetworkAccess = (newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess) ? true : false; newConnectionInfo = newWSManConnectionInfo; } else { Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo, "ConnectionUri", null); string shellUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<string>(remoteRunspace.ConnectionInfo, "ShellUri", string.Empty); newWSManConnectionInfo = new WSManConnectionInfo(connectionUri, shellUri, remoteRunspace.ConnectionInfo.Credential); UpdateConnectionInfo(newWSManConnectionInfo); newWSManConnectionInfo.EnableNetworkAccess = EnableNetworkAccess; newConnectionInfo = newWSManConnectionInfo; } } RemoteRunspacePoolInternal rrsPool = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal; TypeTable typeTable = null; if ((rrsPool != null) && (rrsPool.DataStructureHandler != null) && (rrsPool.DataStructureHandler.TransportManager != null)) { typeTable = rrsPool.DataStructureHandler.TransportManager.Fragmentor.TypeTable; } // Create new remote runspace with name and Id. int rsId; string rsName = GetRunspaceName(rsIndex, out rsId); RemoteRunspace newRemoteRunspace = new RemoteRunspace( typeTable, newConnectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); remoteRunspaces.Add(newRemoteRunspace); } catch (UriFormatException e) { PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, remoteRunspaceInfo); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; writer.Write(errorWriter); } } ++rsIndex; } // foreach return remoteRunspaces; } // CreateRunspacesWhenRunspaceParameterSpecified /// <summary> /// Creates the remote runspace objects when the URI parameter /// is specified /// </summary> private List<RemoteRunspace> CreateRunspacesWhenUriParameterSpecified() { List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>(); // parse the Uri to obtain information about the runspace // required for (int i = 0; i < ConnectionUri.Length; i++) { try { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = ConnectionUri[i]; connectionInfo.ShellUri = ConfigurationName; if (CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } else { connectionInfo.Credential = Credential; } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = EnableNetworkAccess; // Create new remote runspace with name and Id. int rsId; string rsName = GetRunspaceName(i, out rsId); RemoteRunspace remoteRunspace = new RemoteRunspace( Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); Dbg.Assert(remoteRunspace != null, "RemoteRunspace object created using URI is null"); remoteRunspaces.Add(remoteRunspace); } catch (UriFormatException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]); } catch (InvalidOperationException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]); } catch (ArgumentException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]); } catch (NotSupportedException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]); } } // for... return remoteRunspaces; } // CreateRunspacesWhenUriParameterSpecified /// <summary> /// Creates the remote runspace objects when the ComputerName parameter /// is specified /// </summary> private List<RemoteRunspace> CreateRunspacesWhenComputerNameParameterSpecified() { List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>(); // Resolve all the machine names String[] resolvedComputerNames; ResolveComputerNames(ComputerName, out resolvedComputerNames); ValidateComputerName(resolvedComputerNames); // Do for each machine for (int i = 0; i < resolvedComputerNames.Length; i++) { try { WSManConnectionInfo connectionInfo = null; connectionInfo = new WSManConnectionInfo(); string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme; connectionInfo.ComputerName = resolvedComputerNames[i]; connectionInfo.Port = Port; connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Scheme = scheme; if (CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } else { connectionInfo.Credential = Credential; } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = EnableNetworkAccess; // Create new remote runspace with name and Id. int rsId; string rsName = GetRunspaceName(i, out rsId); RemoteRunspace runspace = new RemoteRunspace( Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); remoteRunspaces.Add(runspace); } catch (UriFormatException e) { PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, resolvedComputerNames[i]); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; writer.Write(errorWriter); } }// end of for return remoteRunspaces; }// CreateRunspacesWhenComputerNameParameterSpecified /// <summary> /// Creates the remote runspace objects when the VMId or VMName parameter /// is specified /// </summary> private List<RemoteRunspace> CreateRunspacesWhenVMParameterSpecified() { int inputArraySize; bool isVMIdSet = false; int index; string command; Collection<PSObject> results; List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>(); if (ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) { isVMIdSet = true; inputArraySize = this.VMId.Length; this.VMName = new string[inputArraySize]; command = "Get-VM -Id $args[0]"; } else { Dbg.Assert((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet), "Expected ParameterSetName == VMId or VMName"); inputArraySize = this.VMName.Length; this.VMId = new Guid[inputArraySize]; command = "Get-VM -Name $args"; } for (index = 0; index < inputArraySize; index++) { try { results = this.InvokeCommand.InvokeScript( command, false, PipelineResultTypes.None, null, isVMIdSet ? this.VMId[index].ToString() : this.VMName[index]); } catch (CommandNotFoundException) { ThrowTerminatingError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), ErrorCategory.NotInstalled, null)); return null; } // handle invalid input if (results.Count != 1) { if (isVMIdSet) { this.VMName[index] = string.Empty; WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, this.VMId[index].ToString(null))), PSRemotingErrorId.InvalidVMIdNotSingle.ToString(), ErrorCategory.InvalidArgument, null)); continue; } else { this.VMId[index] = Guid.Empty; WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, this.VMName[index])), PSRemotingErrorId.InvalidVMNameNotSingle.ToString(), ErrorCategory.InvalidArgument, null)); continue; } } else { this.VMId[index] = (Guid)results[0].Properties["VMId"].Value; this.VMName[index] = (string)results[0].Properties["VMName"].Value; // // VM should be in running state. // if ((VMState)results[0].Properties["State"].Value != VMState.Running) { WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName[index])), PSRemotingErrorId.InvalidVMState.ToString(), ErrorCategory.InvalidArgument, null)); continue; } } // create helper objects for VM GUIDs or names RemoteRunspace runspace = null; VMConnectionInfo connectionInfo; int rsId; string rsName = GetRunspaceName(index, out rsId); try { connectionInfo = new VMConnectionInfo(this.Credential, this.VMId[index], this.VMName[index], this.ConfigurationName); runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, rsName, rsId); remoteRunspaces.Add(runspace); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); } } ResolvedComputerNames = this.VMName; return remoteRunspaces; }// CreateRunspacesWhenVMParameterSpecified /// <summary> /// Creates the remote runspace objects when the ContainerId parameter is specified /// </summary> private List<RemoteRunspace> CreateRunspacesWhenContainerParameterSpecified() { int index = 0; List<string> resolvedNameList = new List<string>(); List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>(); Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet), "Expected ParameterSetName == ContainerId"); foreach (var input in ContainerId) { // // Create helper objects for container ID or name. // RemoteRunspace runspace = null; ContainerConnectionInfo connectionInfo = null; int rsId; string rsName = GetRunspaceName(index, out rsId); index++; try { // // Hyper-V container uses Hype-V socket as transport. // Windows Server container uses named pipe as transport. // connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName); resolvedNameList.Add(connectionInfo.ComputerName); connectionInfo.CreateContainerProcess(); runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, rsName, rsId); remoteRunspaces.Add(runspace); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); continue; } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); continue; } catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); continue; } } ResolvedComputerNames = resolvedNameList.ToArray(); return remoteRunspaces; }// CreateRunspacesWhenContainerParameterSpecified /// <summary> /// CreateRunspacesForSSHHostParameterSet /// </summary> /// <returns></returns> private List<RemoteRunspace> CreateRunspacesForSSHHostParameterSet() { var remoteRunspaces = new List<RemoteRunspace>(); var sshConnectionInfo = new SSHConnectionInfo( this.UserName, this.HostName, this.KeyPath); var typeTable = TypeTable.LoadDefaultTypeFiles(); remoteRunspaces.Add(RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace); return remoteRunspaces; } /// <summary> /// Helper method to either get a user supplied runspace/session name /// or to generate one along with a unique Id. /// </summary> /// <param name="rsIndex">Runspace name array index.</param> /// <param name="rsId">Runspace Id.</param> /// <returns>Runspace name.</returns> private string GetRunspaceName(int rsIndex, out int rsId) { // Get a unique session/runspace Id and default Name. string rsName = PSSession.GenerateRunspaceName(out rsId); // If there is a friendly name for the runspace, we need to pass it to the // runspace pool object, which in turn passes it on to the server during // construction. This way the friendly name can be returned when querying // the sever for disconnected sessions/runspaces. if (Name != null && rsIndex < Name.Length) { rsName = Name[rsIndex]; } return rsName; } /// <summary> /// Internal dispose method which does the actual /// dispose operations and finalize suppressions /// </summary> /// <param name="disposing">Whether method is called /// from Dispose or destructor</param> protected void Dispose(bool disposing) { if (disposing) { _throttleManager.Dispose(); // wait for all runspace operations to be complete _operationsComplete.WaitOne(); _operationsComplete.Dispose(); _throttleManager.ThrottleComplete -= new EventHandler<EventArgs>(HandleThrottleComplete); _throttleManager = null; foreach (RemoteRunspace remoteRunspace in _toDispose) { remoteRunspace.Dispose(); } // Dispose all open operation objects, to remove runspace event callback. foreach (List<IThrottleOperation> operationList in _allOperations) { foreach (OpenRunspaceOperation operation in operationList) { operation.Dispose(); } } _stream.Dispose(); } } // Dispose /// <summary> /// Handles the throttling complete event of the throttle manager /// </summary> /// <param name="sender">sender of this event</param> /// <param name="eventArgs"></param> private void HandleThrottleComplete(object sender, EventArgs eventArgs) { // all operations are complete close the stream _stream.ObjectWriter.Close(); _operationsComplete.Set(); } // HandleThrottleComplete /// <summary> /// Writes an error record specifying that creation of remote runspace /// failed /// </summary> /// <param name="e">exception which is causing this error record /// to be written</param> /// <param name="uri">Uri which caused this exception</param> private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri) { Dbg.Assert(e is UriFormatException || e is InvalidOperationException || e is ArgumentException || e is NotSupportedException, "Exception has to be of type UriFormatException or InvalidOperationException or ArgumentException or NotSupportedException"); PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, uri); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; writer.Write(errorWriter); } // WriteErrorCreateRemoteRunspaceFailed #endregion Private Methods #region Private Members private ThrottleManager _throttleManager = new ThrottleManager(); private ObjectStream _stream = new ObjectStream(); // event that signals that all operations are // complete (including closing if any) private ManualResetEvent _operationsComplete = new ManualResetEvent(true); // the initial state is true because when no // operations actually take place as in case of a // parameter binding exception, then Dispose is // called. Since Dispose waits on this handler // it is set to true initially and is Reset() in // BeginProcessing() // list of runspaces to dispose private List<RemoteRunspace> _toDispose = new List<RemoteRunspace>(); // List of runspace connect operations. Need to keep for cleanup. private Collection<List<IThrottleOperation>> _allOperations = new Collection<List<IThrottleOperation>>(); // Default FQEID. private string _defaultFQEID = "PSSessionOpenFailed"; #endregion Private Members }// NewRunspace #region Helper Classes /// <summary> /// Class that implements the IThrottleOperation in turn wrapping the /// opening of a runspace asynchronously within it /// </summary> internal class OpenRunspaceOperation : IThrottleOperation, IDisposable { // Member variables to ensure that the ThrottleManager gets StartComplete // or StopComplete called only once per Start or Stop operation. private bool _startComplete; private bool _stopComplete; private object _syncObject = new object(); internal RemoteRunspace OperatedRunspace { get; } internal OpenRunspaceOperation(RemoteRunspace runspace) { _startComplete = true; _stopComplete = true; OperatedRunspace = runspace; OperatedRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(HandleRunspaceStateChanged); } /// <summary> /// Opens the runspace asynchronously /// </summary> internal override void StartOperation() { lock (_syncObject) { _startComplete = false; } OperatedRunspace.OpenAsync(); } // StartOperation /// <summary> /// Closes the runspace already opened asynchronously /// </summary> internal override void StopOperation() { OperationStateEventArgs operationStateEventArgs = null; lock (_syncObject) { // Ignore stop operation if start operation has completed. if (_startComplete) { _stopComplete = true; _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = new RunspaceStateEventArgs(OperatedRunspace.RunspaceStateInfo); operationStateEventArgs.OperationState = OperationState.StopComplete; } else { _stopComplete = false; } } if (operationStateEventArgs != null) { FireEvent(operationStateEventArgs); } else { OperatedRunspace.CloseAsync(); } } // OperationComplete event handler uses an internal collection of event handler // callbacks for two reasons: // a) To ensure callbacks are made in list order (first added, first called). // b) To ensure all callbacks are fired by manually invoking callbacks and handling // any exceptions thrown on this thread. (ThrottleManager will hang if it doesn't // get a start/stop complete callback). private List<EventHandler<OperationStateEventArgs>> _internalCallbacks = new List<EventHandler<OperationStateEventArgs>>(); internal override event EventHandler<OperationStateEventArgs> OperationComplete { add { lock (_internalCallbacks) { _internalCallbacks.Add(value); } } remove { lock (_internalCallbacks) { _internalCallbacks.Remove(value); } } } /// <summary> /// Handler for handling runspace state changed events. This method will be /// registered in the StartOperation and StopOperation methods. This handler /// will in turn invoke the OperationComplete event for all events that are /// necessary - Opened, Closed, Disconnected, Broken. It will ignore all other state /// changes. /// </summary> /// <remarks> /// There are two problems that need to be handled. /// 1) We need to make sure that the ThrottleManager StartComplete and StopComplete /// operation events are called or the ThrottleManager will never end (hang). /// 2) The HandleRunspaceStateChanged event handler remains in the Runspace /// StateChanged event call chain until this object is disposed. We have to /// disallow the HandleRunspaceStateChanged event from running and throwing /// an exception since this prevents other event handlers in the chain from /// being called. /// </remarks> /// <param name="source">Source of this event</param> /// <param name="stateEventArgs">object describing state information of the /// runspace</param> private void HandleRunspaceStateChanged(object source, RunspaceStateEventArgs stateEventArgs) { // Disregard intermediate states. switch (stateEventArgs.RunspaceStateInfo.State) { case RunspaceState.Opening: case RunspaceState.BeforeOpen: case RunspaceState.Closing: return; } OperationStateEventArgs operationStateEventArgs = null; lock (_syncObject) { // We must call OperationComplete ony *once* for each Start/Stop operation. if (!_stopComplete) { // Note that the StopComplete callback removes *both* the Start and Stop // operations from their respective queues. So update the member vars // accordingly. _stopComplete = true; _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StopComplete; } else if (!_startComplete) { _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StartComplete; } } if (operationStateEventArgs != null) { // Fire callbacks in list order. FireEvent(operationStateEventArgs); } } private void FireEvent(OperationStateEventArgs operationStateEventArgs) { EventHandler<OperationStateEventArgs>[] copyCallbacks; lock (_internalCallbacks) { copyCallbacks = new EventHandler<OperationStateEventArgs>[_internalCallbacks.Count]; _internalCallbacks.CopyTo(copyCallbacks); } foreach (var callbackDelegate in copyCallbacks) { // Ensure all callbacks get called to prevent ThrottleManager hang. try { callbackDelegate.SafeInvoke(this, operationStateEventArgs); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } } } /// <summary> /// Implements IDisposable. /// </summary> public void Dispose() { // Must remove the event callback from the new runspace or it will block other event // handling by throwing an exception on the event thread. OperatedRunspace.StateChanged -= HandleRunspaceStateChanged; GC.SuppressFinalize(this); } } // OpenRunspaceOperation #endregion Helper Classes }//End namespace
// 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 CompareEqualByte() { var test = new SimpleBinaryOpTest__CompareEqualByte(); 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__CompareEqualByte { 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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualByte testClass) { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqualByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__CompareEqualByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.CompareEqual( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_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.CompareEqual( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_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.CompareEqual( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_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.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(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((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(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((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqualByte(); var result = Sse2.CompareEqual(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__CompareEqualByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(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.CompareEqual(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.CompareEqual( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] == right[0]) ? unchecked((byte)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((byte)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; using System; namespace System { public struct DateTime { public static DateTime Now { get; } public DayOfWeek DayOfWeek { get; } public int Second { get; } public static DateTime UtcNow { get; } public DateTime Date { get; } public int Hour { get; } public static DateTime Today { get; } public int Day { get; } public int Millisecond { get; } public int DayOfYear { get; } public int Year { get; } public int Minute { get; } public int Month { get; } public Int64 Ticks { get; } public TimeSpan TimeOfDay { get; } public TypeCode GetTypeCode () { return default(TypeCode); } public String[] GetDateTimeFormats (Char format, IFormatProvider provider) { return default(String[]); } public String[] GetDateTimeFormats (Char format) { return default(String[]); } public String[] GetDateTimeFormats (IFormatProvider provider) { return default(String[]); } public String[] GetDateTimeFormats () { return default(String[]); } public static bool operator >= (DateTime t1, DateTime t2) { return default(bool); } public static bool operator > (DateTime t1, DateTime t2) { return default(bool); } public static bool operator <= (DateTime t1, DateTime t2) { return default(bool); } public static bool operator < (DateTime t1, DateTime t2) { return default(bool); } public static bool operator != (DateTime d1, DateTime d2) { return default(bool); } public static bool operator == (DateTime d1, DateTime d2) { return default(bool); } public static TimeSpan operator - (DateTime d1, DateTime d2) { return default(TimeSpan); } public static DateTime operator - (DateTime d, TimeSpan t) { return default(DateTime); } public static DateTime operator + (DateTime d, TimeSpan t) { return default(DateTime); } public DateTime ToUniversalTime () { return default(DateTime); } public string ToString (string format, IFormatProvider provider) { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToString (IFormatProvider provider) { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToString (string format) { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToShortTimeString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToShortDateString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToLongTimeString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public string ToLongDateString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public DateTime ToLocalTime () { return default(DateTime); } public Int64 ToFileTimeUtc () { return default(Int64); } public Int64 ToFileTime () { return default(Int64); } public double ToOADate () { return default(double); } public DateTime Subtract (TimeSpan value) { return default(DateTime); } public TimeSpan Subtract (DateTime value) { return default(TimeSpan); } public static DateTime ParseExact (string s, String[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style) { return default(DateTime); } public static DateTime ParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style) { return default(DateTime); } public static DateTime ParseExact (string s, string format, IFormatProvider provider) { return default(DateTime); } public static DateTime Parse (string s, IFormatProvider provider, System.Globalization.DateTimeStyles styles) { return default(DateTime); } public static DateTime Parse (string s, IFormatProvider provider) { return default(DateTime); } public static DateTime Parse (string s) { return default(DateTime); } public static bool IsLeapYear (int year) { return default(bool); } public int GetHashCode () { return default(int); } public static DateTime FromOADate (double d) { return default(DateTime); } public static DateTime FromFileTimeUtc (Int64 fileTime) { CodeContract.Requires(fileTime >= 0); return default(DateTime); } public static DateTime FromFileTime (Int64 fileTime) { return default(DateTime); } public static bool Equals (DateTime t1, DateTime t2) { return default(bool); } public bool Equals (object value) { return default(bool); } public static int DaysInMonth (int year, int month) { CodeContract.Requires(month >= 1); CodeContract.Requires(month <= 12); return default(int); } public int CompareTo (object value) { return default(int); } public static int Compare (DateTime t1, DateTime t2) { return default(int); } public DateTime AddYears (int value) { return default(DateTime); } public DateTime AddTicks (Int64 value) { return default(DateTime); } public DateTime AddSeconds (double value) { return default(DateTime); } public DateTime AddMonths (int months) { CodeContract.Requires(months >= -120000); CodeContract.Requires(months <= 120000); return default(DateTime); } public DateTime AddMinutes (double value) { return default(DateTime); } public DateTime AddMilliseconds (double value) { return default(DateTime); } public DateTime AddHours (double value) { return default(DateTime); } public DateTime AddDays (double value) { return default(DateTime); } public DateTime Add (TimeSpan value) { return default(DateTime); } public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar! calendar) { CodeContract.Requires(calendar != null); CodeContract.Requires(millisecond >= 0); CodeContract.Requires(millisecond < 1000); return default(DateTime); } public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond) { CodeContract.Requires(millisecond >= 0); CodeContract.Requires(millisecond < 1000); return default(DateTime); } public DateTime (int year, int month, int day, int hour, int minute, int second, System.Globalization.Calendar! calendar) { CodeContract.Requires(calendar != null); return default(DateTime); } public DateTime (int year, int month, int day, int hour, int minute, int second) { return default(DateTime); } public DateTime (int year, int month, int day, System.Globalization.Calendar calendar) { return default(DateTime); } public DateTime (int year, int month, int day) { return default(DateTime); } public DateTime (Int64 ticks) { CodeContract.Requires(ticks >= 0); CodeContract.Requires(ticks <= 4097261567); return default(DateTime); } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Debugging; using FlatRedBall.Forms.Controls; namespace LadderDemo.Entities { public partial class Player { AnimationController animationController; public IPressableInput RunInput { get; set; } public bool PressedUp => InputDevice.DefaultUpPressable.WasJustPressed; public AxisAlignedRectangle LastCollisionLadderRectange { get; set; } public void SetIndex(int index) { switch(index) { case 0: SpriteInstance.AnimationChains = PlatformerAnimations; break; case 1: SpriteInstance.AnimationChains = p2animations; break; case 2: SpriteInstance.AnimationChains = p3animations; break; case 3: SpriteInstance.AnimationChains = p4animations; break; } } private void CustomInitialize() { animationController = new AnimationController(SpriteInstance); var idleLayer = new AnimationLayer(); idleLayer.EveryFrameAction = () => { return "CharacterIdle" + DirectionFacing; }; animationController.Layers.Add(idleLayer); var lookUpLayer = new AnimationLayer(); lookUpLayer.EveryFrameAction = () => { if (this.VerticalInput.Value > 0) { return "CharacterLookUp" + DirectionFacing; } return null; }; animationController.Layers.Add(lookUpLayer); var walkLayer = new AnimationLayer(); walkLayer.EveryFrameAction = () => { if (this.Velocity.X != 0) { return "CharacterWalk" + DirectionFacing; } return null; }; animationController.Layers.Add(walkLayer); var runLayer = new AnimationLayer(); runLayer.EveryFrameAction = () => { if (this.XVelocity != 0 && RunInput.IsDown) { return "CharacterRun" + DirectionFacing; } return null; }; animationController.Layers.Add(runLayer); var skidLayer = new AnimationLayer(); skidLayer.EveryFrameAction = () => { if (this.XVelocity != 0 && this.HorizontalInput.Value != 0 && Math.Sign(XVelocity) != Math.Sign(this.HorizontalInput.Value) && this.RunInput.IsDown) { return "CharacterSkid" + DirectionFacing; } return null; }; animationController.Layers.Add(skidLayer); var duckLayer = new AnimationLayer(); duckLayer.EveryFrameAction = () => { if (this.VerticalInput.Value < 0) { return "CharacterDuck" + DirectionFacing; } return null; }; animationController.Layers.Add(duckLayer); var fallLayer = new AnimationLayer(); fallLayer.EveryFrameAction = () => { if (this.IsOnGround == false) { return "CharacterFall" + DirectionFacing; } return null; }; animationController.Layers.Add(fallLayer); var jumpLayer = new AnimationLayer(); jumpLayer.EveryFrameAction = () => { if (this.IsOnGround == false && YVelocity > 0) { return "CharacterJump" + DirectionFacing; } return null; }; animationController.Layers.Add(jumpLayer); var runJump = new AnimationLayer(); runJump.EveryFrameAction = () => { if (this.IsOnGround == false && RunInput.IsDown) { return "CharacterRunJump" + DirectionFacing; } return null; }; animationController.Layers.Add(runJump); var climb = new AnimationLayer(); climb.EveryFrameAction = () => { if (this.CurrentMovement.CanClimb) { if(this.YVelocity == 0) { return "CharacterClimbRearIdle"; } else { return "CharacterClimbRear"; } } return null; }; animationController.Layers.Add(climb); } partial void CustomInitializePlatformerInput() { if(InputDevice is Keyboard asKeyboard) { RunInput = asKeyboard.GetKey(Microsoft.Xna.Framework.Input.Keys.R); } else if(InputDevice is Xbox360GamePad asGamepad) { RunInput = asGamepad.GetButton(Xbox360GamePad.Button.X); } } private void CustomActivity() { animationController.Activity(); if(!CurrentMovement.CanClimb) { if (VerticalInput.Value < 0) { this.GroundMovement = PlatformerValuesStatic["Ducking"]; } else if (RunInput.IsDown) { this.GroundMovement = PlatformerValuesStatic["Running"]; this.AirMovement = PlatformerValuesStatic["RunningAir"]; } else { this.GroundMovement = PlatformerValuesStatic["Ground"]; this.AirMovement = PlatformerValuesStatic["Air"]; } } else { if(VerticalInput.Value < 0 && IsOnGround) { this.GroundMovement = PlatformerValuesStatic["Ground"]; } } // Even if we are colliding with it, we want to see if the player's "body" is over // the ladder. We can do this by checking the center. var isOverLadder = LastCollisionLadderRectange != null && X < LastCollisionLadderRectange.Right && X > LastCollisionLadderRectange.Left; if (InputDevice.DefaultUpPressable.WasJustPressed && LastCollisionLadderRectange != null) { this.GroundMovement = PlatformerValuesStatic["Climbing"]; // snap the player's position to the center of the ladder this.X = LastCollisionLadderRectange.X; this.XVelocity = 0; if(this.IsOnGround == false) { // force the player on ground: CurrentMovementType = MovementType.Ground; } } if(isOverLadder == false && CurrentMovement.CanClimb) { // fall off the ladder... CurrentMovementType = MovementType.Air; } } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Test.Azure.Management.Logic { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Microsoft.Azure.Management.Logic; using Microsoft.Azure.Management.Logic.Models; using Microsoft.Rest; using Microsoft.Rest.Azure; using Xunit; public class WorkflowsInMemoryTests : BaseInMemoryTests { #region Constructor private StringContent Workflow { get; set; } private StringContent WorkflowRun { get; set; } private StringContent WorkflowList { get; set; } public WorkflowsInMemoryTests() { var workflow = @"{ 'id': '/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName', 'name': 'wfName', 'type':'Microsoft.Logic/workflows', 'location':'westus', 'properties': { 'createdTime': '2015-06-23T21:47:00.0000001Z', 'changedTime':'2015-06-23T21:47:30.0000002Z', 'state':'Enabled', 'version':'08587717906782501130', 'accessEndpoint':'https://westus.logic.azure.com/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName', 'sku':{ 'name':'Premium', 'plan':{ 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Web/serverFarms/planName', 'type':'Microsoft.Web/serverFarms', 'name':'planName' } }, 'definition':{ '$schema':'http://schema.management.azure.com/providers/Microsoft.Logic/schemas/2014-12-01-preview/workflowdefinition.json#', 'contentVersion':'1.0.0.0', 'parameters':{ 'runworkflowmanually':{ 'defaultValue':true, 'type':'Bool' }, 'subscription':{ 'defaultValue':'66666666-6666-6666-6666-666666666666', 'type':'String' }, 'resourceGroup':{ 'defaultValue':'logicapps-e2e', 'type':'String' }, 'authentication':{ 'defaultValue':{ 'type':'ActiveDirectoryOAuth', 'audience':'https://management.azure.com/', 'tenant':'66666666-6666-6666-6666-666666666666', 'clientId':'66666666-6666-6666-6666-666666666666', 'secret':'<placeholder>' }, 'type':'Object' } }, 'triggers':{ }, 'actions':{ 'listWorkflows':{ 'type':'Http', 'inputs':{ 'method':'GET', 'uri':'someUri', 'authentication':'@parameters(""authentication"")' }, 'conditions':[ ] } }, 'outputs':{ } }, 'parameters':{ 'parameter1':{ 'type': 'string', 'value': 'abc' }, 'parameter2':{ 'type': 'array', 'value': [1, 2, 3] } } } }"; var run = @"{ 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/runs/run87646872399558047', 'name':'run87646872399558047', 'type':'Microsoft.Logic/workflows/runs', 'properties':{ 'startTime':'2015-06-23T21:47:00.0000000Z', 'endTime':'2015-06-23T21:47:30.1300000Z', 'status':'Succeeded', 'correlationId':'a04da054-a1ae-409d-80ff-b09febefc357', 'workflow':{ 'name':'wfName/ver87717906782501130', 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/versions/ver87717906782501130', 'type':'Microsoft.Logic/workflows/versions' }, 'trigger':{ 'name':'6A65DA9E-CFF8-4D3E-B5FB-691739C7AD61' }, 'outputs':{ } } }"; var workflowListFormat = @"{{ 'value':[ {0} ], 'nextLink': 'http://workflowlist1nextlink' }}"; this.Workflow = new StringContent(workflow); this.WorkflowRun = new StringContent(run); this.WorkflowList = new StringContent(string.Format(workflowListFormat, workflow)); } #endregion #region Workflows_ListBySubscription [Fact] public void Workflows_ListBySubscription_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<CloudException>(() => client.Workflows.ListBySubscription()); } public void Workflows_ListBySubscription_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroup("rgName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListBySubscriptionNext [Fact] public void Workflows_ListBySubscriptionNext_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListBySubscriptionNext(null)); Assert.Throws<CloudException>(() => client.Workflows.ListBySubscriptionNext("http://management.azure.com/nextLink")); } public void Workflows_ListBySubscriptionNext_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListBySubscriptionNext("http://management.azure.com/nextLink"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListByResourceGroup [Fact] public void Workflows_ListByResourceGroup_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListByResourceGroup(null)); Assert.Throws<CloudException>(() => client.Workflows.ListByResourceGroup("rgName")); } [Fact] public void Workflows_ListByResourceGroup_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroup("rgName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListByResourceGroupNext [Fact] public void Workflows_ListByResourceGroupNext_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListByResourceGroupNext(null)); Assert.Throws<CloudException>(() => client.Workflows.ListByResourceGroupNext("http://management.azure.com/nextLink")); } public void Workflows_ListByResourceGroupNext_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroupNext("http://management.azure.com/nextLink"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_CreateOrUpdate [Fact] public void Workflows_CreateOrUpdate_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate(null, "wfName", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate("rgName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow())); } [Fact] public void Workflows_CreateOrUpdate_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var workflow = client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow()); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Put); // Validates result. this.ValidateWorkflow1(workflow); } [Fact] public void Workflows_CreateOrUpdate_Created() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created, Content = this.Workflow }; var workflow = client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow()); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Put); // Validates result. this.ValidateWorkflow1(workflow); } #endregion #region Workflows_Delete [Fact] public void Workflows_Delete_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound }; Assert.Throws<ValidationException>(() => client.Workflows.Delete(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Delete("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Delete("rgName", "wfName")); } [Fact] public void Workflows_Delete_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Delete("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Delete); } [Fact] public void Workflows_Delete_NoContent() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent }; client.Workflows.Delete("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Delete); } #endregion #region Workflows_Get [Fact] public void Workflows_Get_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.Get(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Get("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Get("rgName", "wfName")); } [Fact] public void Workflows_Get_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var result = client.Workflows.Get("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflow1(result); } #endregion #region Workflows_Update [Fact] public void Workflows_Update_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.Update(null, "wfName", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Update("rgName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Update("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.Update("rgName", "wfName", new Workflow())); } [Fact] public void Workflows_Update_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var workflow = new Workflow() { Tags = new Dictionary<string, string>() }; workflow.Tags.Add("abc", "def"); workflow = client.Workflows.Update("rgName", "wfName", workflow); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(new HttpMethod("PATCH")); // Validates result. this.ValidateWorkflow1(workflow); } #endregion #region Workflows_Disable [Fact] public void Workflows_Disable_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Disable(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Disable("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Disable("rgName", "wfName")); } [Fact] public void Workflows_Disable_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Disable("rgName", "wfName"); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("disable"); } #endregion #region Workflows_Enable [Fact] public void Workflows_Enable_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Enable(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Enable("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Enable("rgName", "wfName")); } [Fact] public void Workflows_Enable_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Enable("rgName", "wfName"); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("enable"); } #endregion #region Workflows_Validate [Fact] public void Workflows_Validate_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Validate(null, "wfName", "westus", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", null, "westus", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", "wfName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", "wfName", "westus", null)); Assert.Throws<CloudException>(() => client.Workflows.Validate("rgName", "wfName", "westus", new Workflow())); } [Fact] public void Workflows_Validate_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Validate("rgName", "wfName", "westus", new Workflow()); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("validate"); } #endregion #region Workflows_GenerateUpgradedDefinition [Fact] public void Workflows_GenerateUpgradedDefinition_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition(null, "wfName", "2016-04-01-preview")); Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", null, "2016-04-01-preview")); // The Assert is disabled due to the following bug: https://github.com/Azure/autorest/issues/1288. // Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", "2016-04-01-preview")); } [Fact] public void Workflows_GenerateUpgradedDefinition_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", "2016-04-01-preview"); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("generateUpgradedDefinition"); } #endregion #region Validation private void ValidateWorkflowRun1(WorkflowRun workflowRun) { Assert.Equal("/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/runs/run87646872399558047", workflowRun.Id); Assert.Equal("run87646872399558047", workflowRun.Name); Assert.Equal("Microsoft.Logic/workflows/runs", workflowRun.Type); Assert.Equal(2015, workflowRun.StartTime.Value.Year); Assert.Equal(06, workflowRun.StartTime.Value.Month); Assert.Equal(23, workflowRun.StartTime.Value.Day); Assert.Equal(21, workflowRun.StartTime.Value.Hour); Assert.Equal(47, workflowRun.StartTime.Value.Minute); Assert.Equal(00, workflowRun.StartTime.Value.Second); Assert.Equal(00, workflowRun.StartTime.Value.Millisecond); Assert.Equal(DateTimeKind.Utc, workflowRun.StartTime.Value.Kind); Assert.Equal(2015, workflowRun.EndTime.Value.Year); Assert.Equal(06, workflowRun.EndTime.Value.Month); Assert.Equal(23, workflowRun.EndTime.Value.Day); Assert.Equal(21, workflowRun.EndTime.Value.Hour); Assert.Equal(47, workflowRun.EndTime.Value.Minute); Assert.Equal(30, workflowRun.EndTime.Value.Second); Assert.Equal(130, workflowRun.EndTime.Value.Millisecond); Assert.Equal(DateTimeKind.Utc, workflowRun.EndTime.Value.Kind); Assert.Equal(WorkflowStatus.Succeeded, workflowRun.Status.Value); Assert.Equal("a04da054-a1ae-409d-80ff-b09febefc357", workflowRun.CorrelationId); Assert.Equal("/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/versions/ver87717906782501130", workflowRun.Workflow.Id); Assert.Equal("Microsoft.Logic/workflows/versions", workflowRun.Workflow.Type); Assert.Equal("wfName/ver87717906782501130", workflowRun.Workflow.Name); Assert.Equal("6A65DA9E-CFF8-4D3E-B5FB-691739C7AD61", workflowRun.Trigger.Name); Assert.Equal(0, workflowRun.Outputs.Count); } private void ValidateWorkflow1(Workflow workflow) { Assert.Equal("/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName", workflow.Id); Assert.Equal("wfName", workflow.Name); Assert.Equal("Microsoft.Logic/workflows", workflow.Type); Assert.Equal("westus", workflow.Location); // 2015-06-23T21:47:00.0000001Z Assert.Equal(2015, workflow.CreatedTime.Value.Year); Assert.Equal(06, workflow.CreatedTime.Value.Month); Assert.Equal(23, workflow.CreatedTime.Value.Day); Assert.Equal(21, workflow.CreatedTime.Value.Hour); Assert.Equal(47, workflow.CreatedTime.Value.Minute); Assert.Equal(00, workflow.CreatedTime.Value.Second); Assert.Equal(DateTimeKind.Utc, workflow.CreatedTime.Value.Kind); // 2015-06-23T21:47:30.0000002Z Assert.Equal(2015, workflow.ChangedTime.Value.Year); Assert.Equal(06, workflow.ChangedTime.Value.Month); Assert.Equal(23, workflow.ChangedTime.Value.Day); Assert.Equal(21, workflow.ChangedTime.Value.Hour); Assert.Equal(47, workflow.ChangedTime.Value.Minute); Assert.Equal(30, workflow.ChangedTime.Value.Second); Assert.Equal(DateTimeKind.Utc, workflow.ChangedTime.Value.Kind); Assert.Equal(WorkflowState.Enabled, workflow.State); Assert.Equal("08587717906782501130", workflow.Version); Assert.Equal("https://westus.logic.azure.com/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName", workflow.AccessEndpoint); Assert.Equal(SkuName.Premium, workflow.Sku.Name); Assert.Equal("/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Web/serverFarms/planName", workflow.Sku.Plan.Id); Assert.Equal("Microsoft.Web/serverFarms", workflow.Sku.Plan.Type); Assert.Equal("planName", workflow.Sku.Plan.Name); Assert.NotEmpty(workflow.Definition.ToString()); Assert.Equal(2, workflow.Parameters.Count); Assert.Equal(ParameterType.String, workflow.Parameters["parameter1"].Type); Assert.Equal(ParameterType.Array, workflow.Parameters["parameter2"].Type); } private void ValidateWorkflowList1(IPage<Workflow> result) { Assert.Equal(1, result.Count()); this.ValidateWorkflow1(result.First()); Assert.Equal("http://workflowlist1nextlink", result.NextPageLink); } #endregion } }
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestExtrasProtoFile { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt32Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt64Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint32Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint64Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint32Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint64Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed32Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed64Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed32Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed64Extension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFloatExtension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedDoubleExtension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedBoolExtension); registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedEnumExtension); } #endregion #region Extensions public const int UnpackedInt32ExtensionFieldNumber = 90; public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedInt32Extension; public const int UnpackedInt64ExtensionFieldNumber = 91; public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedInt64Extension; public const int UnpackedUint32ExtensionFieldNumber = 92; [global::System.CLSCompliant(false)] public static pb::GeneratedExtensionBase<scg::IList<uint>> UnpackedUint32Extension; public const int UnpackedUint64ExtensionFieldNumber = 93; [global::System.CLSCompliant(false)] public static pb::GeneratedExtensionBase<scg::IList<ulong>> UnpackedUint64Extension; public const int UnpackedSint32ExtensionFieldNumber = 94; public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedSint32Extension; public const int UnpackedSint64ExtensionFieldNumber = 95; public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedSint64Extension; public const int UnpackedFixed32ExtensionFieldNumber = 96; [global::System.CLSCompliant(false)] public static pb::GeneratedExtensionBase<scg::IList<uint>> UnpackedFixed32Extension; public const int UnpackedFixed64ExtensionFieldNumber = 97; [global::System.CLSCompliant(false)] public static pb::GeneratedExtensionBase<scg::IList<ulong>> UnpackedFixed64Extension; public const int UnpackedSfixed32ExtensionFieldNumber = 98; public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedSfixed32Extension; public const int UnpackedSfixed64ExtensionFieldNumber = 99; public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedSfixed64Extension; public const int UnpackedFloatExtensionFieldNumber = 100; public static pb::GeneratedExtensionBase<scg::IList<float>> UnpackedFloatExtension; public const int UnpackedDoubleExtensionFieldNumber = 101; public static pb::GeneratedExtensionBase<scg::IList<double>> UnpackedDoubleExtension; public const int UnpackedBoolExtensionFieldNumber = 102; public static pb::GeneratedExtensionBase<scg::IList<bool>> UnpackedBoolExtension; public const int UnpackedEnumExtensionFieldNumber = 103; public static pb::GeneratedExtensionBase<scg::IList<global::Google.ProtocolBuffers.TestProtos.UnpackedExtensionsForeignEnum>> UnpackedEnumExtension; #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions, global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Builder> internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static UnitTestExtrasProtoFile() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChxleHRlc3QvdW5pdHRlc3RfZXh0cmFzLnByb3RvEhdwcm90b2J1Zl91bml0", "dGVzdF9leHRyYRokZ29vZ2xlL3Byb3RvYnVmL2NzaGFycF9vcHRpb25zLnBy", "b3RvIiIKFlRlc3RVbnBhY2tlZEV4dGVuc2lvbnMqCAgBEICAgIACKlIKHVVu", "cGFja2VkRXh0ZW5zaW9uc0ZvcmVpZ25FbnVtEg8KC0ZPUkVJR05fRk9PEAQS", "DwoLRk9SRUlHTl9CQVIQBRIPCgtGT1JFSUdOX0JBWhAGOlEKGHVucGFja2Vk", "X2ludDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0X2V4dHJhLlRl", "c3RVbnBhY2tlZEV4dGVuc2lvbnMYWiADKAU6UQoYdW5wYWNrZWRfaW50NjRf", "ZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFj", "a2VkRXh0ZW5zaW9ucxhbIAMoAzpSChl1bnBhY2tlZF91aW50MzJfZXh0ZW5z", "aW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0", "ZW5zaW9ucxhcIAMoDTpSChl1bnBhY2tlZF91aW50NjRfZXh0ZW5zaW9uEi8u", "cHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9u", "cxhdIAMoBDpSChl1bnBhY2tlZF9zaW50MzJfZXh0ZW5zaW9uEi8ucHJvdG9i", "dWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxheIAMo", "ETpSChl1bnBhY2tlZF9zaW50NjRfZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5p", "dHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhfIAMoEjpTChp1", "bnBhY2tlZF9maXhlZDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0", "X2V4dHJhLlRlc3RVbnBhY2tlZEV4dGVuc2lvbnMYYCADKAc6UwoadW5wYWNr", "ZWRfZml4ZWQ2NF9leHRlbnNpb24SLy5wcm90b2J1Zl91bml0dGVzdF9leHRy", "YS5UZXN0VW5wYWNrZWRFeHRlbnNpb25zGGEgAygGOlQKG3VucGFja2VkX3Nm", "aXhlZDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0X2V4dHJhLlRl", "c3RVbnBhY2tlZEV4dGVuc2lvbnMYYiADKA86VAobdW5wYWNrZWRfc2ZpeGVk", "NjRfZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVu", "cGFja2VkRXh0ZW5zaW9ucxhjIAMoEDpRChh1bnBhY2tlZF9mbG9hdF9leHRl", "bnNpb24SLy5wcm90b2J1Zl91bml0dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRF", "eHRlbnNpb25zGGQgAygCOlIKGXVucGFja2VkX2RvdWJsZV9leHRlbnNpb24S", "Ly5wcm90b2J1Zl91bml0dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRFeHRlbnNp", "b25zGGUgAygBOlAKF3VucGFja2VkX2Jvb2xfZXh0ZW5zaW9uEi8ucHJvdG9i", "dWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhmIAMo", "CDqIAQoXdW5wYWNrZWRfZW51bV9leHRlbnNpb24SLy5wcm90b2J1Zl91bml0", "dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRFeHRlbnNpb25zGGcgAygOMjYucHJv", "dG9idWZfdW5pdHRlc3RfZXh0cmEuVW5wYWNrZWRFeHRlbnNpb25zRm9yZWln", "bkVudW1CVgoTY29tLmdvb2dsZS5wcm90b2J1ZsI+PgohR29vZ2xlLlByb3Rv", "Y29sQnVmZmVycy5UZXN0UHJvdG9zEhdVbml0VGVzdEV4dHJhc1Byb3RvRmls", "ZUgB")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor = Descriptor.MessageTypes[0]; internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions, global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Builder>(internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor, new string[] { }); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[0]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[1]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint32Extension = pb::GeneratedRepeatExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[2]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint64Extension = pb::GeneratedRepeatExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[3]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[4]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[5]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed32Extension = pb::GeneratedRepeatExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[6]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed64Extension = pb::GeneratedRepeatExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[7]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[8]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[9]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFloatExtension = pb::GeneratedRepeatExtension<float>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[10]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedDoubleExtension = pb::GeneratedRepeatExtension<double>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[11]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedBoolExtension = pb::GeneratedRepeatExtension<bool>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[12]); global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedEnumExtension = pb::GeneratedRepeatExtension<global::Google.ProtocolBuffers.TestProtos.UnpackedExtensionsForeignEnum>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[13]); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Enums public enum UnpackedExtensionsForeignEnum { FOREIGN_FOO = 4, FOREIGN_BAR = 5, FOREIGN_BAZ = 6, } #endregion #region Messages [global::System.SerializableAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class TestUnpackedExtensions : pb::ExtendableMessage<TestUnpackedExtensions, TestUnpackedExtensions.Builder> { private TestUnpackedExtensions() { } private static readonly TestUnpackedExtensions defaultInstance = new TestUnpackedExtensions().MakeReadOnly(); private static readonly string[] _testUnpackedExtensionsFieldNames = new string[] { }; private static readonly uint[] _testUnpackedExtensionsFieldTags = new uint[] { }; public static TestUnpackedExtensions DefaultInstance { get { return defaultInstance; } } public override TestUnpackedExtensions DefaultInstanceForType { get { return DefaultInstance; } } protected override TestUnpackedExtensions ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<TestUnpackedExtensions, TestUnpackedExtensions.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable; } } public override bool IsInitialized { get { if (!ExtensionsAreInitialized) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _testUnpackedExtensionsFieldNames; pb::ExtendableMessage<TestUnpackedExtensions, TestUnpackedExtensions.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this); extensionWriter.WriteUntil(536870912, output); UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += ExtensionsSerializedSize; size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static TestUnpackedExtensions ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static TestUnpackedExtensions ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static TestUnpackedExtensions ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestUnpackedExtensions ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private TestUnpackedExtensions MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(TestUnpackedExtensions prototype) { return new Builder(prototype); } [global::System.SerializableAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::ExtendableBuilder<TestUnpackedExtensions, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(TestUnpackedExtensions cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private TestUnpackedExtensions result; private TestUnpackedExtensions PrepareBuilder() { if (resultIsReadOnly) { TestUnpackedExtensions original = result; result = new TestUnpackedExtensions(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override TestUnpackedExtensions MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Descriptor; } } public override TestUnpackedExtensions DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.DefaultInstance; } } public override TestUnpackedExtensions BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is TestUnpackedExtensions) { return MergeFrom((TestUnpackedExtensions) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(TestUnpackedExtensions other) { if (other == global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.DefaultInstance) return this; PrepareBuilder(); this.MergeExtensionFields(other); this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_testUnpackedExtensionsFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _testUnpackedExtensionsFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } } static TestUnpackedExtensions() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor, null); } } #endregion } #endregion Designer generated code
//--------------------------------------------------------------------------- // // <copyright file="PointLight.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class PointLight : PointLightBase { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new PointLight Clone() { return (PointLight)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new PointLight CloneCurrentValue() { return (PointLight)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new PointLight(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Read values of properties into local variables Transform3D vTransform = Transform; // Obtain handles for properties that implement DUCE.IResource DUCE.ResourceHandle hTransform; if (vTransform == null || Object.ReferenceEquals(vTransform, Transform3D.Identity) ) { hTransform = DUCE.ResourceHandle.Null; } else { hTransform = ((DUCE.IResource)vTransform).GetHandle(channel); } // Obtain handles for animated properties DUCE.ResourceHandle hColorAnimations = GetAnimationResourceHandle(ColorProperty, channel); DUCE.ResourceHandle hPositionAnimations = GetAnimationResourceHandle(PositionProperty, channel); DUCE.ResourceHandle hRangeAnimations = GetAnimationResourceHandle(RangeProperty, channel); DUCE.ResourceHandle hConstantAttenuationAnimations = GetAnimationResourceHandle(ConstantAttenuationProperty, channel); DUCE.ResourceHandle hLinearAttenuationAnimations = GetAnimationResourceHandle(LinearAttenuationProperty, channel); DUCE.ResourceHandle hQuadraticAttenuationAnimations = GetAnimationResourceHandle(QuadraticAttenuationProperty, channel); // Pack & send command packet DUCE.MILCMD_POINTLIGHT data; unsafe { data.Type = MILCMD.MilCmdPointLight; data.Handle = _duceResource.GetHandle(channel); data.htransform = hTransform; if (hColorAnimations.IsNull) { data.color = CompositionResourceManager.ColorToMilColorF(Color); } data.hColorAnimations = hColorAnimations; if (hPositionAnimations.IsNull) { data.position = CompositionResourceManager.Point3DToMilPoint3F(Position); } data.hPositionAnimations = hPositionAnimations; if (hRangeAnimations.IsNull) { data.range = Range; } data.hRangeAnimations = hRangeAnimations; if (hConstantAttenuationAnimations.IsNull) { data.constantAttenuation = ConstantAttenuation; } data.hConstantAttenuationAnimations = hConstantAttenuationAnimations; if (hLinearAttenuationAnimations.IsNull) { data.linearAttenuation = LinearAttenuation; } data.hLinearAttenuationAnimations = hLinearAttenuationAnimations; if (hQuadraticAttenuationAnimations.IsNull) { data.quadraticAttenuation = QuadraticAttenuation; } data.hQuadraticAttenuationAnimations = hQuadraticAttenuationAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_POINTLIGHT)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_POINTLIGHT)) { Transform3D vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Transform3D vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml.Linq; using Microsoft.Internal.Web.Utils; using NuGet.Resources; namespace NuGet { public class ProjectManager : IProjectManager { private event EventHandler<PackageOperationEventArgs> _packageReferenceAdding; private event EventHandler<PackageOperationEventArgs> _packageReferenceAdded; private event EventHandler<PackageOperationEventArgs> _packageReferenceRemoving; private event EventHandler<PackageOperationEventArgs> _packageReferenceRemoved; private ILogger _logger; private IPackageConstraintProvider _constraintProvider; // REVIEW: These should be externally pluggable private static readonly IDictionary<string, IPackageFileTransformer> _fileTransformers = new Dictionary<string, IPackageFileTransformer>(StringComparer.OrdinalIgnoreCase) { { ".transform", new XmlTransfomer(GetConfigMappings()) }, { ".pp", new Preprocessor() } }; public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (project == null) { throw new ArgumentNullException("project"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; Project = project; PathResolver = pathResolver; LocalRepository = localRepository; } public IPackagePathResolver PathResolver { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackageRepository SourceRepository { get; private set; } public IPackageConstraintProvider ConstraintProvider { get { return _constraintProvider ?? NullConstraintProvider.Instance; } set { _constraintProvider = value; } } public IProjectSystem Project { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding { add { _packageReferenceAdding += value; } remove { _packageReferenceAdding -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded { add { _packageReferenceAdded += value; } remove { _packageReferenceAdded -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving { add { _packageReferenceRemoving += value; } remove { _packageReferenceRemoving -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved { add { _packageReferenceRemoved += value; } remove { _packageReferenceRemoved -= value; } } public virtual void AddPackageReference(string packageId) { AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version) { AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions); AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { Execute(package, new UpdateWalker(LocalRepository, SourceRepository, new DependentsWalker(LocalRepository), ConstraintProvider, NullLogger.Instance, !ignoreDependencies, allowPrereleaseVersions) { AcceptedTargets = PackageTargets.Project }); } private void Execute(IPackage package, IPackageOperationResolver resolver) { IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName()); } else { AddPackageReferenceToProject(operation.Package); } } else { if (packageExists) { RemovePackageReferenceFromProject(operation.Package); } } } protected void AddPackageReferenceToProject(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceAdding(args); if (args.Cancel) { return; } ExtractPackageFilesToProject(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, package.GetFullName(), Project.ProjectName); OnPackageReferenceAdded(args); } protected virtual void ExtractPackageFilesToProject(IPackage package) { // BUG 491: Installing a package with incompatible binaries still does a partial install. // Resolve assembly references first so that if this fails we never do anything to the project IEnumerable<IPackageAssemblyReference> assemblyReferences = GetCompatibleItems(Project, package.AssemblyReferences, package.GetFullName()); IEnumerable<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies); try { // Add content files Project.AddFiles(package.GetContentFiles(), _fileTransformers); // Add the references to the reference path foreach (IPackageAssemblyReference assemblyReference in assemblyReferences) { // Get the physical path of the assembly reference string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path); string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath); if (Project.ReferenceExists(assemblyReference.Name)) { Project.RemoveReference(assemblyReference.Name); } using (Stream stream = assemblyReference.GetStream()) { Project.AddReference(relativeReferencePath, stream); } } // Add GAC/Framework references foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences) { if (!Project.ReferenceExists(frameworkReference.AssemblyName)) { Project.AddFrameworkReference(frameworkReference.AssemblyName); } } } finally { // Add package to local repository in the finally so that the user can uninstall it // if any exception occurs. This is easier than rolling back since the user can just // manually uninstall things that may have failed. // If this fails then the user is out of luck. LocalRepository.AddPackage(package); } } public bool IsInstalled(IPackage package) { return LocalRepository.Exists(package); } public void RemovePackageReference(string packageId) { RemovePackageReference(packageId, forceRemove: false, removeDependencies: false); } public void RemovePackageReference(string packageId, bool forceRemove) { RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false); } public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } RemovePackageReference(package, forceRemove, removeDependencies); } public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies) { Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository), NullLogger.Instance, removeDependencies, forceRemove)); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void RemovePackageReferenceFromProject(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceRemoving(args); if (args.Cancel) { return; } // Get other packages IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages() where p.Id != package.Id select p; // Get other references var otherAssemblyReferences = from p in otherPackages let assemblyReferences = Project.GetCompatibleItemsCore(p.AssemblyReferences) from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state select assemblyReference; // Get content files from other packages // Exclude transform files since they are treated specially var otherContentFiles = from p in otherPackages from file in p.GetContentFiles() where !_fileTransformers.ContainsKey(Path.GetExtension(file.Path)) select file; // Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting var assemblyReferencesToDelete = Project.GetCompatibleItemsCore(package.AssemblyReferences).Except(otherAssemblyReferences, PackageFileComparer.Default); var contentFilesToDelete = package.GetContentFiles() .Except(otherContentFiles, PackageFileComparer.Default); // Delete the content files Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers); // Remove references foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete) { Project.RemoveReference(assemblyReference.Name); } // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, package.GetFullName(), Project.ProjectName); OnPackageReferenceRemoved(args); } public void UpdatePackageReference(string packageId) { UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, SemanticVersion version) { UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference( packageId, () => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: versionSpec != null); } public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null); } private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage package = resolvePackage(); // the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version) // is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do: // update-package // without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version. if (package != null && oldPackage.Version != package.Version && (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName); UpdatePackageReference(package, updateDependencies, allowPrereleaseVersions); } else { IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId); if (constraint != null) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source); } Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName); } } protected void UpdatePackageReference(IPackage package) { UpdatePackageReference(package, updateDependencies: true, allowPrereleaseVersions: false); } protected void UpdatePackageReference(IPackage package, bool updateDependencies, bool allowPrereleaseVersions) { AddPackageReference(package, !updateDependencies, allowPrereleaseVersions); } private void OnPackageReferenceAdding(PackageOperationEventArgs e) { if (_packageReferenceAdding != null) { _packageReferenceAdding(this, e); } } private void OnPackageReferenceAdded(PackageOperationEventArgs e) { if (_packageReferenceAdded != null) { _packageReferenceAdded(this, e); } } private void OnPackageReferenceRemoved(PackageOperationEventArgs e) { if (_packageReferenceRemoved != null) { _packageReferenceRemoved(this, e); } } private void OnPackageReferenceRemoving(PackageOperationEventArgs e) { if (_packageReferenceRemoving != null) { _packageReferenceRemoving(this, e); } } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package)); } private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings() { // REVIEW: This might be an edge case, but we're setting this rule for all xml files. // If someone happens to do a transform where the xml file has a configSections node // we will add it first. This is probably fine, but this is a config specific scenario return new Dictionary<XName, Action<XElement, XElement>>() { { "configSections" , (parent, element) => parent.AddFirst(element) } }; } private static IEnumerable<T> GetCompatibleItems<T>(IProjectSystem project, IEnumerable<T> items, string package) where T : IFrameworkTargetable { // A package might have references that target a specific version of the framework (.net/silverlight etc) // so we try to get the highest version that satisfies the target framework i.e. // if a package has 1.0, 2.0, 4.0 and the target framework is 3.5 we'd pick the 2.0 references. IEnumerable<T> compatibleItems; if (!project.TryGetCompatibleItems(items, out compatibleItems)) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, package, project.TargetFramework, NuGetResources.AssemblyReferences)); } return compatibleItems; } private class PackageFileComparer : IEqualityComparer<IPackageFile> { internal static PackageFileComparer Default = new PackageFileComparer(); private PackageFileComparer() { } public bool Equals(IPackageFile x, IPackageFile y) { return x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(IPackageFile obj) { return obj.Path.GetHashCode(); } } // HACK: We need this to avoid a partial trust issue. We need to be able to evaluate closures // within this class. The attributes are necessary to prevent this method from being inlined into ClosureEvaluator [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static object Eval(FieldInfo fieldInfo, object obj) { return fieldInfo.GetValue(obj); } } }