context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Scheme.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Scheme { /// <summary> /// <para>The default class for creating sockets.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/PlainSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/PlainSocketFactory", AccessFlags = 49)] public sealed partial class PlainSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/conn/scheme/HostNameResolver;)V", AccessFlags = 1)] public PlainSocketFactory(global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public PlainSocketFactory() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory); } /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Checks whether a socket connection is secure. This factory creates plain socket connections which are not considered secure.</para><para></para> /// </summary> /// <returns> /// <para><code>false</code></para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 17)] public bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Compares this factory with an object. There is only one instance of this class.</para><para></para> /// </summary> /// <returns> /// <para>iff the argument is this object </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this object. All instances of this class have the same hash code. There is only one instance of this class. </para> /// </summary> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] get{ return GetSocketFactory(); } } } /// <java-name> /// org/apache/http/conn/scheme/HostNameResolver /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/HostNameResolver", AccessFlags = 1537)] public partial interface IHostNameResolver /* scope: __dot42__ */ { /// <java-name> /// resolve /// </java-name> [Dot42.DexImport("resolve", "(Ljava/lang/String;)Ljava/net/InetAddress;", AccessFlags = 1025)] global::Java.Net.InetAddress Resolve(string hostname) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A set of supported protocol schemes. Schemes are identified by lowercase names.</para><para><para></para><para></para><title>Revision:</title><para>648356 </para><title>Date:</title><para>2008-04-15 10:57:53 -0700 (Tue, 15 Apr 2008) </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SchemeRegistry /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SchemeRegistry", AccessFlags = 49)] public sealed partial class SchemeRegistry /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, empty scheme registry. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SchemeRegistry() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(string host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Lorg/apache/http/HttpHost;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains a scheme by name, if registered.</para><para></para> /// </summary> /// <returns> /// <para>the scheme, or <code>null</code> if there is none by this name </para> /// </returns> /// <java-name> /// get /// </java-name> [Dot42.DexImport("get", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Get(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Registers a scheme. The scheme can later be retrieved by its name using getScheme or get.</para><para></para> /// </summary> /// <returns> /// <para>the scheme previously registered with that name, or <code>null</code> if none was registered </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Lorg/apache/http/conn/scheme/Scheme;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Register(global::Org.Apache.Http.Conn.Scheme.Scheme sch) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Unregisters a scheme.</para><para></para> /// </summary> /// <returns> /// <para>the unregistered scheme, or <code>null</code> if there was none </para> /// </returns> /// <java-name> /// unregister /// </java-name> [Dot42.DexImport("unregister", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Unregister(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public global::Java.Util.IList<string> GetSchemeNames() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Populates the internal collection of registered protocol schemes with the content of the map passed as a parameter.</para><para></para> /// </summary> /// <java-name> /// setItems /// </java-name> [Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/conn/scheme/Scheme;>;)V")] public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Conn.Scheme.Scheme> map) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> public global::Java.Util.IList<string> SchemeNames { [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetSchemeNames(); } } } /// <summary> /// <para>Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified by lowercase names. Supported schemes are typically collected in a SchemeRegistry.</para><para>For example, to configure support for "https://" URLs, you could write code like the following: </para><para><pre> /// Scheme https = new Scheme("https", new MySecureSocketFactory(), 443); /// SchemeRegistry.DEFAULT.register(https); /// </pre></para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para>Jeff Dever </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/Scheme /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/Scheme", AccessFlags = 49)] public sealed partial class Scheme /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new scheme. Whether the created scheme allows for layered connections depends on the class of <code>factory</code>.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Lorg/apache/http/conn/scheme/SocketFactory;I)V", AccessFlags = 1)] public Scheme(string name, global::Org.Apache.Http.Conn.Scheme.ISocketFactory factory, int port) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] public int GetDefaultPort() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] public global::Org.Apache.Http.Conn.Scheme.ISocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.ISocketFactory); } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] public string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Indicates whether this scheme allows for layered connections.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if layered connections are possible, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isLayered /// </java-name> [Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)] public bool IsLayered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Resolves the correct port for this scheme. Returns the given port if it is valid, the default port otherwise.</para><para></para> /// </summary> /// <returns> /// <para>the given port or the defaultPort </para> /// </returns> /// <java-name> /// resolvePort /// </java-name> [Dot42.DexImport("resolvePort", "(I)I", AccessFlags = 17)] public int ResolvePort(int port) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Return a string representation of this object.</para><para></para> /// </summary> /// <returns> /// <para>a human-readable string description of this scheme </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Compares this scheme to an object.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> iff the argument is equal to this scheme </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this scheme.</para><para></para> /// </summary> /// <returns> /// <para>the hash code </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Scheme() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> public int DefaultPort { [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] get{ return GetDefaultPort(); } } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public global::Org.Apache.Http.Conn.Scheme.ISocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] get{ return GetSocketFactory(); } } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetName(); } } } /// <summary> /// <para>A SocketFactory for layered sockets (SSL/TLS). See there for things to consider when implementing a socket factory.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/LayeredSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/LayeredSocketFactory", AccessFlags = 1537)] public partial interface ILayeredSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.</para><para></para> /// </summary> /// <returns> /// <para>Socket a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A factory for creating and connecting sockets. The factory encapsulates the logic for establishing a socket connection. <br></br> Both Object.equals() and Object.hashCode() must be overridden for the correct operation of some connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SocketFactory", AccessFlags = 1537)] public partial interface ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ ; /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks whether a socket provides a secure connection. The socket must be connected by this factory. The factory will <b>not</b> perform I/O operations in this method. <br></br> As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, there may be application specific deviations. For example, a plain socket to a host in the same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL socket could be considered insecure based on the cypher suite chosen for the connection.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the connection of the socket should be considered secure, or <code>false</code> if it should not</para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1025)] bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ ; } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Collections; using System.Collections.Generic; /// <summary> /// The class is used to read/set bit value for a byte array. /// </summary> public static class Bit { /// <summary> /// Read a bit value from a byte array with the specified bit position. /// </summary> /// <param name="array">Specify the byte array.</param> /// <param name="bit">Specify the bit position.</param> /// <returns>Return the bit value in the specified bit position.</returns> public static bool IsBitSet(byte[] array, long bit) { return (array[bit / 8] & (1 << (int)(bit % 8))) != 0; } /// <summary> /// Set a bit value to "On" in the specified byte array with the specified bit position. /// </summary> /// <param name="array">Specify the byte array.</param> /// <param name="bit">Specify the bit position.</param> public static void SetBit(byte[] array, long bit) { array[bit / 8] |= unchecked((byte)(1 << (int)(bit % 8))); } /// <summary> /// Set a bit value to "Off" in the specified byte array with the specified bit position. /// </summary> /// <param name="array">Specify the byte array.</param> /// <param name="bit">Specify the bit position.</param> public static void ClearBit(byte[] array, long bit) { array[bit / 8] &= unchecked((byte)(~(1 << (int)(bit % 8)))); } } /// <summary> /// A class is used to extract values across byte boundaries with arbitrary bit positions. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")] public sealed class BitReader : IEnumerator<bool> { /// <summary> /// A byte array which contains the bytes need to be read. /// </summary> private byte[] byteArray; /// <summary> /// A start position which will be not changed in the process of reading. /// This value will be used for recording the start position and will be used by the function reset. /// </summary> private long startPosition; /// <summary> /// An offset which is used to keep trace for the current read position in bit. /// </summary> private long offset; /// <summary> /// The length of the byte Array which contains the byte need to be read. /// </summary> private long length; /// <summary> /// Initializes a new instance of the BitReader class with specified bytes buffer and start position in byte. /// </summary> /// <param name="array">Specify the byte array which contains the bytes need to be read.</param> /// <param name="index">Specify the start position in byte.</param> public BitReader(byte[] array, int index) { this.byteArray = array; this.offset = ((long)index * 8) - 1; this.startPosition = this.offset; this.length = (long)array.Length * 8; } /// <summary> /// Gets a value indicating whether the bit is true or false in the current bit position. /// </summary> public bool Current { get { return Bit.IsBitSet(this.byteArray, this.offset); } } /// <summary> /// Gets the bit in the byte array at the current position of the enumerator. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Read specified bit length content as an UInt64 type and increase the bit offset. /// </summary> /// <param name="readingLength">Specify the reading bit length.</param> /// <returns>Return the UInt64 type value.</returns> public ulong ReadUInt64(int readingLength) { byte[] uint64Bytes = this.GetBytes(readingLength, 8); return LittleEndianBitConverter.ToUInt64(uint64Bytes, 0); } /// <summary> /// Read specified bit length content as an UInt32 type and increase the bit offset with the specified length. /// </summary> /// <param name="readingLength">Specify the reading bit length.</param> /// <returns>Return the UInt32 type value.</returns> public uint ReadUInt32(int readingLength) { byte[] uint32Bytes = this.GetBytes(readingLength, 4); return LittleEndianBitConverter.ToUInt32(uint32Bytes, 0); } /// <summary> /// Reading the bytes specified by the byte length. /// </summary> /// <param name="readingLength">Specify the reading byte length.</param> /// <returns>Return the read bytes array.</returns> public byte[] ReadBytes(int readingLength) { byte[] readingByteArray = this.GetBytes(readingLength * 8, readingLength); return readingByteArray; } /// <summary> /// Read specified bit length content as an byte type and increase the bit offset with the specified length. /// </summary> /// <param name="readingBitLength">Specify the reading bit length.</param> /// <returns>Return the byte value.</returns> public byte ReadByte(int readingBitLength) { byte[] readingByteArray = this.GetBytes(readingBitLength, 1); return readingByteArray[0]; } /// <summary> /// Read specified bit length content as an UInt16 type and increase the bit offset with the specified length. /// </summary> /// <param name="readingLength">Specify the reading bit length.</param> /// <returns>Return the UInt16 value.</returns> public short ReadInt16(int readingLength) { byte[] uint16Bytes = this.GetBytes(readingLength, 2); return LittleEndianBitConverter.ToInt16(uint16Bytes, 0); } /// <summary> /// Read specified bit length content as an Int32 type and increase the bit offset with the specified length. /// </summary> /// <param name="readingLength">Specify the reading bit length.</param> /// <returns>Return the Int32 type value.</returns> public int ReadInt32(int readingLength) { byte[] uint32Bytes = this.GetBytes(readingLength, 4); return LittleEndianBitConverter.ToInt32(uint32Bytes, 0); } /// <summary> /// Read as a GUID from the current offset position and increate the bit offset with 128 bit. /// </summary> /// <returns>Return the GUID value.</returns> public Guid ReadGuid() { return new Guid(this.GetBytes(128, 16)); } /// <summary> /// Advances the enumerator to the next bit of the byte array. /// </summary> /// <returns>true if the enumerator was successfully advanced to the next bit; false if the enumerator has passed the end of the byte array.</returns> public bool MoveNext() { return ++this.offset < this.length; } /// <summary> /// Assign the internal read buffer to null. /// </summary> public void Dispose() { this.byteArray = null; } /// <summary> /// Sets the enumerator to its initial position, which is before the first bit in the byte array. /// </summary> public void Reset() { this.offset = this.startPosition; } /// <summary> /// Construct a byte array with specified bit length and the specified the byte array size. /// </summary> /// <param name="needReadlength">Specify the need read bit length.</param> /// <param name="size">Specify the byte array size.</param> /// <returns>Returns the constructed byte array.</returns> private byte[] GetBytes(int needReadlength, int size) { byte[] retBytes = new byte[size]; int i = 0; while (i < needReadlength) { if (!this.MoveNext()) { throw new InvalidOperationException("Unexpected to meet the byte array end."); } if (this.Current) { Bit.SetBit(retBytes, i); } else { Bit.ClearBit(retBytes, i); } i++; } return retBytes; } } /// <summary> /// A class is used to write various primitive number into a byte array with arbitrary bit positions. /// </summary> public sealed class BitWriter { /// <summary> /// A byte buffer will contain all the written byte. /// </summary> private byte[] bytes; /// <summary> /// An offset which is used to keep trace for the current write position in bit, staring with 0. /// </summary> private int bitOffset; /// <summary> /// Initializes a new instance of the BitWriter class with specified buffer size in byte. /// </summary> /// <param name="bufferSize">Specify the buffer byte size.</param> public BitWriter(int bufferSize) { this.bytes = new byte[bufferSize]; this.bitOffset = 0; } /// <summary> /// Gets a copy byte array which contains the current written byte. /// </summary> public byte[] Bytes { get { if (this.bitOffset % 8 != 0) { throw new InvalidOperationException("BitWriter:Bytes, Cannot get the current bytes because the last byte is not written completely."); } int retByteLength = this.bitOffset / 8; byte[] retByteArray = new byte[retByteLength]; System.Array.Copy(this.bytes, 0, retByteArray, 0, retByteLength); return retByteArray; } } /// <summary> /// Append a specified Unit64 type value into the buffer with the specified bit length. /// </summary> /// <param name="value">Specify the value which needs to be appended.</param> /// <param name="length">Specify the bit length which the value will occupy in the buffer.</param> public void AppendUInt64(ulong value, int length) { byte[] convertedBytes = LittleEndianBitConverter.GetBytes(value); this.SetBytes(convertedBytes, length); } /// <summary> /// Append a specified Unit32 type value into the buffer with the specified bit length. /// </summary> /// <param name="value">Specify the value which needs to be appended.</param> /// <param name="length">Specify the bit length which the value will occupy in the buffer.</param> public void AppendUInit32(uint value, int length) { byte[] convertedBytes = LittleEndianBitConverter.GetBytes(value); this.SetBytes(convertedBytes, length); } /// <summary> /// Append a specified Init32 type value into the buffer with the specified bit length. /// </summary> /// <param name="value">Specify the value which needs to be appended.</param> /// <param name="length">Specify the bit length which the value will occupy in the buffer.</param> public void AppendInit32(int value, int length) { byte[] convertedBytes = LittleEndianBitConverter.GetBytes(value); this.SetBytes(convertedBytes, length); } /// <summary> /// Append a specified GUID value into the buffer. /// </summary> /// <param name="value">Specify the GUID value.</param> public void AppendGUID(Guid value) { this.SetBytes(value.ToByteArray(), 128); } /// <summary> /// Write the specified byte array into the buffer from the current position with the specified bit length. /// </summary> /// <param name="needWrittenBytes">Specify the needed written byte array.</param> /// <param name="length">Specify the bit length which the byte array will occupy in the buffer.</param> private void SetBytes(byte[] needWrittenBytes, int length) { for (uint i = 0; i < length; i++) { if (Bit.IsBitSet(needWrittenBytes, i)) { Bit.SetBit(this.bytes, this.bitOffset++); } else { Bit.ClearBit(this.bytes, this.bitOffset++); } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.VideoIntelligence.V1 { /// <summary>Settings for <see cref="VideoIntelligenceServiceClient"/> instances.</summary> public sealed partial class VideoIntelligenceServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="VideoIntelligenceServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="VideoIntelligenceServiceSettings"/>.</returns> public static VideoIntelligenceServiceSettings GetDefault() => new VideoIntelligenceServiceSettings(); /// <summary> /// Constructs a new <see cref="VideoIntelligenceServiceSettings"/> object with default settings. /// </summary> public VideoIntelligenceServiceSettings() { } private VideoIntelligenceServiceSettings(VideoIntelligenceServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); AnnotateVideoSettings = existing.AnnotateVideoSettings; AnnotateVideoOperationsSettings = existing.AnnotateVideoOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(VideoIntelligenceServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>VideoIntelligenceServiceClient.AnnotateVideo</c> and <c>VideoIntelligenceServiceClient.AnnotateVideoAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 1000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 2.5</description></item> /// <item><description>Retry maximum delay: 120000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings AnnotateVideoSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(120000), backoffMultiplier: 2.5, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// Long Running Operation settings for calls to <c>VideoIntelligenceServiceClient.AnnotateVideo</c> and /// <c>VideoIntelligenceServiceClient.AnnotateVideoAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings AnnotateVideoOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="VideoIntelligenceServiceSettings"/> object.</returns> public VideoIntelligenceServiceSettings Clone() => new VideoIntelligenceServiceSettings(this); } /// <summary> /// Builder class for <see cref="VideoIntelligenceServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class VideoIntelligenceServiceClientBuilder : gaxgrpc::ClientBuilderBase<VideoIntelligenceServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public VideoIntelligenceServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public VideoIntelligenceServiceClientBuilder() { UseJwtAccessWithScopes = VideoIntelligenceServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref VideoIntelligenceServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<VideoIntelligenceServiceClient> task); /// <summary>Builds the resulting client.</summary> public override VideoIntelligenceServiceClient Build() { VideoIntelligenceServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<VideoIntelligenceServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<VideoIntelligenceServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private VideoIntelligenceServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return VideoIntelligenceServiceClient.Create(callInvoker, Settings); } private async stt::Task<VideoIntelligenceServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return VideoIntelligenceServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => VideoIntelligenceServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => VideoIntelligenceServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => VideoIntelligenceServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>VideoIntelligenceService client wrapper, for convenient use.</summary> /// <remarks> /// Service that implements the Video Intelligence API. /// </remarks> public abstract partial class VideoIntelligenceServiceClient { /// <summary> /// The default endpoint for the VideoIntelligenceService service, which is a host of /// "videointelligence.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "videointelligence.googleapis.com:443"; /// <summary>The default VideoIntelligenceService scopes.</summary> /// <remarks> /// The default VideoIntelligenceService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="VideoIntelligenceServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="VideoIntelligenceServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="VideoIntelligenceServiceClient"/>.</returns> public static stt::Task<VideoIntelligenceServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new VideoIntelligenceServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="VideoIntelligenceServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="VideoIntelligenceServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="VideoIntelligenceServiceClient"/>.</returns> public static VideoIntelligenceServiceClient Create() => new VideoIntelligenceServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="VideoIntelligenceServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="VideoIntelligenceServiceSettings"/>.</param> /// <returns>The created <see cref="VideoIntelligenceServiceClient"/>.</returns> internal static VideoIntelligenceServiceClient Create(grpccore::CallInvoker callInvoker, VideoIntelligenceServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient = new VideoIntelligenceService.VideoIntelligenceServiceClient(callInvoker); return new VideoIntelligenceServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC VideoIntelligenceService client</summary> public virtual VideoIntelligenceService.VideoIntelligenceServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo(AnnotateVideoRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync(AnnotateVideoRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync(AnnotateVideoRequest request, st::CancellationToken cancellationToken) => AnnotateVideoAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>AnnotateVideo</c>.</summary> public virtual lro::OperationsClient AnnotateVideoOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>AnnotateVideo</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress> PollOnceAnnotateVideo(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), AnnotateVideoOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>AnnotateVideo</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> PollOnceAnnotateVideoAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), AnnotateVideoOperationsClient, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported. URIs must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For /// more information, see [Request /// URIs](https://cloud.google.com/storage/docs/request-endpoints). To identify /// multiple videos, a video URI may include wildcards in the `object-id`. /// Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` must be unset. /// </param> /// <param name="features"> /// Required. Requested video annotation features. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo(string inputUri, scg::IEnumerable<Feature> features, gaxgrpc::CallSettings callSettings = null) => AnnotateVideo(new AnnotateVideoRequest { InputUri = inputUri ?? "", Features = { gax::GaxPreconditions.CheckNotNull(features, nameof(features)), }, }, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported. URIs must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For /// more information, see [Request /// URIs](https://cloud.google.com/storage/docs/request-endpoints). To identify /// multiple videos, a video URI may include wildcards in the `object-id`. /// Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` must be unset. /// </param> /// <param name="features"> /// Required. Requested video annotation features. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync(string inputUri, scg::IEnumerable<Feature> features, gaxgrpc::CallSettings callSettings = null) => AnnotateVideoAsync(new AnnotateVideoRequest { InputUri = inputUri ?? "", Features = { gax::GaxPreconditions.CheckNotNull(features, nameof(features)), }, }, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported. URIs must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For /// more information, see [Request /// URIs](https://cloud.google.com/storage/docs/request-endpoints). To identify /// multiple videos, a video URI may include wildcards in the `object-id`. /// Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` must be unset. /// </param> /// <param name="features"> /// Required. Requested video annotation features. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync(string inputUri, scg::IEnumerable<Feature> features, st::CancellationToken cancellationToken) => AnnotateVideoAsync(inputUri, features, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>VideoIntelligenceService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service that implements the Video Intelligence API. /// </remarks> public sealed partial class VideoIntelligenceServiceClientImpl : VideoIntelligenceServiceClient { private readonly gaxgrpc::ApiCall<AnnotateVideoRequest, lro::Operation> _callAnnotateVideo; /// <summary> /// Constructs a client wrapper for the VideoIntelligenceService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="VideoIntelligenceServiceSettings"/> used within this client. /// </param> public VideoIntelligenceServiceClientImpl(VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient, VideoIntelligenceServiceSettings settings) { GrpcClient = grpcClient; VideoIntelligenceServiceSettings effectiveSettings = settings ?? VideoIntelligenceServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); AnnotateVideoOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.AnnotateVideoOperationsSettings); _callAnnotateVideo = clientHelper.BuildApiCall<AnnotateVideoRequest, lro::Operation>(grpcClient.AnnotateVideoAsync, grpcClient.AnnotateVideo, effectiveSettings.AnnotateVideoSettings); Modify_ApiCall(ref _callAnnotateVideo); Modify_AnnotateVideoApiCall(ref _callAnnotateVideo); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_AnnotateVideoApiCall(ref gaxgrpc::ApiCall<AnnotateVideoRequest, lro::Operation> call); partial void OnConstruction(VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient, VideoIntelligenceServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC VideoIntelligenceService client</summary> public override VideoIntelligenceService.VideoIntelligenceServiceClient GrpcClient { get; } partial void Modify_AnnotateVideoRequest(ref AnnotateVideoRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>AnnotateVideo</c>.</summary> public override lro::OperationsClient AnnotateVideoOperationsClient { get; } /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo(AnnotateVideoRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AnnotateVideoRequest(ref request, ref callSettings); return new lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>(_callAnnotateVideo.Sync(request, callSettings), AnnotateVideoOperationsClient); } /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync(AnnotateVideoRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AnnotateVideoRequest(ref request, ref callSettings); return new lro::Operation<AnnotateVideoResponse, AnnotateVideoProgress>(await _callAnnotateVideo.Async(request, callSettings).ConfigureAwait(false), AnnotateVideoOperationsClient); } } public static partial class VideoIntelligenceService { public partial class VideoIntelligenceServiceClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Linq; using ILCompiler.Compiler.CppCodeGen; using ILCompiler.SymbolReader; using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.Runtime; using Internal.IL; using ILCompiler.DependencyAnalysis; namespace ILCompiler.CppCodeGen { internal class CppWriter { private Compilation _compilation; private void SetWellKnownTypeSignatureName(WellKnownType wellKnownType, string mangledSignatureName) { var type = _compilation.TypeSystemContext.GetWellKnownType(wellKnownType); _cppSignatureNames.Add(type, mangledSignatureName); } public CppWriter(Compilation compilation) { _compilation = compilation; _out = new StreamWriter(File.Create(compilation.Options.OutputFilePath)); SetWellKnownTypeSignatureName(WellKnownType.Void, "void"); SetWellKnownTypeSignatureName(WellKnownType.Boolean, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Char, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.SByte, "int8_t"); SetWellKnownTypeSignatureName(WellKnownType.Byte, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Int16, "int16_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt16, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.Int32, "int32_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt32, "uint32_t"); SetWellKnownTypeSignatureName(WellKnownType.Int64, "int64_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt64, "uint64_t"); SetWellKnownTypeSignatureName(WellKnownType.IntPtr, "intptr_t"); SetWellKnownTypeSignatureName(WellKnownType.UIntPtr, "uintptr_t"); SetWellKnownTypeSignatureName(WellKnownType.Single, "float"); SetWellKnownTypeSignatureName(WellKnownType.Double, "double"); BuildExternCSignatureMap(); } private Dictionary<TypeDesc, string> _cppSignatureNames = new Dictionary<TypeDesc, string>(); public string GetCppSignatureTypeName(TypeDesc type) { string mangledName; if (_cppSignatureNames.TryGetValue(type, out mangledName)) return mangledName; // TODO: Use friendly names for enums if (type.IsEnum) mangledName = GetCppSignatureTypeName(type.UnderlyingType); else mangledName = GetCppTypeName(type); if (!type.IsValueType && !type.IsByRef && !type.IsPointer) mangledName += "*"; _cppSignatureNames.Add(type, mangledName); return mangledName; } // extern "C" methods are sometimes referenced via different signatures. // _externCSignatureMap contains the canonical signature of the extern "C" import. References // via other signatures are required to use casts. private Dictionary<string, MethodSignature> _externCSignatureMap = new Dictionary<string, MethodSignature>(); private void BuildExternCSignatureMap() { foreach (var nodeAlias in _compilation.NodeFactory.NodeAliases) { var methodNode = (CppMethodCodeNode)nodeAlias.Key; _externCSignatureMap.Add(nodeAlias.Value, methodNode.Method.Signature); } } public string GetCppMethodDeclaration(MethodDesc method, bool implementation, string externalMethodName = null, MethodSignature methodSignature = null) { var sb = new CppGenerationBuffer(); if (methodSignature == null) methodSignature = method.Signature; if (externalMethodName != null) { sb.Append("extern \"C\" "); } else { if (!implementation) { sb.Append("static "); } } sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType)); sb.Append(" "); if (externalMethodName != null) { sb.Append(externalMethodName); } else { if (implementation) { sb.Append(GetCppMethodDeclarationName(method.OwningType, GetCppMethodName(method))); } else { sb.Append(GetCppMethodName(method)); } } sb.Append("("); bool hasThis = !methodSignature.IsStatic; int argCount = methodSignature.Length; if (hasThis) argCount++; List<string> parameterNames = null; if (method != null) { IEnumerable<string> parameters = _compilation.TypeSystemContext.GetParameterNamesForMethod(method); if (parameters != null) { parameterNames = new List<string>(parameters); if (parameterNames.Count != 0) { System.Diagnostics.Debug.Assert(parameterNames.Count == argCount); } else { parameterNames = null; } } } for (int i = 0; i < argCount; i++) { if (hasThis) { if (i == 0) { var thisType = method.OwningType; if (thisType.IsValueType) thisType = thisType.MakeByRefType(); sb.Append(GetCppSignatureTypeName(thisType)); } else { sb.Append(GetCppSignatureTypeName(methodSignature[i - 1])); } } else { sb.Append(GetCppSignatureTypeName(methodSignature[i])); } if (implementation) { sb.Append(" "); if (parameterNames != null) { sb.Append(SanitizeCppVarName(parameterNames[i])); } else { sb.Append("_a"); sb.Append(i.ToStringInvariant()); } } if (i != argCount - 1) sb.Append(", "); } sb.Append(")"); if (!implementation) sb.Append(";"); return sb.ToString(); } public string GetCppMethodCallParamList(MethodDesc method) { var sb = new CppGenerationBuffer(); var methodSignature = method.Signature; bool hasThis = !methodSignature.IsStatic; int argCount = methodSignature.Length; if (hasThis) argCount++; List<string> parameterNames = null; IEnumerable<string> parameters = _compilation.TypeSystemContext.GetParameterNamesForMethod(method); if (parameters != null) { parameterNames = new List<string>(parameters); if (parameterNames.Count != 0) { System.Diagnostics.Debug.Assert(parameterNames.Count == argCount); } else { parameterNames = null; } } for (int i = 0; i < argCount; i++) { if (parameterNames != null) { sb.Append(SanitizeCppVarName(parameterNames[i])); } else { sb.Append("_a"); sb.Append(i.ToStringInvariant()); } if (i != argCount - 1) sb.Append(", "); } return sb.ToString(); } public string GetCppTypeName(TypeDesc type) { switch (type.Category) { case TypeFlags.ByRef: case TypeFlags.Pointer: return GetCppSignatureTypeName(((ParameterizedType)type).ParameterType) + "*"; default: return _compilation.NameMangler.GetMangledTypeName(type); } } /// <summary> /// Compute a proper declaration for <param name="methodName"/> defined in <param name="owningType"/>. /// Usually the C++ name for a type is prefixed by "::" but this is not a valid way to declare a method, /// so we need to strip it if present. /// </summary> /// <param name="owningType">Type where <param name="methodName"/> belongs.</param> /// <param name="methodName">Name of method from <param name="owningType"/>.</param> /// <returns>C++ declaration name for <param name="methodName"/>.</returns> public string GetCppMethodDeclarationName(TypeDesc owningType, string methodName) { var s = GetCppTypeName(owningType); if (s.StartsWith("::")) { // For a Method declaration we do not need the starting :: s = s.Substring(2, s.Length - 2); } return string.Concat(s, "::", methodName); } public string GetCppMethodName(MethodDesc method) { return _compilation.NameMangler.GetMangledMethodName(method); } public string GetCppFieldName(FieldDesc field) { return _compilation.NameMangler.GetMangledFieldName(field); } public string GetCppStaticFieldName(FieldDesc field) { TypeDesc type = field.OwningType; string typeName = GetCppTypeName(type); return typeName.Replace("::", "__") + "__" + _compilation.NameMangler.GetMangledFieldName(field); } public string SanitizeCppVarName(string varName) { // TODO: name mangling robustness if (varName == "errno") // some names collide with CRT headers varName += "_"; return varName; } private string CompileSpecialMethod(MethodDesc method, SpecialMethodKind kind) { var builder = new CppGenerationBuffer(); switch (kind) { case SpecialMethodKind.PInvoke: case SpecialMethodKind.RuntimeImport: { EcmaMethod ecmaMethod = method as EcmaMethod; string importName = kind == SpecialMethodKind.PInvoke ? method.GetPInvokeMethodMetadata().Name : ecmaMethod.GetAttributeStringValue("System.Runtime", "RuntimeImportAttribute"); if (importName == null) importName = method.Name; MethodSignature methodSignature = method.Signature; bool slotCastRequired = false; MethodSignature externCSignature; if (_externCSignatureMap.TryGetValue(importName, out externCSignature)) { slotCastRequired = !externCSignature.Equals(method.Signature); } else { _externCSignatureMap.Add(importName, methodSignature); externCSignature = methodSignature; } builder.AppendLine(); builder.Append(GetCppMethodDeclaration(method, true)); builder.AppendLine(); builder.Append("{"); builder.Indent(); if (slotCastRequired) { AppendSlotTypeDef(builder, method); } builder.AppendLine(); if (!method.Signature.ReturnType.IsVoid) { builder.Append("return "); } if (slotCastRequired) builder.Append("((__slot__" + GetCppMethodName(method) + ")"); builder.Append("::"); builder.Append(importName); if (slotCastRequired) builder.Append(")"); builder.Append("("); builder.Append(GetCppMethodCallParamList(method)); builder.Append(");"); builder.Exdent(); builder.AppendLine(); builder.Append("}"); return builder.ToString(); } default: builder.AppendLine(); builder.Append(GetCppMethodDeclaration(method, true)); builder.AppendLine(); builder.Append("{"); builder.Indent(); builder.AppendLine(); builder.Append("throw 0xC000C000;"); builder.Exdent(); builder.AppendLine(); builder.Append("}"); return builder.ToString(); } } public void CompileMethod(CppMethodCodeNode methodCodeNodeNeedingCode) { MethodDesc method = methodCodeNodeNeedingCode.Method; _compilation.Log.WriteLine("Compiling " + method.ToString()); SpecialMethodKind kind = method.DetectSpecialMethodKind(); if (kind != SpecialMethodKind.Unknown) { string specialMethodCode = CompileSpecialMethod(method, kind); methodCodeNodeNeedingCode.SetCode(specialMethodCode, Array.Empty<Object>()); return; } var methodIL = _compilation.GetMethodIL(method); if (methodIL == null) return; try { var ilImporter = new ILImporter(_compilation, this, method, methodIL); CompilerTypeSystemContext typeSystemContext = _compilation.TypeSystemContext; if (!_compilation.Options.NoLineNumbers) { IEnumerable<ILSequencePoint> sequencePoints = typeSystemContext.GetSequencePointsForMethod(method); if (sequencePoints != null) ilImporter.SetSequencePoints(sequencePoints); } IEnumerable<ILLocalVariable> localVariables = typeSystemContext.GetLocalVariableNamesForMethod(method); if (localVariables != null) ilImporter.SetLocalVariables(localVariables); IEnumerable<string> parameters = typeSystemContext.GetParameterNamesForMethod(method); if (parameters != null) ilImporter.SetParameterNames(parameters); ilImporter.Compile(methodCodeNodeNeedingCode); } catch (Exception e) { _compilation.Log.WriteLine(e.Message + " (" + method + ")"); var builder = new CppGenerationBuffer(); builder.AppendLine(); builder.Append(GetCppMethodDeclaration(method, true)); builder.AppendLine(); builder.Append("{"); builder.Indent(); builder.AppendLine(); builder.Append("throw 0xC000C000;"); builder.Exdent(); builder.AppendLine(); builder.Append("}"); methodCodeNodeNeedingCode.SetCode(builder.ToString(), Array.Empty<Object>()); } } private TextWriter Out { get { return _out; } } private StreamWriter _out; private Dictionary<TypeDesc, List<MethodDesc>> _methodLists; private CppGenerationBuffer _statics; private CppGenerationBuffer _gcStatics; private CppGenerationBuffer _threadStatics; private CppGenerationBuffer _gcThreadStatics; // Base classes and valuetypes has to be emitted before they are used. private HashSet<TypeDesc> _emittedTypes; private TypeDesc GetFieldTypeOrPlaceholder(FieldDesc field) { try { return field.FieldType; } catch { // TODO: For now, catch errors due to missing dependencies return _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Boolean); } } private void ExpandTypes() { _emittedTypes = new HashSet<TypeDesc>(); foreach (var t in _cppSignatureNames.Keys.ToArray()) { ExpandType(t); } _emittedTypes = null; } private void ExpandType(TypeDesc type) { if (_emittedTypes.Contains(type)) return; _emittedTypes.Add(type); GetCppSignatureTypeName(type); var baseType = type.BaseType; if (baseType != null) { ExpandType(baseType); } foreach (var field in type.GetFields()) { ExpandType(GetFieldTypeOrPlaceholder(field)); } if (type.IsDelegate) { MethodDesc method = type.GetKnownMethod("Invoke", null); var sig = method.Signature; ExpandType(sig.ReturnType); for (int i = 0; i < sig.Length; i++) ExpandType(sig[i]); } if (type.IsArray) { ExpandType(((ArrayType)type).ElementType); } } private void OutputTypes(bool full) { var sb = new CppGenerationBuffer(); if (full) { _statics = new CppGenerationBuffer(); _statics.Indent(); _gcStatics = new CppGenerationBuffer(); _gcStatics.Indent(); _threadStatics = new CppGenerationBuffer(); _threadStatics.Indent(); _gcThreadStatics = new CppGenerationBuffer(); _gcThreadStatics.Indent(); } _emittedTypes = new HashSet<TypeDesc>(); foreach (var t in _cppSignatureNames.Keys) { if (t.IsByRef || t.IsPointer) continue; // Base class types and valuetype instantance field types may be emitted out-of-order to make them // appear before they are used. if (_emittedTypes.Contains(t)) continue; OutputType(sb, t, full); } _emittedTypes = null; if (full) { sb.AppendLine(); sb.Append("struct {"); // No need to indent or add a new line as _statics is already properly indented sb.Append(_statics.ToString()); sb.AppendLine(); sb.Append("} __statics;"); // TODO: Register GC statics with GC sb.AppendLine(); sb.Append("struct {"); // No need to indent or add a new line as _gcStatics is already properly indented sb.Append(_gcStatics.ToString()); sb.AppendLine(); sb.Append("} __gcStatics;"); sb.AppendLine(); _statics = null; _gcStatics = null; _threadStatics = null; _gcThreadStatics = null; } Out.Write(sb.ToString()); sb.Clear(); } private void OutputType(CppGenerationBuffer sb, TypeDesc t, bool full) { _emittedTypes.Add(t); if (full) { if (!t.IsValueType) { var baseType = t.BaseType; if (baseType != null) { if (!_emittedTypes.Contains(baseType)) { OutputType(sb, baseType, full); } } } foreach (var field in t.GetFields()) { var fieldType = GetFieldTypeOrPlaceholder(field); if (fieldType.IsValueType && !fieldType.IsPrimitive && !field.IsStatic) { if (!_emittedTypes.Contains(fieldType)) { OutputType(sb, fieldType, full); } } } } string mangledName = GetCppTypeName(t); int nesting = 0; int current = 0; // Create Namespaces. If a mangledName starts with just :: we will simply ignore it. sb.AppendLine(); for (;;) { int sep = mangledName.IndexOf("::", current); if (sep < 0) break; if (sep != 0) { // Case of a name not starting with :: sb.Append("namespace " + mangledName.Substring(current, sep - current) + " { "); nesting++; } current = sep + 2; } if (full) { sb.Append("class " + mangledName.Substring(current)); if (!t.IsValueType) { var baseType = t.BaseType; if (baseType != null) { sb.Append(" : public " + GetCppTypeName(baseType)); } } sb.Append(" {"); sb.AppendLine(); sb.Append("public:"); sb.Indent(); // TODO: Enable once the dependencies are tracked for arrays // if (((DependencyNode)_compilation.NodeFactory.ConstructedTypeSymbol(t)).Marked) if (!t.IsPointer && !t.IsByRef) { sb.AppendLine(); sb.Append("static MethodTable * __getMethodTable();"); } List<MethodDesc> virtualSlots; _compilation.NodeFactory.VirtualSlots.TryGetValue(t, out virtualSlots); if (virtualSlots != null) { int baseSlots = 0; var baseType = t.BaseType; while (baseType != null) { List<MethodDesc> baseVirtualSlots; _compilation.NodeFactory.VirtualSlots.TryGetValue(baseType, out baseVirtualSlots); if (baseVirtualSlots != null) baseSlots += baseVirtualSlots.Count; baseType = baseType.BaseType; } for (int slot = 0; slot < virtualSlots.Count; slot++) { MethodDesc virtualMethod = virtualSlots[slot]; sb.AppendLine(); sb.Append(GetCodeForVirtualMethod(virtualMethod, baseSlots + slot)); } } if (t.IsDelegate) { sb.AppendLine(); sb.Append(GetCodeForDelegate(t)); } OutputTypeFields(sb, t); if (t.HasStaticConstructor) { _statics.AppendLine(); _statics.Append("bool __cctor_" + GetCppTypeName(t).Replace("::", "__") + ";"); } List<MethodDesc> methodList; if (_methodLists.TryGetValue(t, out methodList)) { foreach (var m in methodList) { OutputMethod(sb, m); } } sb.Exdent(); sb.AppendLine(); sb.Append("};"); } else { sb.Append("class " + mangledName.Substring(current) + ";"); } while (nesting > 0) { sb.Append("};"); nesting--; } // Make some rooms between two type definitions if (full) sb.AppendEmptyLine(); } private void OutputTypeFields(CppGenerationBuffer sb, TypeDesc t) { bool explicitLayout = false; ClassLayoutMetadata classLayoutMetadata = default(ClassLayoutMetadata); if (t.IsValueType) { MetadataType metadataType = (MetadataType)t; if (metadataType.IsExplicitLayout) { explicitLayout = true; classLayoutMetadata = metadataType.GetClassLayout(); } } int instanceFieldIndex = 0; if (explicitLayout) { sb.AppendLine(); sb.Append("union {"); sb.Indent(); } foreach (var field in t.GetFields()) { if (field.IsStatic) { if (field.IsLiteral) continue; TypeDesc fieldType = GetFieldTypeOrPlaceholder(field); CppGenerationBuffer builder; if (!fieldType.IsValueType) { builder = _gcStatics; } else { // TODO: Valuetype statics with GC references builder = _statics; } builder.AppendLine(); builder.Append(GetCppSignatureTypeName(fieldType)); builder.Append(" "); builder.Append(GetCppStaticFieldName(field) + ";"); } else { if (explicitLayout) { sb.AppendLine(); sb.Append("struct {"); sb.Indent(); int offset = classLayoutMetadata.Offsets[instanceFieldIndex].Offset; if (offset > 0) { sb.AppendLine(); sb.Append("char __pad" + instanceFieldIndex + "[" + offset + "];"); } } sb.AppendLine(); sb.Append(GetCppSignatureTypeName(GetFieldTypeOrPlaceholder(field)) + " " + GetCppFieldName(field) + ";"); if (explicitLayout) { sb.Exdent(); sb.AppendLine(); sb.Append("};"); } instanceFieldIndex++; } } if (explicitLayout) { sb.Exdent(); sb.AppendLine(); sb.Append("};"); } } private void OutputMethod(CppGenerationBuffer sb, MethodDesc m) { sb.AppendLine(); sb.Append(GetCppMethodDeclaration(m, false)); } private void AppendSlotTypeDef(CppGenerationBuffer sb, MethodDesc method) { MethodSignature methodSignature = method.Signature; TypeDesc thisArgument = null; if (!methodSignature.IsStatic) thisArgument = method.OwningType; AppendSignatureTypeDef(sb, "__slot__" + GetCppMethodName(method), methodSignature, thisArgument); } internal void AppendSignatureTypeDef(CppGenerationBuffer sb, string name, MethodSignature methodSignature, TypeDesc thisArgument) { sb.AppendLine(); sb.Append("typedef "); sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType)); sb.Append("(*"); sb.Append(name); sb.Append(")("); int argCount = methodSignature.Length; if (thisArgument != null) argCount++; for (int i = 0; i < argCount; i++) { if (thisArgument != null) { if (i == 0) { sb.Append(GetCppSignatureTypeName(thisArgument)); } else { sb.Append(GetCppSignatureTypeName(methodSignature[i - 1])); } } else { sb.Append(GetCppSignatureTypeName(methodSignature[i])); } if (i != argCount - 1) sb.Append(", "); } sb.Append(");"); } private String GetCodeForDelegate(TypeDesc delegateType) { var sb = new CppGenerationBuffer(); MethodDesc method = delegateType.GetKnownMethod("Invoke", null); AppendSlotTypeDef(sb, method); sb.AppendLine(); sb.Append("static __slot__"); sb.Append(GetCppMethodName(method)); sb.Append(" __invoke__"); sb.Append(GetCppMethodName(method)); sb.Append("(void * pThis)"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("return (__slot__"); sb.Append(GetCppMethodName(method)); sb.Append(")((("); sb.Append(GetCppSignatureTypeName(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.MulticastDelegate))); sb.Append(")pThis)->m_functionPointer);"); sb.Exdent(); sb.AppendLine(); sb.Append("};"); return sb.ToString(); } private String GetCodeForVirtualMethod(MethodDesc method, int slot) { var sb = new CppGenerationBuffer(); AppendSlotTypeDef(sb, method); sb.AppendLine(); sb.Append("static __slot__"); sb.Append(GetCppMethodName(method)); sb.Append(" __getslot__"); sb.Append(GetCppMethodName(method)); sb.Append("(void * pThis)"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append(" return (__slot__"); sb.Append(GetCppMethodName(method)); sb.Append(")*((void **)(*((RawEEType **)pThis) + 1) + "); sb.Append(slot.ToStringInvariant()); sb.Append(");"); sb.Exdent(); sb.AppendLine(); sb.Append("};"); return sb.ToString(); } private void AppendVirtualSlots(CppGenerationBuffer sb, TypeDesc implType, TypeDesc declType) { var baseType = declType.BaseType; if (baseType != null) AppendVirtualSlots(sb, implType, baseType); List<MethodDesc> virtualSlots; _compilation.NodeFactory.VirtualSlots.TryGetValue(declType, out virtualSlots); if (virtualSlots != null) { for (int i = 0; i < virtualSlots.Count; i++) { MethodDesc declMethod = virtualSlots[i]; MethodDesc implMethod = VirtualFunctionResolution.FindVirtualFunctionTargetMethodOnObjectType(declMethod, implType.GetClosestMetadataType()); sb.AppendLine(); if (implMethod.IsAbstract) { sb.Append("NULL,"); } else { sb.Append("(void*)&"); sb.Append(GetCppMethodDeclarationName(implMethod.OwningType, GetCppMethodName(implMethod))); sb.Append(","); } } } } private String GetCodeForType(TypeDesc type) { var sb = new CppGenerationBuffer(); int totalSlots = 0; TypeDesc t = type; while (t != null) { List<MethodDesc> virtualSlots; _compilation.NodeFactory.VirtualSlots.TryGetValue(t, out virtualSlots); if (virtualSlots != null) totalSlots += virtualSlots.Count; t = t.BaseType; } UInt16 flags = 0; try { flags = EETypeBuilderHelpers.ComputeFlags(type); } catch { // TODO: Handling of missing dependencies flags = 0; } sb.Append("MethodTable * "); sb.Append(GetCppMethodDeclarationName(type, "__getMethodTable")); sb.Append("()"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("static struct {"); sb.Indent(); // sb.Append(GCDesc); sb.AppendLine(); sb.Append("RawEEType EEType;"); if (totalSlots != 0) { sb.AppendLine(); sb.Append("void * slots["); sb.Append(totalSlots); sb.Append("];"); } sb.Exdent(); sb.AppendLine(); sb.Append("} mt = {"); sb.Indent(); // gcdesc if (type.IsString) { // String has non-standard layout sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("sizeof(uint16_t),"); sb.AppendLine(); sb.Append("0x"); // EEType::_usComponentSize sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags sb.Append(","); sb.AppendLine(); sb.Append("2 * sizeof(void*) + sizeof(int32_t) + 2,"); // EEType::_uBaseSize } else if (type.IsSzArray) { sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("sizeof("); sb.Append(GetCppSignatureTypeName(((ArrayType)type).ElementType)); // EEType::_usComponentSize sb.Append("),"); sb.AppendLine(); sb.Append("0x"); sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags sb.Append(","); sb.AppendLine(); sb.Append("3 * sizeof(void*),"); // EEType::_uBaseSize } else if (type.IsArray) { sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("sizeof("); sb.Append(GetCppSignatureTypeName(((ArrayType)type).ElementType)); // EEType::_usComponentSize sb.Append("),"); sb.AppendLine(); sb.Append("0x"); sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags sb.Append(","); sb.AppendLine(); sb.Append("3 * sizeof(void*) + "); // EEType::_uBaseSize sb.Append(((ArrayType)type).Rank.ToStringInvariant()); sb.Append("* sizeof(int32_t) * 2,"); } else { // sizeof(void*) == size of object header sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("0,"); sb.AppendLine(); sb.Append("0x"); // EEType::_usComponentSize sb.Append(flags.ToStringInvariant("x")); // EEType::_usFlags sb.Append(","); sb.AppendLine(); sb.Append("AlignBaseSize(sizeof(void*)+sizeof("); // EEType::_uBaseSize sb.Append(GetCppTypeName(type)); sb.Append(")),"); } sb.AppendLine(); // base type if (type.IsArray) { sb.Append(GetCppMethodDeclarationName(((ArrayType)type).ElementType, "__getMethodTable")); sb.Append("()"); } else { var baseType = type.BaseType; if (baseType != null) { sb.Append(GetCppMethodDeclarationName(type.BaseType, "__getMethodTable")); sb.Append("()"); } else { sb.Append("NULL"); } } sb.Exdent(); sb.AppendLine(); sb.Append("},"); // virtual slots if (((DependencyNode)_compilation.NodeFactory.ConstructedTypeSymbol(type)).Marked) AppendVirtualSlots(sb, type, type); sb.Exdent(); sb.AppendLine(); sb.Append("};"); sb.AppendLine(); sb.Append("return (MethodTable *)&mt.EEType;"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); return sb.ToString(); } private void BuildMethodLists(IEnumerable<DependencyNode> nodes) { _methodLists = new Dictionary<TypeDesc, List<MethodDesc>>(); foreach (var node in nodes) { if (node is CppMethodCodeNode) { CppMethodCodeNode methodCodeNode = (CppMethodCodeNode)node; var method = methodCodeNode.Method; var type = method.OwningType; List<MethodDesc> methodList; if (!_methodLists.TryGetValue(type, out methodList)) { GetCppSignatureTypeName(type); methodList = new List<MethodDesc>(); _methodLists.Add(type, methodList); } methodList.Add(method); } else if (node is EETypeNode) { GetCppSignatureTypeName(((EETypeNode)node).Type); } } } public void OutputCode(IEnumerable<DependencyNode> nodes, MethodDesc entrypoint) { BuildMethodLists(nodes); ExpandTypes(); Out.WriteLine("#include \"common.h\""); Out.WriteLine(); Out.Write("/* Forward type definitions */"); OutputTypes(false); Out.WriteLine(); Out.WriteLine(); Out.Write("/* Type definitions */"); OutputTypes(true); var sb = new CppGenerationBuffer(); foreach (var externC in _externCSignatureMap) { string importName = externC.Key; // TODO: hacky special-case if (importName != "memmove" && importName != "malloc") // some methods are already declared by the CRT headers { sb.AppendLine(); sb.Append(GetCppMethodDeclaration(null, false, importName, externC.Value)); } } Out.Write(sb.ToString()); sb.Clear(); foreach (var t in _cppSignatureNames.Keys) { // TODO: Enable once the dependencies are tracked for arrays // if (((DependencyNode)_compilation.NodeFactory.ConstructedTypeSymbol(t)).Marked) if (!t.IsPointer && !t.IsByRef) { sb.AppendLine(); sb.Append(GetCodeForType(t)); } List<MethodDesc> methodList; if (_methodLists.TryGetValue(t, out methodList)) { foreach (var m in methodList) { var methodCodeNode = (CppMethodCodeNode)_compilation.NodeFactory.MethodEntrypoint(m); sb.AppendLine(); sb.Append(methodCodeNode.CppCode); var alternateName = _compilation.NodeFactory.GetSymbolAlternateName(methodCodeNode); if (alternateName != null) { sb.AppendLine(); sb.Append(GetCppMethodDeclaration(m, true, alternateName)); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); if (!m.Signature.ReturnType.IsVoid) { sb.Append("return "); } sb.Append(GetCppMethodDeclarationName(m.OwningType, GetCppMethodName(m))); sb.Append("("); sb.Append(GetCppMethodCallParamList(m)); sb.Append(");"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); } } } } Out.Write(sb.ToString()); sb.Clear(); if (entrypoint != null) { // Stub for main method sb.AppendLine(); if (_compilation.TypeSystemContext.Target.OperatingSystem == TargetOS.Windows) { sb.Append("int wmain(int argc, wchar_t * argv[]) { "); } else { sb.Append("int main(int argc, char * argv[]) {"); } sb.Indent(); sb.AppendLine(); sb.Append("if (__initialize_runtime() != 0)"); sb.Indent(); sb.AppendLine(); sb.Append("return -1;"); sb.Exdent(); sb.AppendEmptyLine(); sb.AppendLine(); sb.Append("ReversePInvokeFrame frame;"); sb.AppendLine(); sb.Append("__reverse_pinvoke(&frame);"); sb.AppendEmptyLine(); sb.AppendLine(); sb.Append("int ret = "); sb.Append(GetCppMethodDeclarationName(entrypoint.OwningType, GetCppMethodName(entrypoint))); sb.Append("(argc-1, (intptr_t)(argv+1));"); sb.AppendEmptyLine(); sb.AppendLine(); sb.Append("__reverse_pinvoke_return(&frame);"); sb.AppendLine(); sb.Append("__shutdown_runtime();"); sb.AppendLine(); sb.Append("return ret;"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); } Out.Write(sb.ToString()); sb.Clear(); Out.Dispose(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class PatternMatcherTests { [Fact] public void BreakIntoCharacterParts_EmptyIdentifier() { VerifyBreakIntoCharacterParts(string.Empty, Array.Empty<string>()); } [Fact] public void BreakIntoCharacterParts_SimpleIdentifier() { VerifyBreakIntoCharacterParts("foo", "foo"); } [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifier() { VerifyBreakIntoCharacterParts("_foo", "_", "foo"); } [Fact] public void BreakIntoCharacterParts_UnderscoredIdentifier() { VerifyBreakIntoCharacterParts("f_oo", "f", "_", "oo"); } [Fact] public void BreakIntoCharacterParts_PostfixUnderscoredIdentifier() { VerifyBreakIntoCharacterParts("foo_", "foo", "_"); } [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifierWithCapital() { VerifyBreakIntoCharacterParts("_Foo", "_", "Foo"); } [Fact] public void BreakIntoCharacterParts_MUnderscorePrefixed() { VerifyBreakIntoCharacterParts("m_foo", "m", "_", "foo"); } [Fact] public void BreakIntoCharacterParts_CamelCaseIdentifier() { VerifyBreakIntoCharacterParts("FogBar", "Fog", "Bar"); } [Fact] public void BreakIntoCharacterParts_MixedCaseIdentifier() { VerifyBreakIntoCharacterParts("fogBar", "fog", "Bar"); } [Fact] public void BreakIntoCharacterParts_TwoCharacterCapitalIdentifier() { VerifyBreakIntoCharacterParts("UIElement", "U", "I", "Element"); } [Fact] public void BreakIntoCharacterParts_NumberSuffixedIdentifier() { VerifyBreakIntoCharacterParts("Foo42", "Foo", "42"); } [Fact] public void BreakIntoCharacterParts_NumberContainingIdentifier() { VerifyBreakIntoCharacterParts("Fog42Bar", "Fog", "42", "Bar"); } [Fact] public void BreakIntoCharacterParts_NumberPrefixedIdentifier() { // 42Bar is not a valid identifier in either C# or VB, but it is entirely conceivable the user might be // typing it trying to do a substring match VerifyBreakIntoCharacterParts("42Bar", "42", "Bar"); } [Fact] [WorkItem(544296)] public void BreakIntoWordParts_VerbatimIdentifier() { VerifyBreakIntoWordParts("@int:", "int"); } [Fact] [WorkItem(537875)] public void BreakIntoWordParts_AllCapsConstant() { VerifyBreakIntoWordParts("C_STYLE_CONSTANT", "C", "_", "STYLE", "_", "CONSTANT"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_SingleLetterPrefix1() { VerifyBreakIntoWordParts("UInteger", "U", "Integer"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_SingleLetterPrefix2() { VerifyBreakIntoWordParts("IDisposable", "I", "Disposable"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_TwoCharacterCapitalIdentifier() { VerifyBreakIntoWordParts("UIElement", "UI", "Element"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_XDocument() { VerifyBreakIntoWordParts("XDocument", "X", "Document"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_XMLDocument1() { VerifyBreakIntoWordParts("XMLDocument", "XML", "Document"); } [Fact] public void BreakIntoWordParts_XMLDocument2() { VerifyBreakIntoWordParts("XmlDocument", "Xml", "Document"); } [Fact] public void BreakIntoWordParts_TwoUppercaseCharacters() { VerifyBreakIntoWordParts("SimpleUIElement", "Simple", "UI", "Element"); } private void VerifyBreakIntoWordParts(string original, params string[] parts) { AssertEx.Equal(parts, BreakIntoWordParts(original)); } private void VerifyBreakIntoCharacterParts(string original, params string[] parts) { AssertEx.Equal(parts, BreakIntoCharacterParts(original)); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveExact() { var match = TryMatchSingleWordPattern("Foo", "Foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_SingleWordPreferCaseSensitiveExactInsensitive() { var match = TryMatchSingleWordPattern("foo", "Foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitivePrefix() { var match = TryMatchSingleWordPattern("Foo", "Fo"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitivePrefixCaseInsensitive() { var match = TryMatchSingleWordPattern("Foo", "fo"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchSimple() { var match = TryMatchSingleWordPattern("FogBar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); Assert.InRange((int)match.Value.CamelCaseWeight, 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchPartialPattern() { var match = TryMatchSingleWordPattern("FogBar", "FoB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern1() { var match = TryMatchSingleWordPattern("FogBar", "FBB"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern2() { var match = TryMatchSingleWordPattern("FogBar", "FoooB"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_CamelCaseMatchPartiallyUnmatched() { var match = TryMatchSingleWordPattern("FogBarBaz", "FZ"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_CamelCaseMatchCompletelyUnmatched() { var match = TryMatchSingleWordPattern("FogBarBaz", "ZZ"); Assert.Null(match); } [Fact] [WorkItem(544975)] public void TryMatchSingleWordPattern_TwoUppercaseCharacters() { var match = TryMatchSingleWordPattern("SimpleUIElement", "SiUI"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.True(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern() { var match = TryMatchSingleWordPattern("FogBar", "b"); Assert.Equal(PatternMatchKind.Substring, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern2() { var match = TryMatchSingleWordPattern("FogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName() { var match = TryMatchSingleWordPattern("_fogBar", "_fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName2() { var match = TryMatchSingleWordPattern("_fogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredNameInsensitive() { var match = TryMatchSingleWordPattern("_FogBar", "_fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore() { var match = TryMatchSingleWordPattern("Fog_Bar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore2() { var match = TryMatchSingleWordPattern("Fog_Bar", "F_B"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore3() { var match = TryMatchSingleWordPattern("Fog_Bar", "F__B"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore4() { var match = TryMatchSingleWordPattern("Fog_Bar", "f_B"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore5() { var match = TryMatchSingleWordPattern("Fog_Bar", "F_b"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights1() { var match1 = TryMatchSingleWordPattern("FogBarBaz", "FB"); var match2 = TryMatchSingleWordPattern("FooFlobBaz", "FB"); // We should prefer something that starts at the beginning if possible Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights2() { var match1 = TryMatchSingleWordPattern("BazBarFooFooFoo", "FFF"); var match2 = TryMatchSingleWordPattern("BazFogBarFooFoo", "FFF"); // Contiguous things should also be preferred Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights3() { var match1 = TryMatchSingleWordPattern("FogBarFooFoo", "FFF"); var match2 = TryMatchSingleWordPattern("BarFooFooFoo", "FFF"); // The weight of being first should be greater than the weight of being contiguous Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals() { var match = TryMatchSingleWordPattern("Foo", "foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals2() { var match = TryMatchSingleWordPattern("Foo", "Foo"); // Since it's actually case sensitive, we'll report it as such even though we didn't prefer it Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix() { var match = TryMatchSingleWordPattern("FogBar", "fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix2() { var match = TryMatchSingleWordPattern("FogBar", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase1() { var match = TryMatchSingleWordPattern("FogBar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase2() { var match = TryMatchSingleWordPattern("FogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase3() { var match = TryMatchSingleWordPattern("fogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveWhenPrefix() { var match = TryMatchSingleWordPattern("fogBarFoo", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveWhenPrefix() { var match = TryMatchSingleWordPattern("fogBarFoo", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } private void AssertContainsType(PatternMatchKind type, IEnumerable<PatternMatch> results) { Assert.True(results.Any(r => r.Kind == type)); } [Fact] public void MatchMultiWordPattern_ExactWithLowercase() { var match = TryMatchMultiWordPattern("AddMetadataReference", "addmetadatareference"); AssertContainsType(PatternMatchKind.Exact, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "metadata"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Metadata"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "A"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "M"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoLowercaseWords() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add metadata"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersSeparateWords() { var match = TryMatchMultiWordPattern("AddMetadataReference", "A M"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersOneWord() { var match = TryMatchMultiWordPattern("AddMetadataReference", "AM"); AssertContainsType(PatternMatchKind.CamelCase, match); } [Fact] public void MatchMultiWordPattern_Mixed1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "ref Metadata"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [Fact] public void MatchMultiWordPattern_Mixed2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "ref M"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [Fact] public void MatchMultiWordPattern_MixedCamelCase() { var match = TryMatchMultiWordPattern("AddMetadataReference", "AMRe"); AssertContainsType(PatternMatchKind.CamelCase, match); } [Fact] public void MatchMultiWordPattern_BlankPattern() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", string.Empty)); } [Fact] public void MatchMultiWordPattern_WhitespaceOnlyPattern() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", " ")); } [Fact] public void MatchMultiWordPattern_EachWordSeparately1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately3() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_MixedCasing1() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "mEta")); } [Fact] public void MatchMultiWordPattern_MixedCasing2() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "Data")); } [Fact] public void MatchMultiWordPattern_AsteriskSplit() { var match = TryMatchMultiWordPattern("GetKeyWord", "K*W"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [WorkItem(544628)] [Fact] public void MatchMultiWordPattern_LowercaseSubstring1() { Assert.Null(TryMatchMultiWordPattern("Operator", "a")); } [WorkItem(544628)] [Fact] public void MatchMultiWordPattern_LowercaseSubstring2() { var match = TryMatchMultiWordPattern("FooAttribute", "a"); AssertContainsType(PatternMatchKind.Substring, match); Assert.False(match.First().IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_CultureAwareSingleWordPreferCaseSensitiveExactInsensitive() { var previousCulture = Thread.CurrentThread.CurrentCulture; var turkish = CultureInfo.GetCultureInfo("tr-TR"); Thread.CurrentThread.CurrentCulture = turkish; try { var match = TryMatchSingleWordPattern("ioo", "\u0130oo"); // u0130 = Capital I with dot Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } finally { Thread.CurrentThread.CurrentCulture = previousCulture; } } [Fact] public void MatchAllLowerPattern1() { Assert.NotNull(TryMatchSingleWordPattern("FogBarChangedEventArgs", "changedeventargs")); } [Fact] public void MatchAllLowerPattern2() { Assert.Null(TryMatchSingleWordPattern("FogBarChangedEventArgs", "changedeventarrrgh")); } [Fact] public void MatchAllLowerPattern3() { Assert.NotNull(TryMatchSingleWordPattern("ABCDEFGH", "bcd")); } [Fact] public void MatchAllLowerPattern4() { Assert.Null(TryMatchSingleWordPattern("AbcdefghijEfgHij", "efghij")); } private static IList<string> PartListToSubstrings(string identifier, StringBreaks parts) { List<string> result = new List<string>(); for (int i = 0; i < parts.Count; i++) { var span = parts[i]; result.Add(identifier.Substring(span.Start, span.Length)); } return result; } private static IList<string> BreakIntoCharacterParts(string identifier) { return PartListToSubstrings(identifier, StringBreaker.BreakIntoCharacterParts(identifier)); } private static IList<string> BreakIntoWordParts(string identifier) { return PartListToSubstrings(identifier, StringBreaker.BreakIntoWordParts(identifier)); } private static PatternMatch? TryMatchSingleWordPattern(string candidate, string pattern) { return new PatternMatcher(pattern).MatchSingleWordPattern_ForTestingOnly(candidate); } private static IEnumerable<PatternMatch> TryMatchMultiWordPattern(string candidate, string pattern) { return new PatternMatcher(pattern).GetMatches(candidate); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using NDesk.Options; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Util; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("fetch")] [Description("fetch [options] [tfs-remote-id]...")] [RequiresValidGitRepository] public class Fetch : GitTfsCommand { private readonly RemoteOptions remoteOptions; private readonly TextWriter stdout; private readonly Globals globals; private readonly ConfigProperties properties; private readonly AuthorsFile authors; private readonly Labels labels; public Fetch(Globals globals, ConfigProperties properties, TextWriter stdout, RemoteOptions remoteOptions, AuthorsFile authors, Labels labels) { this.globals = globals; this.properties = properties; this.stdout = stdout; this.remoteOptions = remoteOptions; this.authors = authors; this.labels = labels; this.upToChangeSet = -1; } bool FetchAll { get; set; } bool FetchLabels { get; set; } bool FetchParents { get; set; } string BareBranch { get; set; } bool ForceFetch { get; set; } bool ExportMetadatas { get; set; } string ExportMetadatasFile { get; set; } public bool IgnoreBranches { get; set; } public string BatchSizeOption { set { int batchSize; if (!int.TryParse(value, out batchSize)) throw new GitTfsException("error: batch size parameter should be an integer."); properties.BatchSize = batchSize; } } int upToChangeSet { get; set; } public string UpToChangeSetOption { set { int changesetIdParsed; if (!int.TryParse(value, out changesetIdParsed)) throw new GitTfsException("error: up-to parameter should be an integer."); upToChangeSet = changesetIdParsed; } } protected int? InitialChangeset { get; set; } public virtual OptionSet OptionSet { get { return new OptionSet { { "all|fetch-all", "Fetch TFS changesets of all the initialized tfs remotes", v => FetchAll = v != null }, { "parents", "Fetch TFS changesets of the parent(s) initialized tfs remotes", v => FetchParents = v != null }, { "l|with-labels|fetch-labels", "Fetch the labels also when fetching TFS changesets", v => FetchLabels = v != null }, { "b|bare-branch=", "The name of the branch on which the fetch will be done for a bare repository", v => BareBranch = v }, { "force", "Force fetch of tfs changesets when there is ahead commits (ahead commits will be lost!)", v => ForceFetch = v != null }, { "x|export", "Export metadatas", v => ExportMetadatas = v != null }, { "export-work-item-mapping=", "Path to Work-items mapping export file", v => ExportMetadatasFile = v }, { "ignore-branches", "Ignore fetching merged branches when encounter merge changesets", v => IgnoreBranches = v != null }, { "batch-size=", "Size of a the batch of tfs changesets fetched (-1 for all in one batch)", v => BatchSizeOption = v }, { "c|changeset=", "The changeset to clone from (must be a number)", v => InitialChangeset = Convert.ToInt32(v) }, { "t|up-to=", "up-to changeset # (optional, -1 for up to maximum, must be a number, not prefixed with C)", v => UpToChangeSetOption = v } }.Merge(remoteOptions.OptionSet); } } public int Run() { return Run(globals.RemoteId); } public void Run(bool stopOnFailMergeCommit) { Run(stopOnFailMergeCommit, globals.RemoteId); } public int Run(params string[] args) { return Run(false, args); } private int Run(bool stopOnFailMergeCommit, params string[] args) { if (!FetchAll && IgnoreBranches) globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, true.ToString()); var remotesToFetch = GetRemotesToFetch(args).ToList(); foreach (var remote in remotesToFetch) { FetchRemote(stopOnFailMergeCommit, remote); } return 0; } private void FetchRemote(bool stopOnFailMergeCommit, IGitTfsRemote remote) { stdout.WriteLine("Fetching from TFS remote '{0}'...", remote.Id); DoFetch(remote, stopOnFailMergeCommit); if (labels != null && FetchLabels) { stdout.WriteLine("Fetching labels from TFS remote '{0}'...", remote.Id); labels.Run(remote); } } protected virtual void DoFetch(IGitTfsRemote remote, bool stopOnFailMergeCommit) { var bareBranch = string.IsNullOrEmpty(BareBranch) ? remote.Id : BareBranch; // It is possible that we have outdated refs/remotes/tfs/<id>. // E.g. someone already fetched changesets from TFS into another git repository and we've pulled it since // in that case tfs fetch will retrieve same changes again unnecessarily. To prevent it we will scan tree from HEAD and see if newer changesets from // TFS exists (by checking git-tfs-id mark in commit's comments). // The process is similar to bootstrapping. if (!ForceFetch) { if (!remote.Repository.IsBare) remote.Repository.MoveTfsRefForwardIfNeeded(remote); else remote.Repository.MoveTfsRefForwardIfNeeded(remote, bareBranch); } if (!ForceFetch && remote.Repository.IsBare && remote.Repository.HasRef(GitRepository.ShortToLocalName(bareBranch)) && remote.MaxCommitHash != remote.Repository.GetCommit(bareBranch).Sha) { throw new GitTfsException("error : fetch is not allowed when there is ahead commits!", new[] {"Remove ahead commits and retry", "use the --force option (ahead commits will be lost!)"}); } var metadataExportInitializer = new ExportMetadatasInitializer(globals); bool shouldExport = ExportMetadatas || remote.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true"; if (ExportMetadatas) { metadataExportInitializer.InitializeConfig(remote.Repository, ExportMetadatasFile); } metadataExportInitializer.InitializeRemote(remote, shouldExport); try { if (InitialChangeset.HasValue) { properties.InitialChangeset = InitialChangeset.Value; properties.PersistAllOverrides(); remote.QuickFetch(InitialChangeset.Value); remote.Fetch(stopOnFailMergeCommit); } else { remote.Fetch(stopOnFailMergeCommit,upToChangeSet); } } finally { Trace.WriteLine("Cleaning..."); remote.CleanupWorkspaceDirectory(); if (remote.Repository.IsBare) remote.Repository.UpdateRef(GitRepository.ShortToLocalName(bareBranch), remote.MaxCommitHash); } } private IEnumerable<IGitTfsRemote> GetRemotesToFetch(IList<string> args) { IEnumerable<IGitTfsRemote> remotesToFetch; if (FetchParents) remotesToFetch = globals.Repository.GetLastParentTfsCommits("HEAD").Select(commit => commit.Remote); else if (FetchAll) remotesToFetch = globals.Repository.ReadAllTfsRemotes(); else remotesToFetch = args.Select(arg => globals.Repository.ReadTfsRemote(arg)); return remotesToFetch; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudioTools; using IServiceProvider = System.IServiceProvider; namespace Microsoft.PythonTools.Commands { /// <summary> /// Provides the command to send selected text from a buffer to the remote REPL window. /// /// The command supports either sending a selection or sending line-by-line. In line-by-line /// mode the user should be able to just hold down on Alt-Enter and have an entire script /// execute as if they ran it in the interactive window. Focus will continue to remain in /// the active text view. /// /// In selection mode the users selection is executed and focus is transfered to the interactive /// window and their selection remains unchanged. /// </summary> class SendToReplCommand : Command { protected readonly IServiceProvider _serviceProvider; private static string[] _newLineChars = new[] { "\r\n", "\n", "\r" }; private static object _executedLastLine = new object(); public SendToReplCommand(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override async void DoCommand(object sender, EventArgs args) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); var project = activeView.GetProjectAtCaret(_serviceProvider); var analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider); ITextSelection selection = activeView.Selection; ITextSnapshot snapshot = activeView.TextBuffer.CurrentSnapshot; var repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project); string input; bool focusRepl = false; if (selection.StreamSelectionSpan.Length > 0) { // Easy, just send the selection to the interactive window. input = activeView.Selection.StreamSelectionSpan.GetText(); if (!input.EndsWith("\n") && !input.EndsWith("\r")) { input += activeView.Options.GetNewLineCharacter(); } focusRepl = true; } else if (!activeView.Properties.ContainsProperty(_executedLastLine)) { // No selection, and we haven't hit the end of the file in line-by-line mode. // Send the current line, and then move the caret to the next non-blank line. ITextSnapshotLine targetLine = snapshot.GetLineFromPosition(selection.Start.Position); input = targetLine.GetText(); bool moved = false; while (targetLine.LineNumber < snapshot.LineCount - 1) { targetLine = snapshot.GetLineFromLineNumber(targetLine.LineNumber + 1); // skip over blank lines, unless it's the last line, in which case we want to land on it no matter what if (!string.IsNullOrWhiteSpace(targetLine.GetText()) || targetLine.LineNumber == snapshot.LineCount - 1) { activeView.Caret.MoveTo(new SnapshotPoint(snapshot, targetLine.Start)); activeView.Caret.EnsureVisible(); moved = true; break; } } if (!moved) { // There's no where for the caret to go, don't execute the line if // we've already executed it. activeView.Caret.PositionChanged += Caret_PositionChanged; activeView.Properties[_executedLastLine] = _executedLastLine; } } else if ((repl.InteractiveWindow.CurrentLanguageBuffer?.CurrentSnapshot.Length ?? 0) != 0) { // We reached the end of the file but have some text buffered. Execute it now. input = activeView.Options.GetNewLineCharacter(); } else { // We've hit the end of the current text view and executed everything input = null; } if (input != null) { repl.Show(focusRepl); var inputs = repl.InteractiveWindow.Properties.GetOrCreateSingletonProperty( () => new InteractiveInputs(repl.InteractiveWindow, _serviceProvider) ); inputs.Enqueue(input); } // Take focus back if REPL window has stolen it and we're in line-by-line mode. if (!focusRepl && !activeView.HasAggregateFocus) { var adapterService = _serviceProvider.GetComponentModel().GetService<VisualStudio.Editor.IVsEditorAdaptersFactoryService>(); var tv = adapterService.GetViewAdapter(activeView); tv.SendExplicitFocus(); } } private static void Caret_PositionChanged(object sender, CaretPositionChangedEventArgs e) { e.TextView.Properties.RemoveProperty(_executedLastLine); e.TextView.Caret.PositionChanged -= Caret_PositionChanged; } private bool IsRealInterpreter(IPythonInterpreterFactory factory) { if (factory == null) { return false; } var interpreterService = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>(); return interpreterService != null && interpreterService.NoInterpretersValue != factory; } public override int? EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); var empty = activeView.Selection.IsEmpty; Intellisense.VsProjectAnalyzer analyzer; if (activeView != null && (analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider)) != null) { if (activeView.Selection.Mode == TextSelectionMode.Box || analyzer == null || !IsRealInterpreter(analyzer.InterpreterFactory)) { cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } else { cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } } else { cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE); } return VSConstants.S_OK; } public override EventHandler BeforeQueryStatus { get { return (sender, args) => { ((OleMenuCommand)sender).Visible = false; ((OleMenuCommand)sender).Supported = false; }; } } public override int CommandId { get { return (int)PkgCmdIDList.cmdidSendToRepl; } } class InteractiveInputs { private readonly LinkedList<string> _pendingInputs = new LinkedList<string>(); private readonly IServiceProvider _serviceProvider; private readonly IInteractiveWindow _window; public InteractiveInputs(IInteractiveWindow window, IServiceProvider serviceProvider) { _window = window; _serviceProvider = serviceProvider; _window.ReadyForInput += ProcessQueuedInput; } public void Enqueue(string input) { _pendingInputs.AddLast(input); if (!_window.IsRunning) { ProcessQueuedInput(); } } /// <summary> /// Pends the next input line to the current input buffer, optionally executing it /// if it forms a complete statement. /// </summary> private void ProcessQueuedInput() { var textView = _window.TextView; // Process all of our pending inputs until we get a complete statement while (_pendingInputs.First != null) { string current = _pendingInputs.First.Value; _pendingInputs.RemoveFirst(); MoveCaretToEndOfCurrentInput(); var statements = RecombineInput(current); if (statements.Count > 0) { // If there was more than one statement then save those for execution later... var input = statements[0]; for (int i = statements.Count - 1; i > 0; i--) { _pendingInputs.AddFirst(statements[i]); } _window.InsertCode(input); string fullCode = _window.CurrentLanguageBuffer.CurrentSnapshot.GetText(); if (_window.Evaluator.CanExecuteCode(fullCode)) { // the code is complete, execute it now _window.Operations.ExecuteInput(); return; } _window.InsertCode(textView.Options.GetNewLineCharacter()); } } } /// <summary> /// Takes the new input and appends it to any existing input that's been entered so far. The combined /// input is then split into multiple top-level statements that will be executed one-by-one. /// /// Also handles any dedents necessary to make the input a valid input, which usually would only /// apply if we have no input so far. /// </summary> private List<string> RecombineInput(string input) { var textView = _window.TextView; var curLangBuffer = _window.CurrentLanguageBuffer; var analyzer = textView.GetAnalyzerAtCaret(_serviceProvider); if (analyzer == null) { return new List<string>(); } var version = analyzer.InterpreterFactory.Configuration.Version.ToLanguageVersion(); // Combine the current input text with the newly submitted text. This will prevent us // from dedenting code when doing line-by-line submissions of things like: // if True: // x = 1 // // So that we don't dedent "x = 1" when we submit it by its self. string newText = input; var curText = curLangBuffer.CurrentSnapshot.GetText(); var combinedText = curText + newText; var oldLineCount = curText.Split(_newLineChars, StringSplitOptions.None).Length - 1; // The split and join will not alter the number of lines that are fed in and returned but // may change the text by dedenting it if we hadn't submitted the "if True:" in the // code above. var split = ReplEditFilter.SplitAndDedent(combinedText); var joinedLines = ReplEditFilter.JoinToCompleteStatements(split, version, false); // Remove any of the lines that were previously inputted into the buffer and also // remove any extra newlines in the submission. List<string> res = new List<string>(); foreach (var inputLine in joinedLines) { var actualLines = inputLine.Split(_newLineChars, StringSplitOptions.None); var newLine = ReplEditFilter.FixEndingNewLine( string.Join( textView.Options.GetNewLineCharacter(), actualLines.Skip(oldLineCount) ) ); res.Add(newLine); oldLineCount -= actualLines.Count(); if (oldLineCount < 0) { oldLineCount = 0; } } return res; } private void MoveCaretToEndOfCurrentInput() { var textView = _window.TextView; var curLangBuffer = _window.CurrentLanguageBuffer; // Sending to the interactive window is like appending the input to the end, we don't // respect the current caret position or selection. We use InsertCode which uses the // current caret position, so first we need to ensure the caret is in the input buffer, // otherwise inserting code does nothing. SnapshotPoint? viewPoint = textView.BufferGraph.MapUpToBuffer( new SnapshotPoint(curLangBuffer.CurrentSnapshot, curLangBuffer.CurrentSnapshot.Length), PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextBuffer ); if (!viewPoint.HasValue) { // Unable to map language buffer to view. // Try moving caret to the end of the view then. viewPoint = new SnapshotPoint( textView.TextBuffer.CurrentSnapshot, textView.TextBuffer.CurrentSnapshot.Length ); } textView.Caret.MoveTo(viewPoint.Value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal struct AidContainer { internal static readonly AidContainer NullAidContainer = default(AidContainer); private object _value; public AidContainer(FileRecord file) { _value = file; } } internal sealed class BSYMMGR { private HashSet<KAID> bsetGlobalAssemblies; // Assemblies in the global alias. // Special nullable members. public PropertySymbol propNubValue; public MethodSymbol methNubCtor; private readonly SymFactory _symFactory; private readonly MiscSymFactory _miscSymFactory; private readonly NamespaceSymbol _rootNS; // The "root" (unnamed) namespace. // Map from aids to INFILESYMs and EXTERNALIASSYMs private List<AidContainer> ssetAssembly; // Map from aids to MODULESYMs and OUTFILESYMs private NameManager m_nameTable; private SYMTBL tableGlobal; // The hash table for type arrays. private Dictionary<TypeArrayKey, TypeArray> tableTypeArrays; private static readonly TypeArray s_taEmpty = new TypeArray(Array.Empty<CType>()); public BSYMMGR(NameManager nameMgr, TypeManager typeManager) { this.m_nameTable = nameMgr; this.tableGlobal = new SYMTBL(); _symFactory = new SymFactory(this.tableGlobal); _miscSymFactory = new MiscSymFactory(this.tableGlobal); this.ssetAssembly = new List<AidContainer>(); InputFile infileUnres = new InputFile(); infileUnres.SetAssemblyID(KAID.kaidUnresolved); ssetAssembly.Add(new AidContainer(infileUnres)); this.bsetGlobalAssemblies = new HashSet<KAID>(); this.bsetGlobalAssemblies.Add(KAID.kaidThisAssembly); this.tableTypeArrays = new Dictionary<TypeArrayKey, TypeArray>(); _rootNS = _symFactory.CreateNamespace(m_nameTable.Lookup(""), null); GetNsAid(_rootNS, KAID.kaidGlobal); } public void Init() { /* tableTypeArrays.Init(&this->GetPageHeap(), this->getAlloc()); tableNameToSym.Init(this); nsToExtensionMethods.Init(this); // Some root symbols. Name* emptyName = m_nameTable->AddString(L""); rootNS = symFactory.CreateNamespace(emptyName, NULL); // Root namespace nsaGlobal = GetNsAid(rootNS, kaidGlobal); m_infileUnres.name = emptyName; m_infileUnres.isSource = false; m_infileUnres.idLocalAssembly = mdTokenNil; m_infileUnres.SetAssemblyID(kaidUnresolved, allocGlobal); size_t isym; isym = ssetAssembly.Add(&m_infileUnres); ASSERT(isym == 0); */ InitPreLoad(); } public NameManager GetNameManager() { return m_nameTable; } public SYMTBL GetSymbolTable() { return tableGlobal; } public static TypeArray EmptyTypeArray() { return s_taEmpty; } public AssemblyQualifiedNamespaceSymbol GetRootNsAid(KAID aid) { return GetNsAid(_rootNS, aid); } public NamespaceSymbol GetRootNS() { return _rootNS; } public KAID AidAlloc(InputFile sym) { ssetAssembly.Add(new AidContainer(sym)); return (KAID)(ssetAssembly.Count - 1 + KAID.kaidUnresolved); } public BetterType CompareTypes(TypeArray ta1, TypeArray ta2) { if (ta1 == ta2) { return BetterType.Same; } if (ta1.Count != ta2.Count) { // The one with more parameters is more specific. return ta1.Count > ta2.Count ? BetterType.Left : BetterType.Right; } BetterType nTot = BetterType.Neither; for (int i = 0; i < ta1.Count; i++) { CType type1 = ta1[i]; CType type2 = ta2[i]; BetterType nParam = BetterType.Neither; LAgain: if (type1.GetTypeKind() != type2.GetTypeKind()) { if (type1.IsTypeParameterType()) { nParam = BetterType.Right; } else if (type2.IsTypeParameterType()) { nParam = BetterType.Left; } } else { switch (type1.GetTypeKind()) { default: Debug.Assert(false, "Bad kind in CompareTypes"); break; case TypeKind.TK_TypeParameterType: case TypeKind.TK_ErrorType: break; case TypeKind.TK_PointerType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: type1 = type1.GetBaseOrParameterOrElementType(); type2 = type2.GetBaseOrParameterOrElementType(); goto LAgain; case TypeKind.TK_AggregateType: nParam = CompareTypes(type1.AsAggregateType().GetTypeArgsAll(), type2.AsAggregateType().GetTypeArgsAll()); break; } } if (nParam == BetterType.Right || nParam == BetterType.Left) { if (nTot == BetterType.Same || nTot == BetterType.Neither) { nTot = nParam; } else if (nParam != nTot) { return BetterType.Neither; } } } return nTot; } public SymFactory GetSymFactory() { return _symFactory; } public MiscSymFactory GetMiscSymFactory() { return _miscSymFactory; } //////////////////////////////////////////////////////////////////////////////// // Build the data structures needed to make FPreLoad fast. Make sure the // namespaces are created. Compute and sort hashes of the NamespaceSymbol * value and type // name (sans arity indicator). private void InitPreLoad() { for (int i = 0; i < (int)PredefinedType.PT_COUNT; ++i) { NamespaceSymbol ns = GetRootNS(); string name = PredefinedTypeFacts.GetName((PredefinedType)i); int start = 0; while (start < name.Length) { int iDot = name.IndexOf('.', start); if (iDot == -1) break; string sub = (iDot > start) ? name.Substring(start, iDot - start) : name.Substring(start); Name nm = this.GetNameManager().Add(sub); NamespaceSymbol sym = this.LookupGlobalSymCore(nm, ns, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol(); if (sym == null) { ns = _symFactory.CreateNamespace(nm, ns); } else { ns = sym; } start += sub.Length + 1; } } } public Symbol LookupGlobalSymCore(Name name, ParentSymbol parent, symbmask_t kindmask) { return tableGlobal.LookupSym(name, parent, kindmask); } public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask) { return tableGlobal.LookupSym(name, agg, mask); } public static Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask) { Debug.Assert(sym.parent == parent); sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); // Keep traversing the list of symbols with same name and parent. while (sym != null) { if ((kindmask & sym.mask()) > 0) return sym; sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); } return null; } public Name GetNameFromPtrs(object u1, object u2) { // Note: this won't produce the same names as the native logic if (u2 != null) { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}-{1:X}", u1.GetHashCode(), u2.GetHashCode())); } else { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}", u1.GetHashCode())); } } private AssemblyQualifiedNamespaceSymbol GetNsAid(NamespaceSymbol ns, KAID aid) { Name name = GetNameFromPtrs(aid, 0); Debug.Assert(name != null); AssemblyQualifiedNamespaceSymbol nsa = LookupGlobalSymCore(name, ns, symbmask_t.MASK_AssemblyQualifiedNamespaceSymbol).AsAssemblyQualifiedNamespaceSymbol(); if (nsa == null) { // Create a new one. nsa = _symFactory.CreateNamespaceAid(name, ns, aid); } Debug.Assert(nsa.GetNS() == ns); return nsa; } //////////////////////////////////////////////////////////////////////////////// // Allocate a type array; used to represent a parameter list. // We use a hash table to make sure that allocating the same type array twice // returns the same value. This does two things: // // 1) Save a lot of memory. // 2) Make it so parameter lists can be compared by a simple pointer comparison // 3) Allow us to associate a token with each signature for faster metadata emit private struct TypeArrayKey : IEquatable<TypeArrayKey> { private readonly CType[] _types; private readonly int _hashCode; public TypeArrayKey(CType[] types) { _types = types; _hashCode = 0; for (int i = 0, n = types.Length; i < n; i++) { _hashCode ^= types[i].GetHashCode(); } } public bool Equals(TypeArrayKey other) { CType[] types = _types; CType[] otherTypes = other._types; if (otherTypes == types) { return true; } if (other._hashCode != _hashCode || otherTypes.Length != types.Length) { return false; } for (int i = 0; i < types.Length; i++) { if (!types[i].Equals(otherTypes[i])) { return false; } } return true; } #if DEBUG [ExcludeFromCodeCoverage] // Typed overload should always be the method called. #endif public override bool Equals(object obj) { Debug.Fail("Sub-optimal overload called. Check if this can be avoided."); return obj is TypeArrayKey && Equals((TypeArrayKey)obj); } public override int GetHashCode() { return _hashCode; } } public TypeArray AllocParams(int ctype, CType[] prgtype) { if (ctype == 0) { return s_taEmpty; } Debug.Assert(ctype == prgtype.Length); return AllocParams(prgtype); } public TypeArray AllocParams(int ctype, TypeArray array, int offset) { CType[] types = array.Items; CType[] newTypes = new CType[ctype]; Array.ConstrainedCopy(types, offset, newTypes, 0, ctype); return AllocParams(newTypes); } public TypeArray AllocParams(params CType[] types) { if (types == null || types.Length == 0) { return s_taEmpty; } TypeArrayKey key = new TypeArrayKey(types); TypeArray result; if (!tableTypeArrays.TryGetValue(key, out result)) { result = new TypeArray(types); tableTypeArrays.Add(key, result); } return result; } private TypeArray ConcatParams(CType[] prgtype1, CType[] prgtype2) { CType[] combined = new CType[prgtype1.Length + prgtype2.Length]; Array.Copy(prgtype1, 0, combined, 0, prgtype1.Length); Array.Copy(prgtype2, 0, combined, prgtype1.Length, prgtype2.Length); return AllocParams(combined); } public TypeArray ConcatParams(TypeArray pta1, TypeArray pta2) { return ConcatParams(pta1.Items, pta2.Items); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataMemberTests : CSharpTestBase { private const string VTableGapClassIL = @" .class public auto ansi beforefieldinit Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void _VtblGap1_1() cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap2_1() cil managed { ret } .method public hidebysig specialname instance void set_GetterIsGap(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 get_SetterIsGap() cil managed { ret } .method public hidebysig specialname instance void _VtblGap3_1(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap4_1() cil managed { ret } .method public hidebysig specialname instance void _VtblGap5_1(int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .property instance int32 GetterIsGap() { .get instance int32 Class::_VtblGap2_1() .set instance void Class::set_GetterIsGap(int32) } // end of property Class::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Class::get_SetterIsGap() .set instance void Class::_VtblGap3_1(int32) } // end of property Class::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Class::_VtblGap4_1() .set instance void Class::_VtblGap5_1(int32) } // end of property Class::BothAccessorsAreGaps } // end of class Class "; private const string VTableGapInterfaceIL = @" .class interface public abstract auto ansi Interface { .method public hidebysig newslot specialname rtspecialname abstract virtual instance void _VtblGap1_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap2_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_GetterIsGap(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 get_SetterIsGap() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap3_1(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap4_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap5_1(int32 'value') cil managed { } .property instance int32 GetterIsGap() { .get instance int32 Interface::_VtblGap2_1() .set instance void Interface::set_GetterIsGap(int32) } // end of property Interface::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Interface::get_SetterIsGap() .set instance void Interface::_VtblGap3_1(int32) } // end of property Interface::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Interface::_VtblGap4_1() .set instance void Interface::_VtblGap5_1(int32) } // end of property Interface::BothAccessorsAreGaps } // end of class Interface "; [WorkItem(537346, "DevDiv")] [Fact] public void MetadataMethodSymbolCtor01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var type1 = ns1.GetTypeMembers("StringComparer").Single() as NamedTypeSymbol; var ctor = type1.InstanceConstructors.Single(); Assert.Equal(type1, ctor.ContainingSymbol); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name); Assert.Equal(SymbolKind.Method, ctor.Kind); Assert.Equal(MethodKind.Constructor, ctor.MethodKind); Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility); Assert.True(ctor.IsDefinition); Assert.False(ctor.IsStatic); Assert.False(ctor.IsSealed); Assert.False(ctor.IsOverride); Assert.False(ctor.IsExtensionMethod); Assert.True(ctor.ReturnsVoid); Assert.False(ctor.IsVararg); // Bug - 2067 Assert.Equal("System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()); Assert.Equal(0, ctor.TypeParameters.Length); Assert.Equal("Void", ctor.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537345, "DevDiv")] [Fact] public void MetadataMethodSymbol01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); // 4 overloads Assert.Equal(4, members.Length); var member1 = members.Last() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(class1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); Assert.Equal(MethodKind.Ordinary, member1.MethodKind); Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility); Assert.True(member1.IsDefinition); Assert.True(member1.IsStatic); Assert.False(member1.IsAbstract); Assert.False(member1.IsSealed); Assert.False(member1.IsVirtual); Assert.False(member1.IsOverride); // Bug - // Assert.True(member1.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl // Assert.False(member1.IsExtensionMethod); Assert.False(member1.ReturnsVoid); Assert.False(member1.IsVararg); var fullName = "System.Boolean Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(System.String pwzFilePath, System.String pwzKeyContainer, System.Byte[] bKeyBlob, System.Int32 cbKeyBlob, ref System.IntPtr ppbSignatureBlob, out System.Int32 pcbSignatureBlob)"; Assert.Equal(fullName, member1.ToTestDisplayString()); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member1.TypeParameters.Length); Assert.Equal(6, member1.Parameters.Length); Assert.Equal("Boolean", member1.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(527150, "DevDiv")] [WorkItem(527151, "DevDiv")] [Fact] public void MetadataParameterSymbol01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = (ns1.GetMembers("Runtime").Single() as NamespaceSymbol).GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns2.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); var member1 = members.Last() as MethodSymbol; Assert.Equal(6, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; var p3 = member1.Parameters[2] as ParameterSymbol; var p4 = member1.Parameters[3] as ParameterSymbol; var p5 = member1.Parameters[4] as ParameterSymbol; var p6 = member1.Parameters[5] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(class1, p1.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p1.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("pwzFilePath", p1.Name); Assert.Equal("System.String pwzKeyContainer", p2.ToTestDisplayString()); Assert.Equal("String", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.Equal("System.Byte[] bKeyBlob", p3.ToTestDisplayString()); Assert.Equal("System.Byte[]", p3.Type.ToTestDisplayString()); //array types do not have names - use ToTestDisplayString Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p3.IsOverride); Assert.False(p3.IsParams); Assert.False(p4.IsOptional); Assert.False(p4.HasExplicitDefaultValue); // Not Impl - out of scope // Assert.Null(p4.DefaultValue); Assert.Equal("ppbSignatureBlob", p5.Name); Assert.Equal("IntPtr", p5.Type.Name); Assert.Equal(RefKind.Ref, p5.RefKind); Assert.Equal("out System.Int32 pcbSignatureBlob", p6.ToTestDisplayString()); Assert.Equal(RefKind.Out, p6.RefKind); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataMethodSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("Add").Single() as MethodSymbol; var member2 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(type1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); // Not Impl //Assert.Equal(MethodKind.Ordinary, member2.MethodKind); Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility); Assert.True(member2.IsDefinition); Assert.False(member1.IsStatic); Assert.True(member1.IsAbstract); Assert.False(member2.IsSealed); Assert.False(member2.IsVirtual); Assert.False(member2.IsOverride); //Assert.True(member1.IsOverloads); //Assert.True(member2.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl //Assert.False(member1.IsExtensionMethod); Assert.True(member1.ReturnsVoid); Assert.False(member2.IsVararg); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member2.TypeParameters.Length); Assert.Equal(2, member1.Parameters.Length); Assert.Equal("Boolean", member2.ReturnType.Name); Assert.Equal("System.Boolean System.Collections.Generic.IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)", member2.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataParameterSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(2, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(type1, p2.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p2.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("value", p2.Name); Assert.Equal("TKey key", p1.ToTestDisplayString()); // Empty // Assert.Equal("TValue", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p1.IsOverride); Assert.False(p1.IsExtern); Assert.False(p1.IsParams); Assert.False(p2.IsOptional); Assert.False(p2.HasExplicitDefaultValue); // Not Impl - Not in M2 scope // Assert.Null(p2.DefaultValue); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537424, "DevDiv")] [Fact] public void MetadataMethodStaticAndInstanceCtor() { var text = @" class C { C() { } static C() { } }"; var compilation = CreateCompilationWithMscorlib(text); Assert.False(compilation.GetDiagnostics().Any()); var classC = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(); // NamedTypeSymbol.Constructors only contains instance constructors Assert.Equal(1, classC.InstanceConstructors.Length); Assert.Equal(1, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); } [ClrOnlyFact] public void ImportDecimalConstantAttribute() { const string ilSource = @" .class public C extends [mscorlib]System.Object { .field public static initonly valuetype [mscorlib]System.Decimal MyDecimalTen .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 ) } // end of class C"; const string cSharpSource = @" class B { static void Main() { var x = C.MyDecimalTen; System.Console.Write(x); } } "; CompileWithCustomILSource(cSharpSource, ilSource, expectedOutput: "10"); } [Fact] public void TypeAndNamespaceWithSameNameButDifferentArities() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B`1<T> { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } [Fact] public void TypeAndNamespaceWithSameNameAndArity() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } // TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472). [WorkItem(546951, "DevDiv")] [Fact] public void VTableGapsNotInSymbolTable() { var csharp = @""; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Class"); AssertEx.None(type.GetMembersUnordered(), symbol => symbol.Name.StartsWith("_VtblGap", StringComparison.Ordinal)); // Dropped entirely. Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length); // Dropped entirely, since both accessors are dropped. Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length); // Getter is silently dropped, property appears valid and write-only. var propWithoutGetter = type.GetMember<PropertySymbol>("GetterIsGap"); Assert.Null(propWithoutGetter.GetMethod); Assert.NotNull(propWithoutGetter.SetMethod); Assert.False(propWithoutGetter.MustCallMethodsDirectly); // Setter is silently dropped, property appears valid and read-only. var propWithoutSetter = type.GetMember<PropertySymbol>("SetterIsGap"); Assert.NotNull(propWithoutSetter.GetMethod); Assert.Null(propWithoutSetter.SetMethod); Assert.False(propWithoutSetter.MustCallMethodsDirectly); } [WorkItem(546951, "DevDiv")] [Fact] public void CallVTableGap() { var csharp = @" class Test { static void Main() { Class c = new Class(); c._VtblGap1_1(); // CS1061 int x; x = c.BothAccessorsAreGaps; // CS1061 c.BothAccessorsAreGaps = x; // CS1061 x = c.GetterIsGap; // CS0154 c.GetterIsGap = x; x = c.SetterIsGap; c.SetterIsGap = x; // CS0200 } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics( // (8,11): error CS1061: 'Class' does not contain a definition for '_VtblGap1_1' and no extension method '_VtblGap1_1' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c._VtblGap1_1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "_VtblGap1_1").WithArguments("Class", "_VtblGap1_1"), // (12,15): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // x = c.BothAccessorsAreGaps; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (13,11): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.BothAccessorsAreGaps = x; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (15,13): error CS0154: The property or indexer 'Class.GetterIsGap' cannot be used in this context because it lacks the get accessor // x = c.GetterIsGap; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.GetterIsGap").WithArguments("Class.GetterIsGap"), // (19,9): error CS0200: Property or indexer 'Class.SetterIsGap' cannot be assigned to -- it is read only // c.SetterIsGap = x; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.SetterIsGap").WithArguments("Class.SetterIsGap")); } [WorkItem(546951, "DevDiv")] [Fact] public void ImplementVTableGap() { var csharp = @" class Empty : Interface { } class Implicit : Interface { public void _VtblGap1_1() { } public int GetterIsGap { get; set; } public int SetterIsGap { get; set; } public int BothAccessorsAreGaps { get; set; } } class Explicit : Interface { void Interface._VtblGap1_1() { } int Interface.GetterIsGap { get; set; } int Interface.SetterIsGap { get; set; } int Interface.BothAccessorsAreGaps { get; set; } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapInterfaceIL); comp.VerifyDiagnostics( // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.SetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.SetterIsGap"), // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.GetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.GetterIsGap"), // (17,33): error CS0550: 'Explicit.Interface.GetterIsGap.get' adds an accessor not found in interface member 'Interface.GetterIsGap' // int Interface.GetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Explicit.Interface.GetterIsGap.get", "Interface.GetterIsGap"), // (18,38): error CS0550: 'Explicit.Interface.SetterIsGap.set' adds an accessor not found in interface member 'Interface.SetterIsGap' // int Interface.SetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Explicit.Interface.SetterIsGap.set", "Interface.SetterIsGap"), // (19,19): error CS0539: 'Explicit.BothAccessorsAreGaps' in explicit interface declaration is not a member of interface // int Interface.BothAccessorsAreGaps { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "BothAccessorsAreGaps").WithArguments("Explicit.BothAccessorsAreGaps"), // (16,20): error CS0539: 'Explicit._VtblGap1_1()' in explicit interface declaration is not a member of interface // void Interface._VtblGap1_1() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "_VtblGap1_1").WithArguments("Explicit._VtblGap1_1()")); } [Fact, WorkItem(1094411, "DevDiv")] public void Bug1094411_01() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilationWithMscorlib("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact, WorkItem(1094411, "DevDiv")] public void Bug1094411_02() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); test1.GetMembers(); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilationWithMscorlib("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); test2.GetMembers(); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } } }
namespace DragAndResize { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// A Canvas which manages dragging of the UIElements it contains. /// </summary> public class DragCanvas : Canvas { #region Data // Stores a reference to the UIElement currently being dragged by the user. UIElement _elementBeingDragged; // Keeps track of where the mouse cursor was when a drag operation began. Point _origCursorLocation; // The offsets from the DragCanvas' edges when the drag operation began. double _origHorizOffset; double _origVertOffset; // Keeps track of which horizontal and vertical offset should be modified for the drag element. bool _modifyLeftOffset; bool _modifyTopOffset; // True if a drag operation is underway, else false. bool _isDragInProgress; #endregion // Data #region Attached Properties #region CanBeDragged public static readonly DependencyProperty CanBeDraggedProperty; public static bool GetCanBeDragged(UIElement uiElement) { if (uiElement == null) { return false; } return (bool)uiElement.GetValue(CanBeDraggedProperty); } public static void SetCanBeDragged(UIElement uiElement, bool value) { if (uiElement != null) { uiElement.SetValue(CanBeDraggedProperty, value); } } #endregion // CanBeDragged #endregion // Attached Properties #region Dependency Properties public static readonly DependencyProperty AllowDraggingProperty; public static readonly DependencyProperty AllowDragOutOfViewProperty; #endregion // Dependency Properties #region Static Constructor static DragCanvas() { AllowDraggingProperty = DependencyProperty.Register( "AllowDragging", typeof(bool), typeof(DragCanvas), new PropertyMetadata(true)); AllowDragOutOfViewProperty = DependencyProperty.Register( "AllowDragOutOfView", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(false)); CanBeDraggedProperty = DependencyProperty.RegisterAttached( "CanBeDragged", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(true)); } #endregion // Static Constructor #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DragCanvas"/> class. /// Initializes a new instance of DragCanvas. UIElements in /// the DragCanvas will immediately be draggable by the user. /// </summary> public DragCanvas() { } #endregion // Constructor #region Interface #region AllowDragging /// <summary> /// Gets/sets whether elements in the DragCanvas should be draggable by the user. /// The default value is true. This is a dependency property. /// </summary> public bool AllowDragging { get { return (bool)this.GetValue(AllowDraggingProperty); } set { this.SetValue(AllowDraggingProperty, value); } } #endregion // AllowDragging #region AllowDragOutOfView /// <summary> /// Gets/sets whether the user should be able to drag elements in the DragCanvas out of /// the viewable area. The default value is false. This is a dependency property. /// </summary> public bool AllowDragOutOfView { get { return (bool)GetValue(AllowDragOutOfViewProperty); } set { SetValue(AllowDragOutOfViewProperty, value); } } #endregion // AllowDragOutOfView #region BringToFront / SendToBack /// <summary> /// Assigns the element a z-index which will ensure that /// it is in front of every other element in the Canvas. /// The z-index of every element whose z-index is between /// the element's old and new z-index will have its z-index /// decremented by one. /// </summary> /// <param name="element"> /// The element to be sent to the front of the z-order. /// </param> public void BringToFront(UIElement element) { UpdateZOrder(element, true); } /// <summary> /// Assigns the element a z-index which will ensure that /// it is behind every other element in the Canvas. /// The z-index of every element whose z-index is between /// the element's old and new z-index will have its z-index /// incremented by one. /// </summary> /// <param name="element"> /// The element to be sent to the back of the z-order. /// </param> public void SendToBack(UIElement element) { UpdateZOrder(element, false); } #endregion // BringToFront / SendToBack #region ElementBeingDragged /// <summary> /// Returns the UIElement currently being dragged, or null. /// </summary> /// <remarks> /// Note to inheritors: This property exposes a protected /// setter which should be used to modify the drag element. /// </remarks> public UIElement ElementBeingDragged { get { if (!AllowDragging) { return null; } else { return _elementBeingDragged; } } protected set { if (_elementBeingDragged != null) { _elementBeingDragged.ReleaseMouseCapture(); } if (!AllowDragging) { _elementBeingDragged = null; } else { if (GetCanBeDragged(value)) { _elementBeingDragged = value; _elementBeingDragged.CaptureMouse(); } else { _elementBeingDragged = null; } } } } #endregion // ElementBeingDragged #region FindCanvasChild /// <summary> /// Walks up the visual tree starting with the specified DependencyObject, /// looking for a UIElement which is a child of the Canvas. If a suitable /// element is not found, null is returned. If the 'depObj' object is a /// UIElement in the Canvas's Children collection, it will be returned. /// </summary> /// <param name="depObj"> /// A DependencyObject from which the search begins. /// </param> public UIElement FindCanvasChild(DependencyObject depObj) { while (depObj != null) { // If the current object is a UIElement which is a child of the // Canvas, exit the loop and return it. UIElement elem = depObj as UIElement; if (elem != null && base.Children.Contains(elem)) { break; } // VisualTreeHelper works with objects of type Visual or Visual3D. // If the current object is not derived from Visual or Visual3D, // then use the LogicalTreeHelper to find the parent element. if (depObj is Visual || depObj is Visual3D) { depObj = VisualTreeHelper.GetParent(depObj); } else { depObj = LogicalTreeHelper.GetParent(depObj); } } return depObj as UIElement; } #endregion // FindCanvasChild #endregion // Interface #region Overrides #region OnPreviewMouseLeftButtonDown protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnPreviewMouseLeftButtonDown(e); _isDragInProgress = false; // Cache the mouse cursor location. _origCursorLocation = e.GetPosition(this); // Walk up the visual tree from the element that was clicked, // looking for an element that is a direct child of the Canvas. ElementBeingDragged = FindCanvasChild(e.Source as DependencyObject); if (ElementBeingDragged == null) { return; } // Get the element's offsets from the four sides of the Canvas. double left = GetLeft(ElementBeingDragged); double right = GetRight(ElementBeingDragged); double top = GetTop(ElementBeingDragged); double bottom = GetBottom(ElementBeingDragged); // Calculate the offset deltas and determine for which sides // of the Canvas to adjust the offsets. _origHorizOffset = ResolveOffset(left, right, out _modifyLeftOffset); _origVertOffset = ResolveOffset(top, bottom, out _modifyTopOffset); // Set the Handled flag so that a control being dragged // does not react to the mouse input. e.Handled = true; _isDragInProgress = true; } #endregion // OnPreviewMouseLeftButtonDown #region OnPreviewMouseMove protected override void OnPreviewMouseMove(MouseEventArgs e) { base.OnPreviewMouseMove(e); // If no element is being dragged, there is nothing to do. if (ElementBeingDragged == null || !_isDragInProgress) { return; } // Get the position of the mouse cursor, relative to the Canvas. Point cursorLocation = e.GetPosition(this); // These values will store the new offsets of the drag element. double newHorizontalOffset, newVerticalOffset; // Determine the horizontal offset. if (_modifyLeftOffset) { newHorizontalOffset = _origHorizOffset + (cursorLocation.X - _origCursorLocation.X); } else { newHorizontalOffset = _origHorizOffset - (cursorLocation.X - _origCursorLocation.X); } // Determine the vertical offset. if (_modifyTopOffset) { newVerticalOffset = _origVertOffset + (cursorLocation.Y - _origCursorLocation.Y); } else { newVerticalOffset = _origVertOffset - (cursorLocation.Y - _origCursorLocation.Y); } if (! AllowDragOutOfView) { CorrectOffsetsToKeepElementInsideCanvas(ref newHorizontalOffset, ref newVerticalOffset); } if (_modifyLeftOffset) { SetLeft(ElementBeingDragged, newHorizontalOffset); } else { SetRight(ElementBeingDragged, newHorizontalOffset); } if (_modifyTopOffset) { SetTop(ElementBeingDragged, newVerticalOffset); } else { SetBottom(ElementBeingDragged, newVerticalOffset); } } void CorrectOffsetsToKeepElementInsideCanvas(ref double newHorizontalOffset, ref double newVerticalOffset) { // Get the bounding rect of the drag element. Rect elemRect = CalculateDragElementRect(newHorizontalOffset, newVerticalOffset); // If the element is being dragged out of the viewable area, // determine the ideal rect location, so that the element is // within the edge(s) of the canvas. bool leftAlign = elemRect.Left < 0 - (elemRect.Width / 2); bool rightAlign = elemRect.Right > ActualWidth + (elemRect.Width / 2); if (leftAlign) { newHorizontalOffset = _modifyLeftOffset ? 0 - (elemRect.Width / 2) : ActualWidth - elemRect.Width; } else if (rightAlign) { newHorizontalOffset = _modifyLeftOffset ? ActualWidth - (elemRect.Width / 2) : 0; } bool topAlign = elemRect.Top < 0 - (elemRect.Height / 2); bool bottomAlign = elemRect.Bottom > ActualHeight + (elemRect.Height / 2); if (topAlign) { newVerticalOffset = _modifyTopOffset ? 0 - (elemRect.Height / 2) : ActualHeight - elemRect.Height; } else if (bottomAlign) { newVerticalOffset = _modifyTopOffset ? ActualHeight - (elemRect.Height / 2) : 0; } } #endregion // OnPreviewMouseMove #region OnHostPreviewMouseUp protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { base.OnPreviewMouseUp(e); // Reset the field whether the left or right mouse button was // released, in case a context menu was opened on the drag element. ElementBeingDragged = null; } #endregion // OnHostPreviewMouseUp #endregion // Host Event Handlers #region CalculateDragElementRect /// <summary> /// Returns a Rect which describes the bounds of the element being dragged. /// </summary> Rect CalculateDragElementRect(double newHorizOffset, double newVertOffset) { if (ElementBeingDragged == null) { throw new InvalidOperationException("ElementBeingDragged is null."); } Size elemSize = ElementBeingDragged.RenderSize; double x, y; if (_modifyLeftOffset) { x = newHorizOffset; } else { x = ActualWidth - newHorizOffset - elemSize.Width; } if (_modifyTopOffset) { y = newVertOffset; } else { y = ActualHeight - newVertOffset - elemSize.Height; } var elemLoc = new Point(x, y); return new Rect(elemLoc, elemSize); } #endregion // CalculateDragElementRect #region ResolveOffset /// <summary> /// Determines one component of a UIElement's location /// within a Canvas (either the horizontal or vertical offset). /// </summary> /// <param name="side1"> /// The value of an offset relative to a default side of the /// Canvas (i.e. top or left). /// </param> /// <param name="side2"> /// The value of the offset relative to the other side of the /// Canvas (i.e. bottom or right). /// </param> /// <param name="useSide1"> /// Will be set to true if the returned value should be used /// for the offset from the side represented by the 'side1' /// parameter. Otherwise, it will be set to false. /// </param> static double ResolveOffset(double side1, double side2, out bool useSide1) { // If the Canvas.Left and Canvas.Right attached properties // are specified for an element, the 'Left' value is honored. // The 'Top' value is honored if both Canvas.Top and // Canvas.Bottom are set on the same element. If one // of those attached properties is not set on an element, // the default value is Double.NaN. useSide1 = true; double result; if (Double.IsNaN(side1)) { if (Double.IsNaN(side2)) { // Both sides have no value, so set the // first side to a value of zero. result = 0; } else { result = side2; useSide1 = false; } } else { result = side1; } return result; } #endregion // ResolveOffset /// <summary> /// Helper method used by the BringToFront and SendToBack methods. /// </summary> /// <param name="element"> /// The element to bring to the front or send to the back. /// </param> /// <param name="bringToFront"> /// Pass true if calling from BringToFront, else false. /// </param> void UpdateZOrder(UIElement element, bool bringToFront) { if (element == null) { throw new ArgumentNullException("element"); } if (!base.Children.Contains(element)) { throw new ArgumentException("Must be a child element of the Canvas.", "element"); } // Determine the Z-Index for the target UIElement. int elementNewZIndex = -1; if (bringToFront) { foreach (UIElement elem in base.Children) { if (elem.Visibility != Visibility.Collapsed) { ++elementNewZIndex; } } } else { elementNewZIndex = 0; } // Determine if the other UIElements' Z-Index // should be raised or lowered by one. int offset = (elementNewZIndex == 0) ? +1 : -1; int elementCurrentZIndex = GetZIndex(element); // Update the Z-Index of every UIElement in the Canvas. foreach (UIElement childElement in base.Children) { if (childElement == element) { SetZIndex(element, elementNewZIndex); } else { int zIndex = GetZIndex(childElement); // Only modify the z-index of an element if it is // in between the target element's old and new z-index. if (bringToFront && elementCurrentZIndex < zIndex || !bringToFront && zIndex < elementCurrentZIndex) { SetZIndex(childElement, zIndex + offset); } } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace NowinTests { using OwinApp = Func<IDictionary<string, object>, Task>; public abstract class NowinTestsBase { const string HostValue = "localhost:8080"; const string SampleContent = "Hello World"; protected abstract string HttpClientAddress { get; } protected abstract string ExpectedRequestScheme { get; } readonly OwinApp _appThrow = env => { throw new InvalidOperationException(); }; [Test] public void NowinTrivial() { using (CreateServer(_appThrow)) { } } [Test] public void EmptyAppRespondOk() { var listener = CreateServer(env => Task.Delay(0)); var response = SendGetRequest(listener, HttpClientAddress); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content.Headers.ContentLength); Assert.AreEqual(0, response.Content.Headers.ContentLength.Value); Assert.AreEqual("Nowin", response.Headers.Server.First().Product.Name); Assert.True(response.Headers.Date.HasValue); } [Test] public void EmptyAppAnd2Requests() { var listener = CreateServer(env => Task.Delay(0)); using (listener) { var client = new HttpClient(); string result = client.GetStringAsync(HttpClientAddress).Result; Assert.AreEqual("", result); result = client.GetStringAsync(HttpClientAddress).Result; Assert.AreEqual("", result); } } [Test] public void ThrowAppRespond500() { var listener = CreateServer(_appThrow); var response = SendGetRequest(listener, HttpClientAddress); Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); Assert.NotNull(response.Content.Headers.ContentLength); Assert.AreEqual(0, response.Content.Headers.ContentLength.Value); } [Test] public void AsyncThrowAppRespond500() { var callCancelled = false; var listener = CreateServer( async env => { GetCallCancelled(env).Register(() => callCancelled = true); await Task.Delay(1); throw new InvalidOperationException(); }); var response = SendGetRequest(listener, HttpClientAddress); Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); Assert.NotNull(response.Content.Headers.ContentLength); Assert.AreEqual(0, response.Content.Headers.ContentLength.Value); Assert.True(callCancelled); } [Test] public void PostEchoAppWorks() { var callCancelled = false; var listener = CreateServer( async env => { GetCallCancelled(env).Register(() => callCancelled = true); var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Content-Length", requestHeaders["Content-Length"]); var requestStream = env.Get<Stream>("owin.RequestBody"); var responseStream = env.Get<Stream>("owin.ResponseBody"); var buffer = new MemoryStream(); await requestStream.CopyToAsync(buffer, 1024); buffer.Seek(0, SeekOrigin.Begin); await buffer.CopyToAsync(responseStream, 1024); }); using (listener) { var client = new HttpClient(); const string dataString = SampleContent; var response = client.PostAsync(HttpClientAddress, new StringContent(dataString)).Result; response.EnsureSuccessStatusCode(); Assert.NotNull(response.Content.Headers.ContentLength); Assert.AreEqual(dataString.Length, response.Content.Headers.ContentLength.Value); Assert.AreEqual(dataString, response.Content.ReadAsStringAsync().Result); Assert.False(callCancelled); } } [Test] public void ConnectionClosedAfterStartReturningResponseAndThrowing() { bool callCancelled = false; var listener = CreateServer( env => { GetCallCancelled(env).Register(() => callCancelled = true); var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Content-Length", new[] { "10" }); var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.WriteByte(0xFF); responseStream.Flush(); throw new InvalidOperationException(); }); try { Assert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress)); } finally { Assert.True(callCancelled); } } [Test] public void ConnectionClosedAfterStartReturningResponseAndAsyncThrowing() { var callCancelled = false; var listener = CreateServer( env => { GetCallCancelled(env).Register(() => callCancelled = true); var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Content-Length", new[] { "10" }); var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.WriteByte(0xFF); responseStream.Flush(); var tcs = new TaskCompletionSource<bool>(); tcs.SetException(new InvalidOperationException()); return tcs.Task; }); try { Assert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress)); } finally { Assert.True(callCancelled); } } [Test] [TestCase("", "/", "")] [TestCase("path?query", "/path", "query")] [TestCase("pathBase/path?query", "/pathBase/path", "query")] public void PathAndQueryParsing(string clientString, string expectedPath, string expectedQuery) { clientString = HttpClientAddress + clientString; var listener = CreateServerSync(env => { Assert.AreEqual("", env["owin.RequestPathBase"]); Assert.AreEqual(expectedPath, env["owin.RequestPath"]); Assert.AreEqual(expectedQuery, env["owin.RequestQueryString"]); }); using (listener) { var client = new HttpClient(); var result = client.GetAsync(clientString).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); } } [Test] public void CallParametersEmptyGetRequest() { var listener = CreateServerSync( env => { Assert.NotNull(env); Assert.NotNull(env.Get<Stream>("owin.RequestBody")); Assert.NotNull(env.Get<Stream>("owin.ResponseBody")); Assert.NotNull(env.Get<IDictionary<string, string[]>>("owin.RequestHeaders")); Assert.NotNull(env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders")); }); SendGetRequest(listener, HttpClientAddress); } [Test] public void EnvironmentEmptyGetRequest() { var listener = CreateServerSync( env => { object ignored; Assert.True(env.TryGetValue("owin.RequestMethod", out ignored)); Assert.AreEqual("GET", env["owin.RequestMethod"]); Assert.True(env.TryGetValue("owin.RequestPath", out ignored)); Assert.AreEqual("/SubPath", env["owin.RequestPath"]); Assert.True(env.TryGetValue("owin.RequestPathBase", out ignored)); Assert.AreEqual("", env["owin.RequestPathBase"]); Assert.True(env.TryGetValue("owin.RequestProtocol", out ignored)); Assert.AreEqual("HTTP/1.1", env["owin.RequestProtocol"]); Assert.True(env.TryGetValue("owin.RequestQueryString", out ignored)); Assert.AreEqual("QueryString", env["owin.RequestQueryString"]); Assert.True(env.TryGetValue("owin.RequestScheme", out ignored)); Assert.AreEqual(ExpectedRequestScheme, env["owin.RequestScheme"]); Assert.True(env.TryGetValue("owin.Version", out ignored)); Assert.AreEqual("1.0", env["owin.Version"]); Assert.True(env.TryGetValue("server.IsLocal", out ignored)); Assert.AreEqual(true, env["server.IsLocal"]); Assert.True(env.TryGetValue("server.RemoteIpAddress", out ignored)); Assert.AreEqual("127.0.0.1", env["server.RemoteIpAddress"]); Assert.True(env.TryGetValue("server.LocalIpAddress", out ignored)); Assert.AreEqual("127.0.0.1", env["server.LocalIpAddress"]); Assert.True(env.TryGetValue("server.RemotePort", out ignored)); Assert.True(env.TryGetValue("server.LocalPort", out ignored)); Assert.False(env.TryGetValue("websocket.Accept", out ignored)); }); Assert.AreEqual(HttpStatusCode.OK, SendGetRequest(listener, HttpClientAddress + "SubPath?QueryString").StatusCode); } [Test] public void EnvironmentPost10Request() { var listener = CreateServerSync( env => { object ignored; Assert.True(env.TryGetValue("owin.RequestMethod", out ignored)); Assert.AreEqual("POST", env["owin.RequestMethod"]); Assert.True(env.TryGetValue("owin.RequestPath", out ignored)); Assert.AreEqual("/SubPath", env["owin.RequestPath"]); Assert.True(env.TryGetValue("owin.RequestPathBase", out ignored)); Assert.AreEqual("", env["owin.RequestPathBase"]); Assert.True(env.TryGetValue("owin.RequestProtocol", out ignored)); Assert.AreEqual("HTTP/1.0", env["owin.RequestProtocol"]); Assert.True(env.TryGetValue("owin.RequestQueryString", out ignored)); Assert.AreEqual("QueryString", env["owin.RequestQueryString"]); Assert.True(env.TryGetValue("owin.RequestScheme", out ignored)); Assert.AreEqual(ExpectedRequestScheme, env["owin.RequestScheme"]); Assert.True(env.TryGetValue("owin.Version", out ignored)); Assert.AreEqual("1.0", env["owin.Version"]); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString") { Content = new StringContent(SampleContent), Version = new Version(1, 0) }; SendRequest(listener, request); } [Test] public void HeadersEmptyGetRequest() { var listener = CreateServerSync( env => { var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); string[] values; Assert.True(requestHeaders.TryGetValue("host", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual(HostValue, values[0]); }); SendGetRequest(listener, HttpClientAddress); } [Test] public void HeadersPostContentLengthRequest() { const string requestBody = SampleContent; var listener = CreateServerSync( env => { var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); string[] values; Assert.True(requestHeaders.TryGetValue("host", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual(HostValue, values[0]); Assert.True(requestHeaders.TryGetValue("Content-length", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual(requestBody.Length.ToString(CultureInfo.InvariantCulture), values[0]); Assert.True(requestHeaders.TryGetValue("exPect", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("100-continue", values[0]); Assert.True(requestHeaders.TryGetValue("Content-Type", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("text/plain; charset=utf-8", values[0]); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString") { Content = new StringContent(requestBody) }; SendRequest(listener, request); } [Test] [TestCase("GET")] [TestCase("POST")] [TestCase("PUT")] [TestCase("DELETE")] [TestCase("HEAD")] [TestCase("OPTIONS")] [TestCase("TRACE")] [TestCase("NOWIN")] public void HttpMethodWorks(string name) { var listener = CreateServerSync( env => Assert.AreEqual(name, env.Get<string>("owin.RequestMethod"))); var request = new HttpRequestMessage(new HttpMethod(name), HttpClientAddress); SendRequest(listener, request); } [Test] public void HeadersPostChunkedRequest() { const string requestBody = SampleContent; var listener = CreateServerSync( env => { var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); string[] values; Assert.True(requestHeaders.TryGetValue("host", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual(HostValue, values[0]); Assert.True(requestHeaders.TryGetValue("Transfer-encoding", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("chunked", values[0]); Assert.True(requestHeaders.TryGetValue("exPect", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("100-continue", values[0]); Assert.True(requestHeaders.TryGetValue("Content-Type", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("text/plain; charset=utf-8", values[0]); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString"); request.Headers.TransferEncodingChunked = true; request.Content = new StringContent(requestBody); SendRequest(listener, request); } [Test] public void BodyPostContentLengthZero() { var listener = CreateServerSync( env => { string[] values; var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); Assert.True(requestHeaders.TryGetValue("Content-length", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("0", values[0]); Assert.NotNull(env.Get<Stream>("owin.RequestBody")); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress) { Content = new StringContent("") }; SendRequest(listener, request); } [Test] public void BodyPostContentLengthX() { var listener = CreateServerSync( env => { string[] values; var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); Assert.True(requestHeaders.TryGetValue("Content-length", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual(SampleContent.Length.ToString(CultureInfo.InvariantCulture), values[0]); var requestBody = env.Get<Stream>("owin.RequestBody"); Assert.NotNull(requestBody); var buffer = new MemoryStream(); requestBody.CopyTo(buffer); Assert.AreEqual(SampleContent.Length, buffer.Length); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress) { Content = new StringContent(SampleContent) }; SendRequest(listener, request); } [Test] public void BodyPostChunkedEmpty() { var listener = CreateServerSync( env => { string[] values; var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); Assert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("chunked", values[0]); var requestBody = env.Get<Stream>("owin.RequestBody"); Assert.NotNull(requestBody); var buffer = new MemoryStream(); requestBody.CopyTo(buffer); Assert.AreEqual(0, buffer.Length); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress); request.Headers.TransferEncodingChunked = true; request.Content = new StringContent(""); SendRequest(listener, request); } [Test] public void BodyPostChunkedX() { var listener = CreateServerSync( env => { string[] values; var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"); Assert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values)); Assert.AreEqual(1, values.Length); Assert.AreEqual("chunked", values[0]); var requestBody = env.Get<Stream>("owin.RequestBody"); Assert.NotNull(requestBody); var buffer = new MemoryStream(); requestBody.CopyTo(buffer); Assert.AreEqual(SampleContent.Length, buffer.Length); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress); request.Headers.TransferEncodingChunked = true; request.Content = new StringContent(SampleContent); SendRequest(listener, request); } [Test] public void BodyPostChunkedXClientCloseConnection() { var listener = CreateServerSync( env => { var requestBody = env.Get<Stream>("owin.RequestBody"); var buffer = new MemoryStream(); Assert.Throws<AggregateException>(() => requestBody.CopyTo(buffer)); Assert.True(GetCallCancelled(env).IsCancellationRequested); }); var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress); request.Headers.TransferEncodingChunked = true; request.Content = new StreamContent(new ReadZerosAndThrowAfter(100000)); using (listener) { using (var client = new HttpClient()) { Assert.Throws<AggregateException>(() => client.SendAsync(request, HttpCompletionOption.ResponseContentRead).Wait()); } } } class ReadZerosAndThrowAfter : Stream { readonly int _length; int _pos; public ReadZerosAndThrowAfter(int length) { _length = length; } public override void Flush() { throw new InvalidOperationException(); } public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); } public override void SetLength(long value) { throw new InvalidOperationException(); } public override int Read(byte[] buffer, int offset, int count) { if (_pos + count >= _length) throw new EndOfStreamException(); Array.Clear(buffer, offset, count); _pos += count; return count; } public override void Write(byte[] buffer, int offset, int count) { throw new InvalidOperationException(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _length * 2; } } public override long Position { get { return _pos; } set { throw new InvalidOperationException(); } } } [Test] public void DefaultEmptyResponse() { var listener = CreateServer(call => Task.Delay(0)); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("OK", response.ReasonPhrase); Assert.AreEqual(2, response.Headers.Count()); Assert.False(response.Headers.TransferEncodingChunked.HasValue); Assert.True(response.Headers.Date.HasValue); Assert.AreEqual(1, response.Headers.Server.Count); Assert.AreEqual("", response.Content.ReadAsStringAsync().Result); } } [Test] public void SurviveNullResponseHeaders() { var listener = CreateServer( env => { env["owin.ResponseHeaders"] = null; return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } [Test] public void CustomHeadersArePassedThrough() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Custom1", new[] { "value1a", "value1b" }); responseHeaders.Add("Custom2", new[] { "value2a, value2b" }); responseHeaders.Add("Custom3", new[] { "value3a, value3b", "value3c" }); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(5, response.Headers.Count()); Assert.AreEqual(2, response.Headers.GetValues("Custom1").Count()); Assert.AreEqual("value1a", response.Headers.GetValues("Custom1").First()); Assert.AreEqual("value1b", response.Headers.GetValues("Custom1").Skip(1).First()); Assert.AreEqual(1, response.Headers.GetValues("Custom2").Count()); Assert.AreEqual("value2a, value2b", response.Headers.GetValues("Custom2").First()); Assert.AreEqual(2, response.Headers.GetValues("Custom3").Count()); Assert.AreEqual("value3a, value3b", response.Headers.GetValues("Custom3").First()); Assert.AreEqual("value3c", response.Headers.GetValues("Custom3").Skip(1).First()); } } [Test] public void ReservedHeadersArePassedThrough() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); env.Add("owin.ResponseProtocol", "HTTP/1.0"); responseHeaders.Add("KEEP-alive", new[] { "TRUE" }); responseHeaders.Add("content-length", new[] { "0" }); responseHeaders.Add("www-Authenticate", new[] { "Basic", "NTLM" }); responseHeaders.Add("server", new[] { "cool" }); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(4, response.Headers.Count()); Assert.AreEqual(0, response.Content.Headers.ContentLength); Assert.AreEqual(2, response.Headers.WwwAuthenticate.Count()); Assert.AreEqual("cool", response.Headers.Server.First().Product.Name); // The client does not expose KeepAlive } } [Test] public void ConnectionHeaderIsHonoredAndTransferEncodingIngnored() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Transfer-Encoding", new[] { "ChUnKed" }); responseHeaders.Add("CONNECTION", new[] { "ClOsE" }); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(3, response.Headers.Count()); Assert.AreEqual("", response.Headers.TransferEncoding.ToString()); Assert.False(response.Headers.TransferEncodingChunked.HasValue); Assert.AreEqual("close", response.Headers.Connection.First()); // Normalized by server Assert.NotNull(response.Headers.ConnectionClose); Assert.True(response.Headers.ConnectionClose.Value); } } [Test] public void BadContentLengthIs500() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("content-length", new[] { "-10" }); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); Assert.NotNull(response.Content.Headers.ContentLength); Assert.AreEqual(0, response.Content.Headers.ContentLength.Value); } } [Test] public void CustomReasonPhraseSupported() { var listener = CreateServer( env => { env.Add("owin.ResponseReasonPhrase", SampleContent); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(SampleContent, response.ReasonPhrase); } } [Test] public void BadReasonPhraseIs500() { var listener = CreateServer( env => { env.Add("owin.ResponseReasonPhrase", int.MaxValue); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); } } [Test] public void ResponseProtocolIsIgnored() { var listener = CreateServer( env => { env.Add("owin.ResponseProtocol", "garbage"); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(new Version(1, 1), response.Version); } } [Test] public void SmallResponseBodyWorks() { var listener = CreateServer( env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Write(new byte[10], 0, 10); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(10, response.Content.ReadAsByteArrayAsync().Result.Length); } } [Test] public void TwiceSmallResponseBodyWorks() { var listener = CreateServer( env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Write(new byte[10], 0, 10); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(10, response.Content.ReadAsByteArrayAsync().Result.Length); response.Dispose(); client.Dispose(); client = new HttpClient(); response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(10, response.Content.ReadAsByteArrayAsync().Result.Length); } } [Test] public void LargeResponseBodyWith100AsyncWritesWorks() { OwinApp app = async env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); var pos = 0; for (var i = 0; i < 100; i++) { var buffer = PrepareLargeResponseBuffer(ref pos, 1000); await responseStream.WriteAsync(buffer, 0, buffer.Length); } }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWith1AsyncWriteWorks() { OwinApp app = async env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); var pos = 0; var buffer = PrepareLargeResponseBuffer(ref pos, 100000); await responseStream.WriteAsync(buffer, 0, buffer.Length); }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWith100WritesWorks() { OwinApp app = async env => { await Task.Delay(1); var responseStream = env.Get<Stream>("owin.ResponseBody"); var pos = 0; for (var i = 0; i < 100; i++) { var buffer = PrepareLargeResponseBuffer(ref pos, 1000); responseStream.Write(buffer, 0, buffer.Length); } }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWith1WriteWorks() { OwinApp app = async env => { await Task.Delay(1); var responseStream = env.Get<Stream>("owin.ResponseBody"); var pos = 0; var buffer = PrepareLargeResponseBuffer(ref pos, 100000); responseStream.Write(buffer, 0, buffer.Length); }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWithFlushAsyncAnd1WriteWorks() { OwinApp app = async env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); await responseStream.FlushAsync(); var pos = 0; var buffer = PrepareLargeResponseBuffer(ref pos, 100000); responseStream.Write(buffer, 0, buffer.Length); }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWithFlushAnd1WriteWorks() { OwinApp app = async env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Flush(); var pos = 0; var buffer = PrepareLargeResponseBuffer(ref pos, 100000); responseStream.Write(buffer, 0, buffer.Length); }; CheckLargeBody(app); } [Test] public void LargeResponseBodyWithFlushAnd1WriteAsyncWorks() { OwinApp app = async env => { var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Flush(); var pos = 0; var buffer = PrepareLargeResponseBuffer(ref pos, 100000); await responseStream.WriteAsync(buffer, 0, buffer.Length); }; CheckLargeBody(app); } static byte[] PrepareLargeResponseBuffer(ref int pos, int len) { var buffer = new byte[len]; for (var i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(pos & 0xff); pos++; } return buffer; } void CheckLargeBody(OwinApp app) { var listener = CreateServer(app); using (listener) { var client = new HttpClient(); var response = client.GetAsync(HttpClientAddress).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); var result = response.Content.ReadAsByteArrayAsync().Result; Assert.AreEqual(100000, result.Length); for (var i = 0; i < result.Length; i++) { if (result[i] != (i & 0xff)) Assert.Fail("Response is wrong on {0} byte", i); } } } [Test] public void BodySmallerThanContentLengthClosesConnection() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Content-Length", new[] { "10000" }); var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Write(new byte[9500], 0, 9500); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); Assert.Throws<AggregateException>(() => client.GetAsync(HttpClientAddress).Wait()); } } [Test] public void BodyLargerThanContentLengthClosesConnection() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); responseHeaders.Add("Content-Length", new[] { "10000" }); var responseStream = env.Get<Stream>("owin.ResponseBody"); responseStream.Write(new byte[10500], 0, 10500); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); Assert.Throws<AggregateException>(() => client.GetAsync(HttpClientAddress).Wait()); } } [Test] public void StatusesLessThan200AreInvalid() { var listener = CreateServer( env => { env["owin.ResponseStatusCode"] = 100; return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.PostAsync(HttpClientAddress, new StringContent(SampleContent)).Result; Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); } } [Test] public void BasicOnSendingHeadersWorks() { var listener = CreateServer( env => { env["owin.ResponseReasonPhrase"] = "Custom"; var responseStream = env.Get<Stream>("owin.ResponseBody"); var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state => responseHeaders["custom-header"] = new[] { "customvalue" }, null); responseHeaders["content-length"] = new[] { "10" }; responseStream.Write(new byte[10], 0, 10); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.PostAsync(HttpClientAddress, new StringContent(SampleContent)).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("Custom", response.ReasonPhrase); Assert.AreEqual("customvalue", response.Headers.GetValues("custom-header").First()); Assert.AreEqual(10, response.Content.ReadAsByteArrayAsync().Result.Length); } } [Test] public void DoubleOnSendingHeadersWorks() { var listener = CreateServer( env => { var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"); env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state => responseHeaders["custom-header"] = new[] { (string)state }, "customvalue"); env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state => { responseHeaders["custom-header"] = new[] { "badvalue" }; responseHeaders["custom-header2"] = new[] { "goodvalue" }; }, null); return Task.Delay(0); }); using (listener) { var client = new HttpClient(); var response = client.PostAsync(HttpClientAddress, new StringContent(SampleContent)).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("customvalue", response.Headers.GetValues("custom-header").First()); Assert.AreEqual("goodvalue", response.Headers.GetValues("custom-header2").First()); } } static void SendRequest(IDisposable listener, HttpRequestMessage request) { using (listener) { using (var client = new HttpClient()) { var result = client.SendAsync(request, HttpCompletionOption.ResponseContentRead).Result; result.EnsureSuccessStatusCode(); } } } static CancellationToken GetCallCancelled(IDictionary<string, object> env) { return env.Get<CancellationToken>("owin.CallCancelled"); } static HttpResponseMessage SendGetRequest(IDisposable listener, string address) { using (listener) { var handler = new WebRequestHandler { ServerCertificateValidationCallback = (a, b, c, d) => true, ClientCertificateOptions = ClientCertificateOption.Automatic }; using (var client = new HttpClient(handler)) { return client.GetAsync(address, HttpCompletionOption.ResponseContentRead).Result; } } } protected abstract IDisposable CreateServer(Func<IDictionary<string, object>, Task> app); IDisposable CreateServerSync(Action<IDictionary<string, object>> appSync) { return CreateServer(env => { appSync(env); return Task.Delay(0); }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.AspNetCore.StaticFiles; using OrchardCore.Modules; namespace OrchardCore.FileStorage.AzureBlob { /// <summary> /// Provides an <see cref="IFileStore"/> implementation that targets an underlying Azure Blob Storage account. /// </summary> /// <remarks> /// Azure Blob Storage has very different semantics for directories compared to a local file system, and /// some special consideration is required for make this provider conform to the semantics of the /// <see cref="IFileStore"/> interface and behave in an expected way. /// /// Directories have no physical manifestation in blob storage; we can obtain a reference to them, but /// that reference can be created regardless of whether the directory exists, and it can only be used /// as a scoping container to operate on blobs within that directory namespace. /// /// As a consequence, this provider generally behaves as if any given directory always exists. To /// simulate "creating" a directory (which cannot technically be done in blob storage) this provider creates /// a marker file inside the directory, which makes the directory "exist" and appear when listing contents /// subsequently. This marker file is ignored (excluded) when listing directory contents. /// /// Note that the Blob Container is not created automatically, and existence of the Container is not verified. /// /// Create the Blob Container before enabling a Blob File Store. /// /// Azure Blog Storage will create the BasePath inside the container during the upload of the first file. /// </remarks> public class BlobFileStore : IFileStore { private const string _directoryMarkerFileName = "OrchardCore.Media.txt"; private readonly BlobStorageOptions _options; private readonly IClock _clock; private readonly BlobContainerClient _blobContainer; private readonly IContentTypeProvider _contentTypeProvider; private readonly string _basePrefix = null; public BlobFileStore(BlobStorageOptions options, IClock clock, IContentTypeProvider contentTypeProvider) { _options = options; _clock = clock; _contentTypeProvider = contentTypeProvider; _blobContainer = new BlobContainerClient(_options.ConnectionString, _options.ContainerName); if (!String.IsNullOrEmpty(_options.BasePath)) { _basePrefix = NormalizePrefix(_options.BasePath); } } public async Task<IFileStoreEntry> GetFileInfoAsync(string path) { var blob = GetBlobReference(path); if (!await blob.ExistsAsync()) { return null; } var properties = await blob.GetPropertiesAsync(); return new BlobFile(path, properties.Value.ContentLength, properties.Value.LastModified); } public async Task<IFileStoreEntry> GetDirectoryInfoAsync(string path) { if (path == string.Empty) { return new BlobDirectory(path, _clock.UtcNow); } var blobDirectory = await GetBlobDirectoryReference(path); if (blobDirectory != null) { return new BlobDirectory(path, _clock.UtcNow); } return null; } public Task<IEnumerable<IFileStoreEntry>> GetDirectoryContentAsync(string path = null, bool includeSubDirectories = false) { if (includeSubDirectories) { return GetDirectoryContentFlatAsync(path); } else { return GetDirectoryContentByHierarchyAsync(path); } } private async Task<IEnumerable<IFileStoreEntry>> GetDirectoryContentByHierarchyAsync(string path = null) { var results = new List<IFileStoreEntry>(); var prefix = this.Combine(_basePrefix, path); prefix = NormalizePrefix(prefix); var page = _blobContainer.GetBlobsByHierarchyAsync(BlobTraits.Metadata, BlobStates.None, "/", prefix); await foreach (var blob in page) { if (blob.IsPrefix) { var folderPath = blob.Prefix; if (!String.IsNullOrEmpty(_basePrefix)) { folderPath = folderPath.Substring(_basePrefix.Length - 1); } folderPath = folderPath.Trim('/'); results.Add(new BlobDirectory(folderPath, _clock.UtcNow)); } else { var itemName = Path.GetFileName(WebUtility.UrlDecode(blob.Blob.Name)).Trim('/'); // Ignore directory marker files. if (itemName != _directoryMarkerFileName) { var itemPath = this.Combine(path?.Trim('/'), itemName); results.Add(new BlobFile(itemPath, blob.Blob.Properties.ContentLength, blob.Blob.Properties.LastModified)); } } } return results .OrderByDescending(x => x.IsDirectory) .ToArray(); } private async Task<IEnumerable<IFileStoreEntry>> GetDirectoryContentFlatAsync(string path = null) { var results = new List<IFileStoreEntry>(); // Folders are considered case sensitive in blob storage. var directories = new HashSet<string>(); var prefix = this.Combine(_basePrefix, path); prefix = NormalizePrefix(prefix); var page = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix); await foreach (var blob in page) { var name = WebUtility.UrlDecode(blob.Name); // A flat blob listing does not return a folder hierarchy. // We can infer a hierarchy by examining the paths returned for the file contents // and evaluate whether a directory exists and should be added to the results listing. var directory = Path.GetDirectoryName(name); // Strip base folder from directory name. if (!String.IsNullOrEmpty(_basePrefix)) { directory = directory.Substring(_basePrefix.Length - 1); } // Do not include root folder, or current path, or multiple folders in folder listing. if (!String.IsNullOrEmpty(directory) && !directories.Contains(directory) && (String.IsNullOrEmpty(path) ? true : !directory.EndsWith(path))) { directories.Add(directory); results.Add(new BlobDirectory(directory, _clock.UtcNow)); } // Ignore directory marker files. if (!name.EndsWith(_directoryMarkerFileName)) { if (!String.IsNullOrEmpty(_basePrefix)) { name = name.Substring(_basePrefix.Length - 1); } results.Add(new BlobFile(name.Trim('/'), blob.Properties.ContentLength, blob.Properties.LastModified)); } } return results .OrderByDescending(x => x.IsDirectory) .ToArray(); } public async Task<bool> TryCreateDirectoryAsync(string path) { // Since directories are only created implicitly when creating blobs, we // simply pretend like we created the directory, unless there is already // a blob with the same path. var blobFile = GetBlobReference(path); if (await blobFile.ExistsAsync()) { throw new FileStoreException($"Cannot create directory because the path '{path}' already exists and is a file."); } var blobDirectory = await GetBlobDirectoryReference(path); if (blobDirectory == null) { await CreateDirectoryAsync(path); } return true; } public async Task<bool> TryDeleteFileAsync(string path) { var blob = GetBlobReference(path); return await blob.DeleteIfExistsAsync(); } public async Task<bool> TryDeleteDirectoryAsync(string path) { if (String.IsNullOrEmpty(path)) { throw new FileStoreException("Cannot delete the root directory."); } var blobsWereDeleted = false; var prefix = this.Combine(_basePrefix, path); prefix = this.NormalizePrefix(prefix); var page = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix); await foreach (var blob in page) { var blobReference = _blobContainer.GetBlobClient(blob.Name); await blobReference.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots); blobsWereDeleted = true; } return blobsWereDeleted; } public async Task MoveFileAsync(string oldPath, string newPath) { await CopyFileAsync(oldPath, newPath); await TryDeleteFileAsync(oldPath); } public async Task CopyFileAsync(string srcPath, string dstPath) { if (srcPath == dstPath) { throw new ArgumentException($"The values for {nameof(srcPath)} and {nameof(dstPath)} must not be the same."); } var oldBlob = GetBlobReference(srcPath); var newBlob = GetBlobReference(dstPath); if (!await oldBlob.ExistsAsync()) { throw new FileStoreException($"Cannot copy file '{srcPath}' because it does not exist."); } if (await newBlob.ExistsAsync()) { throw new FileStoreException($"Cannot copy file '{srcPath}' because a file already exists in the new path '{dstPath}'."); } await newBlob.StartCopyFromUriAsync(oldBlob.Uri); await Task.Delay(250); var properties = await newBlob.GetPropertiesAsync(); while (properties.Value.CopyStatus == CopyStatus.Pending) { await Task.Delay(250); // Need to fetch properties or CopyStatus will never update. properties = await newBlob.GetPropertiesAsync(); } if (properties.Value.CopyStatus != CopyStatus.Success) { throw new FileStoreException($"Error while copying file '{srcPath}'; copy operation failed with status {properties.Value.CopyStatus} and description {properties.Value.CopyStatusDescription}."); } } public async Task<Stream> GetFileStreamAsync(string path) { var blob = GetBlobReference(path); if (!await blob.ExistsAsync()) { throw new FileStoreException($"Cannot get file stream because the file '{path}' does not exist."); } return (await blob.DownloadAsync()).Value.Content; } // Reduces the need to call blob.FetchAttributes, and blob.ExistsAsync, // as Azure Storage Library will perform these actions on OpenReadAsync(). public Task<Stream> GetFileStreamAsync(IFileStoreEntry fileStoreEntry) { return GetFileStreamAsync(fileStoreEntry.Path); } public async Task<string> CreateFileFromStreamAsync(string path, Stream inputStream, bool overwrite = false) { var blob = GetBlobReference(path); if (!overwrite && await blob.ExistsAsync()) { throw new FileStoreException($"Cannot create file '{path}' because it already exists."); } _contentTypeProvider.TryGetContentType(path, out var contentType); var headers = new BlobHttpHeaders { ContentType = contentType ?? "application/octet-stream" }; await blob.UploadAsync(inputStream, headers); return path; } private BlobClient GetBlobReference(string path) { var blobPath = this.Combine(_options.BasePath, path); var blob = _blobContainer.GetBlobClient(blobPath); return blob; } private async Task<BlobHierarchyItem> GetBlobDirectoryReference(string path) { var prefix = this.Combine(_basePrefix, path); prefix = NormalizePrefix(prefix); // Directory exists if path contains any files. var page = _blobContainer.GetBlobsByHierarchyAsync(BlobTraits.Metadata, BlobStates.None, "/", prefix); var enumerator = page.GetAsyncEnumerator(); var result = await enumerator.MoveNextAsync(); if (result) { return enumerator.Current; } return null; } private async Task CreateDirectoryAsync(string path) { var placeholderBlob = GetBlobReference(this.Combine(path, _directoryMarkerFileName)); // Create a directory marker file to make this directory appear when listing directories. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("This is a directory marker file created by Orchard Core. It is safe to delete it."))) { await placeholderBlob.UploadAsync(stream); } } /// <summary> /// Blob prefix requires a trailing slash except when loading the root of the container. /// </summary> private string NormalizePrefix(string prefix) { prefix = prefix.Trim('/') + '/'; if (prefix.Length == 1) { return String.Empty; } else { return prefix; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Specialized; using System.Linq; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Xunit; using Avalonia.Input; namespace Avalonia.Controls.UnitTests.Primitives { public class PopupTests { [Fact] public void Setting_Child_Should_Set_Child_Controls_LogicalParent() { var target = new Popup(); var child = new Control(); target.Child = child; Assert.Equal(child.Parent, target); Assert.Equal(((ILogical)child).LogicalParent, target); } [Fact] public void Clearing_Child_Should_Clear_Child_Controls_Parent() { var target = new Popup(); var child = new Control(); target.Child = child; target.Child = null; Assert.Null(child.Parent); Assert.Null(((ILogical)child).LogicalParent); } [Fact] public void Child_Control_Should_Appear_In_LogicalChildren() { var target = new Popup(); var child = new Control(); target.Child = child; Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Clearing_Child_Should_Remove_From_LogicalChildren() { var target = new Popup(); var child = new Control(); target.Child = child; target.Child = null; Assert.Equal(new ILogical[0], ((ILogical)target).LogicalChildren.ToList()); } [Fact] public void Setting_Child_Should_Fire_LogicalChildren_CollectionChanged() { var target = new Popup(); var child = new Control(); var called = false; ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; target.Child = child; Assert.True(called); } [Fact] public void Clearing_Child_Should_Fire_LogicalChildren_CollectionChanged() { var target = new Popup(); var child = new Control(); var called = false; target.Child = child; ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Remove; target.Child = null; Assert.True(called); } [Fact] public void Changing_Child_Should_Fire_LogicalChildren_CollectionChanged() { var target = new Popup(); var child1 = new Control(); var child2 = new Control(); var called = false; target.Child = child1; ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Child = child2; Assert.True(called); } [Fact] public void Setting_Child_Should_Not_Set_Childs_VisualParent() { var target = new Popup(); var child = new Control(); target.Child = child; Assert.Null(((IVisual)child).VisualParent); } [Fact] public void PopupRoot_Should_Initially_Be_Null() { using (CreateServices()) { var target = new Popup(); Assert.Null(target.PopupRoot); } } [Fact] public void PopupRoot_Should_Have_Null_VisualParent() { using (CreateServices()) { var target = new Popup(); target.Open(); Assert.Null(target.PopupRoot.GetVisualParent()); } } [Fact] public void PopupRoot_Should_Have_Popup_As_LogicalParent() { using (CreateServices()) { var target = new Popup(); target.Open(); Assert.Equal(target, target.PopupRoot.Parent); Assert.Equal(target, target.PopupRoot.GetLogicalParent()); } } [Fact] public void PopupRoot_Should_Be_Detached_From_Logical_Tree_When_Popup_Is_Detached() { using (CreateServices()) { var target = new Popup(); var root = new TestRoot { Child = target }; target.Open(); var popupRoot = (ILogical)target.PopupRoot; Assert.True(popupRoot.IsAttachedToLogicalTree); root.Child = null; Assert.False(((ILogical)target).IsAttachedToLogicalTree); } } [Fact] public void PopupRoot_Should_Have_Template_Applied() { using (CreateServices()) { var window = new Window(); var target = new Popup(); var child = new Control(); window.Content = target; target.Open(); Assert.Single(target.PopupRoot.GetVisualChildren()); var templatedChild = target.PopupRoot.GetVisualChildren().Single(); Assert.IsType<ContentPresenter>(templatedChild); Assert.Equal(target.PopupRoot, ((IControl)templatedChild).TemplatedParent); } } [Fact] public void Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent() { using (CreateServices()) { PopupContentControl target; var root = new TestRoot { Child = target = new PopupContentControl { Content = new Border(), Template = new FuncControlTemplate<PopupContentControl>(PopupContentControlTemplate), }, StylingParent = AvaloniaLocator.Current.GetService<IGlobalStyles>() }; target.ApplyTemplate(); var popup = (Popup)target.GetTemplateChildren().First(x => x.Name == "popup"); popup.Open(); var popupRoot = popup.PopupRoot; var children = popupRoot.GetVisualDescendants().ToList(); var types = children.Select(x => x.GetType().Name).ToList(); Assert.Equal( new[] { "ContentPresenter", "ContentPresenter", "Border", }, types); var templatedParents = children .OfType<IControl>() .Select(x => x.TemplatedParent).ToList(); Assert.Equal( new object[] { popupRoot, target, null, }, templatedParents); } } [Fact] public void DataContextBeginUpdate_Should_Not_Be_Called_For_Controls_That_Dont_Inherit() { using (CreateServices()) { TestControl child; var popup = new Popup { Child = child = new TestControl(), DataContext = "foo", }; var beginCalled = false; child.DataContextBeginUpdate += (s, e) => beginCalled = true; // Test for #1245. Here, the child's logical parent is the popup but it's not yet // attached to a visual tree because the popup hasn't been opened. Assert.Same(popup, ((ILogical)child).LogicalParent); Assert.Same(popup, child.InheritanceParent); Assert.Null(child.GetVisualRoot()); popup.Open(); // #1245 was caused by the fact that DataContextBeginUpdate was called on `target` // when the PopupRoot was created, even though PopupRoot isn't the // InheritanceParent of child. Assert.False(beginCalled); } } private static IDisposable CreateServices() { var result = AvaloniaLocator.EnterScope(); var styles = new Styles { new Style(x => x.OfType<PopupRoot>()) { Setters = new[] { new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<PopupRoot>(PopupRootTemplate)), } }, }; var globalStyles = new Mock<IGlobalStyles>(); globalStyles.Setup(x => x.IsStylesInitialized).Returns(true); globalStyles.Setup(x => x.Styles).Returns(styles); var renderInterface = new Mock<IPlatformRenderInterface>(); AvaloniaLocator.CurrentMutable .Bind<ILayoutManager>().ToTransient<LayoutManager>() .Bind<IGlobalStyles>().ToFunc(() => globalStyles.Object) .Bind<IWindowingPlatform>().ToConstant(new WindowingPlatformMock()) .Bind<IStyler>().ToTransient<Styler>() .Bind<IPlatformRenderInterface>().ToFunc(() => renderInterface.Object) .Bind<IInputManager>().ToConstant(new InputManager()); return result; } private static IControl PopupRootTemplate(PopupRoot control) { return new ContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty], }; } private static IControl PopupContentControlTemplate(PopupContentControl control) { return new Popup { Name = "popup", Child = new ContentPresenter { [~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty], } }; } private class PopupContentControl : ContentControl { } private class TestControl : Decorator { public event EventHandler DataContextBeginUpdate; public new IAvaloniaObject InheritanceParent => base.InheritanceParent; protected override void OnDataContextBeginUpdate() { DataContextBeginUpdate?.Invoke(this, EventArgs.Empty); base.OnDataContextBeginUpdate(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using WebSocket.Portable.Interfaces; using WebSocket.Portable.Internal; using WebSocket.Portable.Resources; using WebSocket.Portable.Security; using WebSocket.Portable.Tasks; namespace WebSocket.Portable { public abstract class WebSocketBase : ICanLog, IWebSocket { private readonly List<IWebSocketExtension> _extensions; private Uri _uri; private int _state; private ITcpConnection _tcp; /// <summary> /// Prevents a default instance of the <see cref="WebSocketBase"/> class from being created. /// </summary> protected WebSocketBase() { _extensions = new List<IWebSocketExtension>(); _state = WebSocketState.Closed; } public void RegisterExtension(IWebSocketExtension extension) { if (extension == null) throw new ArgumentNullException("extension"); if (_extensions.Contains(extension)) throw new ArgumentException(ErrorMessages.ExtensionsAlreadyRegistered + extension.Name, "extension"); var oldState = Interlocked.CompareExchange(ref _state, _state, _state); if (oldState != WebSocketState.Closed) throw new InvalidOperationException(ErrorMessages.InvalidState + _state); _extensions.Add(extension); } public virtual Task CloseAsync(WebSocketErrorCode errorCode) { _state = WebSocketState.Closed; _tcp.Dispose(); return TaskAsyncHelper.Empty; } /// <summary> /// Connects asynchronous. /// </summary> /// <param name="uri">The URI.</param> /// <returns></returns> public Task ConnectAsync(string uri) { return this.ConnectAsync(uri, CancellationToken.None); } /// <summary> /// Connects asynchronous. /// </summary> /// <param name="uri">The URI.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Cannot connect because current state is + _state</exception> public async Task ConnectAsync(string uri, CancellationToken cancellationToken) { var oldState = Interlocked.CompareExchange(ref _state, WebSocketState.Connecting, WebSocketState.Closed); if (oldState != WebSocketState.Closed) throw new InvalidOperationException(ErrorMessages.InvalidState + _state); if (uri == null) throw new ArgumentNullException("uri"); _uri = WebSocketHelper.CreateWebSocketUri(uri); var useSsl = _uri.Scheme == "wss"; var port = useSsl ? 443 : 80; _tcp = await this.ConnectAsync(_uri.DnsSafeHost, port, useSsl, cancellationToken); Interlocked.Exchange(ref _state, WebSocketState.Connected); } /// <summary> /// Connects asynchronous. /// </summary> /// <param name="host">The host.</param> /// <param name="port">The port.</param> /// <param name="useSsl">if set to <c>true</c> [use SSL].</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected abstract Task<ITcpConnection> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken); /// <summary> /// Sends the default handshake asynchronous. /// </summary> /// <returns></returns> public Task<WebSocketResponseHandshake> SendHandshakeAsync() { return this.SendHandshakeAsync(CancellationToken.None); } /// <summary> /// Sends the default handshake asynchronous. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public Task<WebSocketResponseHandshake> SendHandshakeAsync(CancellationToken cancellationToken) { var handshake = new WebSocketRequestHandshake(_uri); foreach (var extension in _extensions) handshake.AddExtension(extension); return this.SendHandshakeAsync(handshake, cancellationToken); } /// <summary> /// Sends the handshake asynchronous. /// </summary> /// <param name="handshake">The handshake.</param> /// <returns></returns> public Task<WebSocketResponseHandshake> SendHandshakeAsync(WebSocketRequestHandshake handshake) { return this.SendHandshakeAsync(handshake, CancellationToken.None); } /// <summary> /// Sends the handshake asynchronous. /// </summary> /// <param name="handshake">The handshake.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task<WebSocketResponseHandshake> SendHandshakeAsync(WebSocketRequestHandshake handshake, CancellationToken cancellationToken) { var oldState = Interlocked.CompareExchange(ref _state, WebSocketState.Opening, WebSocketState.Connected); if (oldState != WebSocketState.Connected) throw new InvalidOperationException(ErrorMessages.InvalidState + _state); var data = handshake.ToString(); await this.SendAsync(data, Encoding.UTF8, cancellationToken); var responseHeaders = new List<string>(); var line = await _tcp.ReadLineAsync(cancellationToken); while (!String.IsNullOrEmpty(line)) { responseHeaders.Add(line); line = await _tcp.ReadLineAsync(cancellationToken); } var response = WebSocketResponseHandshake.Parse(responseHeaders); if (response.StatusCode != HttpStatusCode.SwitchingProtocols) { var versions = response.SecWebSocketVersion; if (versions != null && !versions.Intersect(Consts.SupportedClientVersions).Any()) throw new WebSocketException(WebSocketErrorCode.HandshakeVersionNotSupported); throw new WebSocketException(WebSocketErrorCode.HandshakeInvalidStatusCode); } var challenge = Encoding.UTF8.GetBytes(handshake.SecWebSocketKey + Consts.ServerGuid); var hash = Sha1Digest.ComputeHash(challenge); var calculatedAccept = Convert.ToBase64String(hash); if (response.SecWebSocketAccept != calculatedAccept) throw new WebSocketException(WebSocketErrorCode.HandshakeInvalidSecWebSocketAccept); response.RequestMessage = handshake; Interlocked.Exchange(ref _state, WebSocketState.Open); return response; } public Task SendFrameAsync(IWebSocketFrame frame) { return this.SendFrameAsync(frame, CancellationToken.None); } public Task SendFrameAsync(IWebSocketFrame frame, CancellationToken cancellationToken) { if (frame == null) throw new ArgumentNullException("frame"); return frame.WriteToAsync(_tcp, cancellationToken); } public Task<IWebSocketFrame> ReceiveFrameAsync() { return ReceiveFrameAsync(CancellationToken.None); } public async Task<IWebSocketFrame> ReceiveFrameAsync(CancellationToken cancellationToken) { //BADREAD? var frame = new WebSocketServerFrame(); await frame.ReadFromAsync(_tcp, cancellationToken); return frame; } /// <summary> /// Sends data asynchronous. /// </summary> /// <param name="data">The data.</param> /// <param name="encoding">The encoding.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> private Task SendAsync(string data, Encoding encoding, CancellationToken cancellationToken) { var bytes = encoding.GetBytes(data); return SendAsync(bytes, 0, bytes.Length, cancellationToken); } /// <summary> /// Sends data asynchronous. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> private Task SendAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { return _tcp.WriteAsync(buffer, offset, length, cancellationToken); } public virtual void Dispose() { _tcp.Dispose(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Data.Tables.Models; using Azure.Data.Tables.Sas; using NUnit.Framework; namespace Azure.Data.Tables.Tests { /// <summary> /// The suite of tests for the <see cref="TableServiceClient"/> class. /// </summary> /// <remarks> /// These tests have a dependency on live Azure services and may incur costs for the associated /// Azure subscription. /// </remarks> public class TableClientLiveTests : TableServiceLiveTestsBase { public TableClientLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */) { } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateIfNotExists() { // Call CreateIfNotExists when the table already exists. Assert.That(async () => await CosmosThrottleWrapper(async () => await client.CreateIfNotExistsAsync().ConfigureAwait(false)), Throws.Nothing); // Call CreateIfNotExists when the table does not already exist. var newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); TableItem table; TableClient tableClient = null; try { tableClient = service.GetTableClient(newTableName); table = await CosmosThrottleWrapper(async () => await tableClient.CreateIfNotExistsAsync().ConfigureAwait(false)); } finally { await tableClient.DeleteAsync().ConfigureAwait(false); } Assert.That(table.TableName, Is.EqualTo(newTableName)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task ValidateCreateDeleteTable() { // Get the TableClient of a table that hasn't been created yet. var validTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); var tableClient = service.GetTableClient(validTableName); // Create the table using the TableClient method. await CosmosThrottleWrapper(async () => await tableClient.CreateAsync().ConfigureAwait(false)); // Check that the table was created. var tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{validTableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList(); Assert.That(() => tableResponses, Is.Not.Empty); // Delete the table using the TableClient method. await CosmosThrottleWrapper(async () => await tableClient.DeleteAsync().ConfigureAwait(false)); // Check that the table was deleted. tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{validTableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList(); Assert.That(() => tableResponses, Is.Empty); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public void ValidateSasCredentials() { // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(AccountName, AccountKey); // Build a shared access signature with only Read permissions. TableSasBuilder sas = client.GetSasBuilder(TableSasPermissions.Read, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); if (_endpointType == TableEndpointType.CosmosTable) { sas.Version = "2017-07-29"; } string token = sas.Sign(credential); // Create the TableServiceClient using the SAS URI. var sasAuthedService = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(token), InstrumentClientOptions(new TableClientOptions()))); var sasTableclient = sasAuthedService.GetTableClient(tableName); // Validate that we are able to query the table from the service. Assert.That(async () => await sasTableclient.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false), Throws.Nothing); // Validate that we are not able to upsert an entity to the table. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await sasTableclient.UpsertEntityAsync(CreateTableEntities("partition", 1).First(), TableUpdateMode.Replace).ConfigureAwait(false)); Assert.That(ex.Status, Is.EqualTo((int)HttpStatusCode.Forbidden)); if (_endpointType == TableEndpointType.Storage) { Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.AuthorizationPermissionMismatch.ToString())); } else { Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.Forbidden.ToString())); } } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task ValidateSasCredentialsWithRowKeyAndPartitionKeyRanges() { List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 2); // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(AccountName, AccountKey); // Build a shared access signature with only All permissions. TableSasBuilder sas = client.GetSasBuilder(TableSasPermissions.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); // Add PartitionKey restrictions. sas.PartitionKeyStart = PartitionKeyValue; sas.PartitionKeyEnd = PartitionKeyValue; // Add RowKey restrictions so that only the first entity is visible. sas.RowKeyStart = entitiesToCreate[0].RowKey; sas.RowKeyEnd = entitiesToCreate[0].RowKey; if (_endpointType == TableEndpointType.CosmosTable) { sas.Version = "2017-07-29"; } string token = sas.Sign(credential); // Create the TableServiceClient using the SAS URI. var sasAuthedService = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(token), InstrumentClientOptions(new TableClientOptions()))); var sasTableclient = sasAuthedService.GetTableClient(tableName); // Insert the entities foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Validate that we are able to query the table from the service. var entities = await sasTableclient.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entities.Count, Is.EqualTo(1)); // Validate that we are not able to fetch the entity outside the range of the row key filter. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await sasTableclient.GetEntityAsync<TableEntity>(PartitionKeyValue, entitiesToCreate[1].RowKey).ConfigureAwait(false)); Assert.That(ex.Status, Is.EqualTo((int)HttpStatusCode.NotFound)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.ResourceNotFound.ToString())); // Validate that we are able to fetch the entity with the client with full access. Assert.That(async () => await client.GetEntityAsync<TableEntity>(PartitionKeyValue, entitiesToCreate[1].RowKey).ConfigureAwait(false), Throws.Nothing); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] [TestCase(null)] [TestCase(5)] public async Task CreatedEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount) { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities. entityResults = await client.QueryAsync<TableEntity>(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); entityResults.Clear(); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedDynamicEntitiesCanBeQueriedWithFilters() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateDictionaryTableEntities(PartitionKeyValue, 20); // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEntitiesCanBeQueriedWithFilters() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityCanBeUpserted() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var entityToUpdate = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); entityToUpdate[propertyName] = updatedValue; await client.UpsertEntityAsync(entityToUpdate, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityUpdateRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityMergeRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityMergeDoesPartialPropertyUpdates() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string mergepropertyName = "MergedProperty"; const string originalValue = "This is the original"; const string mergeValue = "This was merged!"; const string mergeUpdatedValue = "merged value was updated!"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; var partialEntity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {mergepropertyName, mergeValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(originalEntity.TryGetValue(mergepropertyName, out var _), Is.False); Assert.That(originalEntity[propertyName], Is.EqualTo(originalValue)); await client.UpsertEntityAsync(partialEntity, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var mergedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeValue)); Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue)); // Update just the merged value. partialEntity[mergepropertyName] = mergeUpdatedValue; await client.UpsertEntityAsync(partialEntity, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. mergedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeUpdatedValue)); Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityDeleteRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); var staleEtag = originalEntity.ETag; // Use a wildcard ETag to delete unconditionally. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false); // Validate that the entity is deleted. var emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); // Create the new entity again. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, originalEntity.ETag).ConfigureAwait(false); // Validate that the entity is deleted. emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEntitiesAreRoundtrippedWithProperOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First().PartitionKey, Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First().RowKey, Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First().Timestamp, Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTimeOffset?"); Assert.That(entityResults.First().Timestamp, Is.Not.Null, "The entity property should not be null"); Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTime"); Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid"); Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]"); Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64"); //TODO: Remove conditional after fixing https://github.com/Azure/azure-sdk-for-net/issues/13552 if (_endpointType != TableEndpointType.CosmosTable) { Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); } Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task UpsertedEntitiesAreRoundtrippedWithProperOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTime"); Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid"); Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]"); Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64"); //TODO: Remove conditional after fixing https://github.com/Azure/azure-sdk-for-net/issues/13552 if (_endpointType != TableEndpointType.CosmosTable) { Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); } Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateEntityReturnsEntitiesWithoutOdataAnnoations() { TableEntity entityToCreate = CreateTableEntities(PartitionKeyValue, 1).First(); // Create an entity. await client.AddEntityAsync(entityToCreate).ConfigureAwait(false); TableEntity entity = await client.GetEntityAsync<TableEntity>(entityToCreate.PartitionKey, entityToCreate.RowKey).ConfigureAwait(false); Assert.That(entity.Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateEntityAllowsSelect() { TableEntity entityToCreate = CreateTableEntities(PartitionKeyValue, 1).First(); // Create an entity. await client.AddEntityAsync(entityToCreate).ConfigureAwait(false); TableEntity entity = await client.GetEntityAsync<TableEntity>(entityToCreate.PartitionKey, entityToCreate.RowKey, new[] { nameof(entityToCreate.Timestamp) }).ConfigureAwait(false); Assert.That(entity.PartitionKey, Is.Null, "The entity property should be null"); Assert.That(entity.RowKey, Is.Null, "The entity property should be null"); Assert.That(entity.Timestamp, Is.Not.Null, "The entity property should not be null"); Assert.That(entity.TryGetValue(StringTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DateTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(GuidTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(BinaryTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(Int64TypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DoubleTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DoubleDecimalTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(IntTypePropertyName, out _), Is.False, "The entity property should not exist"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task QueryReturnsEntitiesWithoutOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First().Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] [TestCase(null)] [TestCase(5)] public async Task CreatedCustomEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount) { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities. entityResults = await client.QueryAsync<TestEntity>(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); entityResults.Clear(); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedCustomEntitiesCanBeQueriedWithFilters() { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityCanBeUpserted() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var entityToUpdate = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); entityToUpdate[propertyName] = updatedValue; await client.UpsertEntityAsync(entityToUpdate, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityUpdateRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityMergeRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityDeleteRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string originalValue = "This is the original"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); var staleEtag = originalEntity.ETag; // Use a wildcard ETag to delete unconditionally. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false); // Validate that the entity is deleted. var emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); // Create the new entity again. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Use a non-matching ETag. var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false)); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.UpdateConditionNotSatisfied.ToString())); // Use a matching ETag. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, originalEntity.ETag).ConfigureAwait(false); // Validate that the entity is deleted. emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedCustomEntitiesAreRoundtrippedProprly() { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 1); // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); entityResults.Sort((first, second) => first.IntTypeProperty.CompareTo(second.IntTypeProperty)); for (int i = 0; i < entityResults.Count; i++) { Assert.That(entityResults[i].BinaryTypeProperty, Is.EqualTo(entitiesToCreate[i].BinaryTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DatetimeOffsetTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeOffsetTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DatetimeTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DoubleTypeProperty, Is.EqualTo(entitiesToCreate[i].DoubleTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].GuidTypeProperty, Is.EqualTo(entitiesToCreate[i].GuidTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].Int64TypeProperty, Is.EqualTo(entitiesToCreate[i].Int64TypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].IntTypeProperty, Is.EqualTo(entitiesToCreate[i].IntTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].PartitionKey, Is.EqualTo(entitiesToCreate[i].PartitionKey), "The entities should be equivalent"); Assert.That(entityResults[i].RowKey, Is.EqualTo(entitiesToCreate[i].RowKey), "The entities should be equivalent"); Assert.That(entityResults[i].StringTypeProperty, Is.EqualTo(entitiesToCreate[i].StringTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].ETag, Is.Not.EqualTo(default(ETag)), $"ETag value should not be default: {entityResults[i].ETag}"); } } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEnumEntitiesAreRoundtrippedProperly() { List<EnumEntity> entityResults; var entitiesToCreate = new[] { new EnumEntity{ PartitionKey = PartitionKeyValue, RowKey = "01", MyFoo = Foo.Two, MyNullableFoo = NullableFoo.Two}, new EnumEntity{ PartitionKey = PartitionKeyValue, RowKey = "02", MyFoo = Foo.Two, MyNullableFoo = null}, }; // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<EnumEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); for (int i = 0; i < entityResults.Count; i++) { Assert.That(entityResults[i].PartitionKey, Is.EqualTo(entitiesToCreate[i].PartitionKey), "The entities should be equivalent"); Assert.That(entityResults[i].RowKey, Is.EqualTo(entitiesToCreate[i].RowKey), "The entities should be equivalent"); Assert.That(entityResults[i].MyFoo, Is.EqualTo(entitiesToCreate[i].MyFoo), "The entities should be equivalent"); Assert.That(entityResults[i].MyNullableFoo, Is.EqualTo(entitiesToCreate[i].MyNullableFoo), "The entities should be equivalent"); } } /// <summary> /// Validates the functionality of the TableServiceClient. /// </summary> [RecordedTest] public async Task GetAccessPoliciesReturnsPolicies() { // Create some policies. var policyToCreate = new List<SignedIdentifier> { new SignedIdentifier("MyPolicy", new TableAccessPolicy(new DateTime(2020, 1,1,1,1,0,DateTimeKind.Utc), new DateTime(2021, 1,1,1,1,0,DateTimeKind.Utc), "r")) }; await client.SetAccessPolicyAsync(tableAcl: policyToCreate); // Get the created policy. var policies = await client.GetAccessPolicyAsync(); Assert.That(policies.Value[0].Id, Is.EqualTo(policyToCreate[0].Id)); Assert.That(policies.Value[0].AccessPolicy.ExpiresOn, Is.EqualTo(policyToCreate[0].AccessPolicy.ExpiresOn)); Assert.That(policies.Value[0].AccessPolicy.Permission, Is.EqualTo(policyToCreate[0].AccessPolicy.Permission)); Assert.That(policies.Value[0].AccessPolicy.StartsOn, Is.EqualTo(policyToCreate[0].AccessPolicy.StartsOn)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task GetEntityReturnsSingleEntity() { TableEntity entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Get the single entity by PartitionKey and RowKey. entityResults = (await client.GetEntityAsync<TableEntity>(PartitionKeyValue, "01").ConfigureAwait(false)).Value; Assert.That(entityResults, Is.Not.Null, "The entity should not be null."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchInsert() { var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 5); // Create the batch. var batch = InstrumentClient(client.CreateTransactionalBatch(entitiesToCreate[0].PartitionKey)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Add the entities to the batch. batch.AddEntities(entitiesToCreate); TableBatchResponse response = await batch.SubmitBatchAsync().ConfigureAwait(false); foreach (var entity in entitiesToCreate) { Assert.That(response.GetResponseForEntity(entity.RowKey).Status, Is.EqualTo((int)HttpStatusCode.NoContent)); } Assert.That(response.ResponseCount, Is.EqualTo(entitiesToCreate.Count)); // Query the entities. var entityResults = await client.QueryAsync<TestEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchInsertAndMergeAndDelete() { const string updatedString = "the string was updated!"; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 5); // Add just the first three entities await client.AddEntityAsync(entitiesToCreate[0]).ConfigureAwait(false); await client.AddEntityAsync(entitiesToCreate[1]).ConfigureAwait(false); await client.AddEntityAsync(entitiesToCreate[2]).ConfigureAwait(false); // Create the batch. TableTransactionalBatch batch = InstrumentClient(client.CreateTransactionalBatch(PartitionKeyValue)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Add a Merge operation to the entity we are adding. var mergeEntity = new TableEntity(PartitionKeyValue, entitiesToCreate[0].RowKey); mergeEntity.Add("MergedProperty", "foo"); batch.UpdateEntity(mergeEntity, ETag.All, TableUpdateMode.Merge); // Add a Delete operation. var entityToDelete = entitiesToCreate[1]; batch.DeleteEntity(entityToDelete.RowKey, ETag.All); // Add an Upsert operation to replace the entity with an updated value. entitiesToCreate[2].StringTypeProperty = updatedString; batch.UpsertEntity(entitiesToCreate[2], TableUpdateMode.Replace); // Add an Upsert operation to add an entity. batch.UpsertEntity(entitiesToCreate[3], TableUpdateMode.Replace); // Add the last entity. batch.AddEntity(entitiesToCreate.Last()); // Submit the batch. TableBatchResponse response = await batch.SubmitBatchAsync().ConfigureAwait(false); // Validate that the batch throws if we try to send it again. Assert.ThrowsAsync<InvalidOperationException>(() => batch.SubmitBatchAsync()); // Validate that adding more operations to the batch throws. var exception = Assert.Throws<InvalidOperationException>(() => batch.AddEntity(new TableEntity())); Assert.That(exception.Message, Is.EqualTo(TableConstants.ExceptionMessages.BatchCanOnlyBeSubmittedOnce)); foreach (var entity in entitiesToCreate) { Assert.That(response.GetResponseForEntity(entity.RowKey).Status, Is.EqualTo((int)HttpStatusCode.NoContent)); } Assert.That(response.ResponseCount, Is.EqualTo(entitiesToCreate.Count)); // Query the entities. var entityResults = await client.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count - 1), "The entity result count should match the created count minus the deleted count."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[0].RowKey).ContainsKey("StringTypeProperty"), "The merged entity result should still contain StringTypeProperty."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[0].RowKey)["MergedProperty"], Is.EqualTo("foo"), "The merged entity should have merged the value of MergedProperty."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[2].RowKey)["StringTypeProperty"], Is.EqualTo(updatedString), "The entity result property should have been updated."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchError() { var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 4); // Create the batch. var batch = InstrumentClient(client.CreateTransactionalBatch(entitiesToCreate[0].PartitionKey)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Sending an empty batch throws. var exception = Assert.ThrowsAsync<InvalidOperationException>(() => batch.SubmitBatchAsync()); Assert.That(exception.Message, Is.EqualTo(TableConstants.ExceptionMessages.BatchIsEmpty)); // Add the last entity to the table prior to adding it as part of the batch to cause a batch failure. await client.AddEntityAsync(entitiesToCreate.Last()); // Add the entities to the batch batch.AddEntities(entitiesToCreate); var ex = Assert.ThrowsAsync<RequestFailedException>(() => batch.SubmitBatchAsync()); Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.EntityAlreadyExists.ToString())); Assert.That(ex.Status == (int)HttpStatusCode.Conflict, $"Status should be {HttpStatusCode.Conflict}"); Assert.That(ex.Message, Is.Not.Null, "Message should not be null"); Assert.That(batch.TryGetFailedEntityFromException(ex, out ITableEntity failedEntity), Is.True); Assert.That(failedEntity.RowKey, Is.EqualTo(entitiesToCreate.Last().RowKey)); Assert.That(ex.Message.Contains(nameof(TableTransactionalBatch.TryGetFailedEntityFromException))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace ILCompiler.DependencyAnalysis.X64 { public struct X64Emitter { public X64Emitter(NodeFactory factory) { Builder = new ObjectDataBuilder(factory); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; // Assembly stub creation api. TBD, actually make this general purpose public void EmitMOV(Register regDst, ref AddrMode memory) { EmitIndirInstructionSize(0x8a, regDst, ref memory); } public void EmitMOV(Register regDst, Register regSrc) { AddrMode rexAddrMode = new AddrMode(regSrc, null, 0, 0, AddrModeSize.Int64); EmitRexPrefix(regDst, ref rexAddrMode); Builder.EmitByte(0x89); Builder.EmitByte((byte)(0xC0 | (((int)regSrc & 0x07) << 3) | (((int)regDst & 0x07)))); } public void EmitLEAQ(Register reg, ISymbolNode symbol) { AddrMode rexAddrMode = new AddrMode(Register.RAX, null, 0, 0, AddrModeSize.Int64); EmitRexPrefix(reg, ref rexAddrMode); Builder.EmitByte(0x8D); Builder.EmitByte((byte)(0x05 | (((int)reg) & 0x07) << 3)); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitJmpToAddrMode(ref AddrMode addrMode) { EmitIndirInstruction(0xFF, 0x4, ref addrMode); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.RBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { //# ifdef _TARGET_AMD64_ // x64 requires SIB to avoid RIP relative address emitSibByte = true; //#else // emitSibByte = (addrMode.m_indexReg != MDIL_REG_NO_INDEX); //#endif modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.RBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.RBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.RSP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { // MDIL_REG_ESP as the base is the marker that there is a SIB byte modRM = (byte)((modRM & 0xF8) | (int)Register.RSP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.RSP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitRexPrefix(Register reg, ref AddrMode addrMode) { byte rexPrefix = 0; // Check the situations where a REX prefix is needed // Are we accessing a byte register that wasn't byte accessible in x86? if (addrMode.Size == AddrModeSize.Int8 && reg >= Register.RSP) { rexPrefix |= 0x40; } // Is this a 64 bit instruction? if (addrMode.Size == AddrModeSize.Int64) { rexPrefix |= 0x48; } // Is the destination register one of the new ones? if (reg >= Register.R8) { rexPrefix |= 0x44; } // Is the index register one of the new ones? if (addrMode.IndexReg.HasValue && addrMode.IndexReg.Value >= Register.R8 && addrMode.IndexReg.Value <= Register.R15) { rexPrefix |= 0x42; } // Is the base register one of the new ones? if (addrMode.BaseReg >= Register.R8 && addrMode.BaseReg <= Register.R15 || addrMode.BaseReg >= (int)Register.R8 + Register.RegDirect && addrMode.BaseReg <= (int)Register.R15 + Register.RegDirect) { rexPrefix |= 0x41; } // If we have anything so far, emit it. if (rexPrefix != 0) { Builder.EmitByte(rexPrefix); } } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { EmitRexPrefix(Register.RAX, ref addrMode); if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } private void EmitIndirInstruction(int opcode, Register dstReg, ref AddrMode addrMode) { EmitRexPrefix(dstReg, ref addrMode); if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM((byte)((int)dstReg & 0x07), ref addrMode); } private void EmitIndirInstructionSize(int opcode, Register dstReg, ref AddrMode addrMode) { //# ifndef _TARGET_AMD64_ // assert that ESP, EBP, ESI, EDI are not accessed as bytes in 32-bit mode // Debug.Assert(!(addrMode.Size == AddrModeSize.Int8 && dstReg > Register.RBX)); //#endif Debug.Assert(addrMode.Size != 0); if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction(opcode + ((addrMode.Size != AddrModeSize.Int8) ? 1 : 0), dstReg, ref addrMode); } } }
/* * Anarres C Preprocessor * Copyright (c) 2007-2008, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; using System.Text; using System.Globalization; using System.Diagnostics; namespace CppNet { /** Does not handle digraphs. */ public class LexerSource : Source { static bool isJavaIdentifierStart(int c) { return char.IsLetter((char)c) || c == '$' || c == '_'; } static bool isJavaIdentifierPart(int c) { return char.IsLetter((char)c) || c == '$' || c == '_' || char.IsDigit((char)c); } static bool isIdentifierIgnorable(int c) { return c >= 0 && c <= 8 || c >= 0xE && c <= 0x1B || c >= 0x7F && c <= 0x9F || CharUnicodeInfo.GetUnicodeCategory((char)c) == UnicodeCategory.Format; } static int digit(char ch, int radix) { string alphabet; switch(radix) { case 8: alphabet = "012345678"; break; case 10: alphabet = "0123456789"; break; case 16: ch = char.ToLower(ch); alphabet = "0123456789abcdef"; break; default: throw new NotSupportedException(); } return alphabet.IndexOf(ch); } private static readonly bool DEBUG = false; private JoinReader reader; private bool ppvalid; private bool bol; private bool include; private bool digraphs; /* Unread. */ private int u0, u1; private int ucount; private int line; private int column; private int lastcolumn; private bool cr; /* ppvalid is: * false in StringLexerSource, * true in FileLexerSource */ public LexerSource(TextReader r, bool ppvalid) { this.reader = new JoinReader(r); this.ppvalid = ppvalid; this.bol = true; this.include = false; this.digraphs = true; this.ucount = 0; this.line = 1; this.column = 0; this.lastcolumn = -1; this.cr = false; } override internal void init(Preprocessor pp) { base.init(pp); this.digraphs = pp.getFeature(Feature.DIGRAPHS); this.reader.init(pp, this); } override public int getLine() { return line; } override public int getColumn() { return column; } override internal bool isNumbered() { return true; } /* Error handling. */ private void _error(String msg, bool error) { int _l = line; int _c = column; if (_c == 0) { _c = lastcolumn; _l--; } else { _c--; } if (error) base.error(_l, _c, msg); else base.warning(_l, _c, msg); } /* Allow JoinReader to call this. */ internal void error(String msg) { _error(msg, true); } /* Allow JoinReader to call this. */ internal void warning(String msg) { _error(msg, false); } /* A flag for string handling. */ internal void setInclude(bool b) { this.include = b; } /* private bool _isLineSeparator(int c) { return Character.getType(c) == Character.LINE_SEPARATOR || c == -1; } */ /* XXX Move to JoinReader and canonicalise newlines. */ private static bool isLineSeparator(int c) { switch ((char)c) { case '\r': case '\n': case '\u2028': case '\u2029': case '\u000B': case '\u000C': case '\u0085': return true; default: return (c == -1); } } private int read() { System.Diagnostics.Debug.Assert(ucount <= 2, "Illegal ucount: " + ucount); switch (ucount) { case 2: ucount = 1; return u1; case 1: ucount = 0; return u0; } if (reader == null) return -1; int c = reader.read(); switch (c) { case '\r': cr = true; line++; lastcolumn = column; column = 0; break; case '\n': if (cr) { cr = false; break; } goto case '\u2028'; /* fallthrough */ case '\u2028': case '\u2029': case '\u000B': case '\u000C': case '\u0085': cr = false; line++; lastcolumn = column; column = 0; break; default: cr = false; column++; break; } /* if (isLineSeparator(c)) { line++; lastcolumn = column; column = 0; } else { column++; } */ return c; } /* You can unget AT MOST one newline. */ private void unread(int c) { /* XXX Must unread newlines. */ if (c != -1) { if (isLineSeparator(c)) { line--; column = lastcolumn; cr = false; } else { column--; } switch (ucount) { case 0: u0 = c; ucount = 1; break; case 1: u1 = c; ucount = 2; break; default: throw new InvalidOperationException( "Cannot unget another character!" ); } // reader.unread(c); } } /* Consumes the rest of the current line into an invalid. */ private Token invalid(StringBuilder text, String reason) { int d = read(); while (!isLineSeparator(d)) { text.Append((char)d); d = read(); } unread(d); return new Token(Token.INVALID, text.ToString(), reason); } private Token ccomment() { StringBuilder text = new StringBuilder("/*"); int d; do { do { d = read(); text.Append((char)d); } while (d != '*'); do { d = read(); text.Append((char)d); } while (d == '*'); } while (d != '/'); return new Token(Token.CCOMMENT, text.ToString()); } private Token cppcomment() { StringBuilder text = new StringBuilder("//"); int d = read(); while (!isLineSeparator(d)) { text.Append((char)d); d = read(); } unread(d); return new Token(Token.CPPCOMMENT, text.ToString()); } private int escape(StringBuilder text) { int d = read(); switch (d) { case 'a': text.Append('a'); return 0x07; case 'b': text.Append('b'); return '\b'; case 'f': text.Append('f'); return '\f'; case 'n': text.Append('n'); return '\n'; case 'r': text.Append('r'); return '\r'; case 't': text.Append('t'); return '\t'; case 'v': text.Append('v'); return 0x0b; case '\\': text.Append('\\'); return '\\'; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': int len = 0; int val = 0; do { val = (val << 3) + digit((char)d, 8); text.Append((char)d); d = read(); } while(++len < 3 && digit((char)d, 8) != -1); unread(d); return val; case 'x': len = 0; val = 0; do { val = (val << 4) + digit((char)d, 16); text.Append((char)d); d = read(); } while(++len < 2 && digit((char)d, 16) != -1); unread(d); return val; /* Exclude two cases from the warning. */ case '"': text.Append('"'); return '"'; case '\'': text.Append('\''); return '\''; default: warning("Unnecessary escape character " + (char)d); text.Append((char)d); return d; } } private Token character() { StringBuilder text = new StringBuilder("'"); int d = read(); if (d == '\\') { text.Append('\\'); d = escape(text); } else if (isLineSeparator(d)) { unread(d); return new Token(Token.INVALID, text.ToString(), "Unterminated character literal"); } else if (d == '\'') { text.Append('\''); return new Token(Token.INVALID, text.ToString(), "Empty character literal"); } else if (char.IsControl((char)d)) { text.Append('?'); return invalid(text, "Illegal unicode character literal"); } else { text.Append((char)d); } int e = read(); if (e != '\'') { // error("Illegal character constant"); /* We consume up to the next ' or the rest of the line. */ for (;;) { if (isLineSeparator(e)) { unread(e); break; } text.Append((char)e); if (e == '\'') break; e = read(); } return new Token(Token.INVALID, text.ToString(), "Illegal character constant " + text); } text.Append('\''); /* XXX It this a bad cast? */ return new Token(Token.CHARACTER, text.ToString(), (char)d); } private Token String(char open, char close) { StringBuilder text = new StringBuilder(); text.Append(open); StringBuilder buf = new StringBuilder(); for (;;) { int c = read(); if (c == close) { break; } else if (c == '\\') { text.Append('\\'); if (!include) { char d = (char)escape(text); buf.Append(d); } } else if (c == -1) { unread(c); // error("End of file in string literal after " + buf); return new Token(Token.INVALID, text.ToString(), "End of file in string literal after " + buf); } else if (isLineSeparator(c)) { unread(c); // error("Unterminated string literal after " + buf); return new Token(Token.INVALID, text.ToString(), "Unterminated string literal after " + buf); } else { text.Append((char)c); buf.Append((char)c); } } text.Append(close); return new Token(close == '>' ? Token.HEADER : Token.STRING, text.ToString(), buf.ToString()); } private Token _number(StringBuilder text, long val, int d) { int bits = 0; for (;;) { /* XXX Error check duplicate bits. */ if (d == 'U' || d == 'u') { bits |= 1; text.Append((char)d); d = read(); } else if (d == 'L' || d == 'l') { if ((bits & 4) != 0) /* XXX warn */ ; bits |= 2; text.Append((char)d); d = read(); } else if (d == 'I' || d == 'i') { if ((bits & 2) != 0) /* XXX warn */ ; bits |= 4; text.Append((char)d); d = read(); } else if (char.IsLetter((char)d)) { unread(d); return new Token(Token.INVALID, text.ToString(), "Invalid suffix \"" + (char)d + "\" on numeric constant"); } else { unread(d); return new Token(Token.INTEGER, text.ToString(), (long)val); } } } /* We already chewed a zero, so empty is fine. */ private Token number_octal() { StringBuilder text = new StringBuilder("0"); int d = read(); long val = 0; while (digit((char)d, 8) != -1) { val = (val << 3) + digit((char)d, 8); text.Append((char)d); d = read(); } return _number(text, val, d); } /* We do not know whether know the first digit is valid. */ private Token number_hex(char x) { StringBuilder text = new StringBuilder("0"); text.Append(x); int d = read(); if (digit((char)d, 16) == -1) { unread(d); // error("Illegal hexadecimal constant " + (char)d); return new Token(Token.INVALID, text.ToString(), "Illegal hexadecimal digit " + (char)d + " after "+ text); } long val = 0; do { val = (val << 4) + digit((char)d, 16); text.Append((char)d); d = read(); } while (digit((char)d, 16) != -1); return _number(text, val, d); } /* We know we have at least one valid digit, but empty is not * fine. */ /* XXX This needs a complete rewrite. */ private Token number_decimal(int c) { StringBuilder text = new StringBuilder((char)c); int d = c; long val = 0; do { val = val * 10 + digit((char)d, 10); text.Append((char)d); d = read(); } while (digit((char)d, 10) != -1); return _number(text, val, d); } private Token identifier(int c) { StringBuilder text = new StringBuilder(); int d; text.Append((char)c); for (;;) { d = read(); if (isIdentifierIgnorable(d)) ; else if (isJavaIdentifierPart(d)) text.Append((char)d); else break; } unread(d); return new Token(Token.IDENTIFIER, text.ToString()); } private Token whitespace(int c) { StringBuilder text = new StringBuilder(); int d; text.Append((char)c); for (;;) { d = read(); if (ppvalid && isLineSeparator(d)) /* XXX Ugly. */ break; if (char.IsWhiteSpace((char)d)) text.Append((char)d); else break; } unread(d); return new Token(Token.WHITESPACE, text.ToString()); } /* No token processed by cond() contains a newline. */ private Token cond(char c, int yes, int no) { int d = read(); if (c == d) return new Token(yes); unread(d); return new Token(no); } public override Token token() { Token tok = null; int _l = line; int _c = column; int c = read(); int d; switch (c) { case '\n': if (ppvalid) { bol = true; if (include) { tok = new Token(Token.NL, _l, _c, "\n"); } else { int nls = 0; do { nls++; d = read(); } while (d == '\n'); unread(d); char[] text = new char[nls]; for (int i = 0; i < text.Length; i++) text[i] = '\n'; // Skip the bol = false below. tok = new Token(Token.NL, _l, _c, new String(text)); } if (DEBUG) Debug.WriteLine("lx: Returning NL: " + tok); return tok; } /* Let it be handled as whitespace. */ break; case '!': tok = cond('=', Token.NE, '!'); break; case '#': if (bol) tok = new Token(Token.HASH); else tok = cond('#', Token.PASTE, '#'); break; case '+': d = read(); if (d == '+') tok = new Token(Token.INC); else if (d == '=') tok = new Token(Token.PLUS_EQ); else unread(d); break; case '-': d = read(); if (d == '-') tok = new Token(Token.DEC); else if (d == '=') tok = new Token(Token.SUB_EQ); else if (d == '>') tok = new Token(Token.ARROW); else unread(d); break; case '*': tok = cond('=', Token.MULT_EQ, '*'); break; case '/': d = read(); if (d == '*') tok = ccomment(); else if (d == '/') tok = cppcomment(); else if (d == '=') tok = new Token(Token.DIV_EQ); else unread(d); break; case '%': d = read(); if (d == '=') tok = new Token(Token.MOD_EQ); else if (digraphs && d == '>') tok = new Token('}'); // digraph else if (digraphs && d == ':') { bool paste = true; d = read(); if (d != '%') { unread(d); tok = new Token('#'); // digraph paste = false; } d = read(); if (d != ':') { unread(d); // Unread 2 chars here. unread('%'); tok = new Token('#'); // digraph paste = false; } if(paste) { tok = new Token(Token.PASTE); // digraph } } else unread(d); break; case ':': /* :: */ d = read(); if (digraphs && d == '>') tok = new Token(']'); // digraph else unread(d); break; case '<': if (include) { tok = String('<', '>'); } else { d = read(); if (d == '=') tok = new Token(Token.LE); else if (d == '<') tok = cond('=', Token.LSH_EQ, Token.LSH); else if (digraphs && d == ':') tok = new Token('['); // digraph else if (digraphs && d == '%') tok = new Token('{'); // digraph else unread(d); } break; case '=': tok = cond('=', Token.EQ, '='); break; case '>': d = read(); if (d == '=') tok = new Token(Token.GE); else if (d == '>') tok = cond('=', Token.RSH_EQ, Token.RSH); else unread(d); break; case '^': tok = cond('=', Token.XOR_EQ, '^'); break; case '|': d = read(); if (d == '=') tok = new Token(Token.OR_EQ); else if (d == '|') tok = cond('=', Token.LOR_EQ, Token.LOR); else unread(d); break; case '&': d = read(); if (d == '&') tok = cond('=', Token.LAND_EQ, Token.LAND); else if (d == '=') tok = new Token(Token.AND_EQ); else unread(d); break; case '.': d = read(); if (d == '.') tok = cond('.', Token.ELLIPSIS, Token.RANGE); else unread(d); /* XXX decimal fraction */ break; case '0': /* octal or hex */ d = read(); if (d == 'x' || d == 'X') tok = number_hex((char)d); else { unread(d); tok = number_octal(); } break; case '\'': tok = character(); break; case '"': tok = String('"', '"'); break; case -1: close(); tok = new Token(Token.EOF, _l, _c, "<eof>"); break; } if (tok == null) { if (char.IsWhiteSpace((char)c)) { tok = whitespace(c); } else if (char.IsDigit((char)c)) { tok = number_decimal(c); } else if (isJavaIdentifierStart(c)) { tok = identifier(c); } else { tok = new Token(c); } } if (bol) { switch (tok.getType()) { case Token.WHITESPACE: case Token.CCOMMENT: break; default: bol = false; break; } } tok.setLocation(_l, _c); if (DEBUG) Debug.WriteLine("lx: Returning " + tok); // (new Exception("here")).printStackTrace(System.out); return tok; } public override void close() { if(reader != null) { reader.close(); reader = null; } base.close(); } } }
// 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.Reflection; using System.Globalization; using System.Threading; using System.Diagnostics; using System.Collections; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Runtime.InteropServices; using System.Configuration.Assemblies; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.Reflection { [Serializable] internal enum CorElementType : byte { End = 0x00, Void = 0x01, Boolean = 0x02, Char = 0x03, I1 = 0x04, U1 = 0x05, I2 = 0x06, U2 = 0x07, I4 = 0x08, U4 = 0x09, I8 = 0x0A, U8 = 0x0B, R4 = 0x0C, R8 = 0x0D, String = 0x0E, Ptr = 0x0F, ByRef = 0x10, ValueType = 0x11, Class = 0x12, Var = 0x13, Array = 0x14, GenericInst = 0x15, TypedByRef = 0x16, I = 0x18, U = 0x19, FnPtr = 0x1B, Object = 0x1C, SzArray = 0x1D, MVar = 0x1E, CModReqd = 0x1F, CModOpt = 0x20, Internal = 0x21, Max = 0x22, Modifier = 0x40, Sentinel = 0x41, Pinned = 0x45, } [Serializable] [Flags()] internal enum MdSigCallingConvention : byte { CallConvMask = 0x0f, // Calling convention is bottom 4 bits Default = 0x00, C = 0x01, StdCall = 0x02, ThisCall = 0x03, FastCall = 0x04, Vararg = 0x05, Field = 0x06, LocalSig = 0x07, Property = 0x08, Unmgd = 0x09, GenericInst = 0x0a, // generic method instantiation Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count) HasThis = 0x20, // Top bit indicates a 'this' parameter ExplicitThis = 0x40, // This parameter is explicitly in the signature } [Serializable] [Flags()] internal enum PInvokeAttributes { NoMangle = 0x0001, CharSetMask = 0x0006, CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, BestFitUseAssem = 0x0000, BestFitEnabled = 0x0010, BestFitDisabled = 0x0020, BestFitMask = 0x0030, ThrowOnUnmappableCharUseAssem = 0x0000, ThrowOnUnmappableCharEnabled = 0x1000, ThrowOnUnmappableCharDisabled = 0x2000, ThrowOnUnmappableCharMask = 0x3000, SupportsLastError = 0x0040, CallConvMask = 0x0700, CallConvWinapi = 0x0100, CallConvCdecl = 0x0200, CallConvStdcall = 0x0300, CallConvThiscall = 0x0400, CallConvFastcall = 0x0500, MaxValue = 0xFFFF, } [Serializable] [Flags()] internal enum MethodSemanticsAttributes { Setter = 0x0001, Getter = 0x0002, Other = 0x0004, AddOn = 0x0008, RemoveOn = 0x0010, Fire = 0x0020, } [Serializable] internal enum MetadataTokenType { Module = 0x00000000, TypeRef = 0x01000000, TypeDef = 0x02000000, FieldDef = 0x04000000, MethodDef = 0x06000000, ParamDef = 0x08000000, InterfaceImpl = 0x09000000, MemberRef = 0x0a000000, CustomAttribute = 0x0c000000, Permission = 0x0e000000, Signature = 0x11000000, Event = 0x14000000, Property = 0x17000000, ModuleRef = 0x1a000000, TypeSpec = 0x1b000000, Assembly = 0x20000000, AssemblyRef = 0x23000000, File = 0x26000000, ExportedType = 0x27000000, ManifestResource = 0x28000000, GenericPar = 0x2a000000, MethodSpec = 0x2b000000, String = 0x70000000, Name = 0x71000000, BaseType = 0x72000000, Invalid = 0x7FFFFFFF, } [Serializable] internal struct ConstArray { public IntPtr Signature { get { return m_constArray; } } public int Length { get { return m_length; } } public byte this[int index] { get { if (index < 0 || index >= m_length) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); unsafe { return ((byte*)m_constArray.ToPointer())[index]; } } } // Keep the definition in sync with vm\ManagedMdImport.hpp internal int m_length; internal IntPtr m_constArray; } [Serializable] internal struct MetadataToken { #region Implicit Cast Operators public static implicit operator int(MetadataToken token) { return token.Value; } public static implicit operator MetadataToken(int token) { return new MetadataToken(token); } #endregion #region Public Static Members public static bool IsTokenOfType(int token, params MetadataTokenType[] types) { for (int i = 0; i < types.Length; i++) { if ((int)(token & 0xFF000000) == (int)types[i]) return true; } return false; } public static bool IsNullToken(int token) { return (token & 0x00FFFFFF) == 0; } #endregion #region Public Data Members public int Value; #endregion #region Constructor public MetadataToken(int token) { Value = token; } #endregion #region Public Members public bool IsGlobalTypeDefToken { get { return (Value == 0x02000001); } } public MetadataTokenType TokenType { get { return (MetadataTokenType)(Value & 0xFF000000); } } public bool IsTypeRef { get { return TokenType == MetadataTokenType.TypeRef; } } public bool IsTypeDef { get { return TokenType == MetadataTokenType.TypeDef; } } public bool IsFieldDef { get { return TokenType == MetadataTokenType.FieldDef; } } public bool IsMethodDef { get { return TokenType == MetadataTokenType.MethodDef; } } public bool IsMemberRef { get { return TokenType == MetadataTokenType.MemberRef; } } public bool IsEvent { get { return TokenType == MetadataTokenType.Event; } } public bool IsProperty { get { return TokenType == MetadataTokenType.Property; } } public bool IsParamDef { get { return TokenType == MetadataTokenType.ParamDef; } } public bool IsTypeSpec { get { return TokenType == MetadataTokenType.TypeSpec; } } public bool IsMethodSpec { get { return TokenType == MetadataTokenType.MethodSpec; } } public bool IsString { get { return TokenType == MetadataTokenType.String; } } public bool IsSignature { get { return TokenType == MetadataTokenType.Signature; } } public bool IsModule { get { return TokenType == MetadataTokenType.Module; } } public bool IsAssembly { get { return TokenType == MetadataTokenType.Assembly; } } public bool IsGenericPar { get { return TokenType == MetadataTokenType.GenericPar; } } #endregion #region Object Overrides public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "0x{0:x8}", Value); } #endregion } internal unsafe struct MetadataEnumResult { // Keep the definition in sync with vm\ManagedMdImport.hpp private int[] largeResult; private int length; private fixed int smallResult[16]; public int Length { get { return length; } } public int this[int index] { get { Contract.Requires(0 <= index && index < Length); if (largeResult != null) return largeResult[index]; fixed (int* p = smallResult) return p[index]; } } } internal struct MetadataImport { #region Private Data Members private IntPtr m_metadataImport2; private object m_keepalive; #endregion #region Override methods from Object internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null); public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(m_metadataImport2); } public override bool Equals(object obj) { if (!(obj is MetadataImport)) return false; return Equals((MetadataImport)obj); } private bool Equals(MetadataImport import) { return import.m_metadataImport2 == m_metadataImport2; } #endregion #region Static Members [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex); internal static void GetMarshalAs(ConstArray nativeType, out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex) { int _unmanagedType, _safeArraySubType, _arraySubType; _GetMarshalAs(nativeType.Signature, (int)nativeType.Length, out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType, out _arraySubType, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie, out iidParamIndex); unmanagedType = (UnmanagedType)_unmanagedType; safeArraySubType = (VarEnum)_safeArraySubType; arraySubType = (UnmanagedType)_arraySubType; } #endregion #region Internal Static Members internal static void ThrowError(int hResult) { throw new MetadataException(hResult); } #endregion #region Constructor internal MetadataImport(IntPtr metadataImport2, object keepalive) { m_metadataImport2 = metadataImport2; m_keepalive = keepalive; } #endregion #region FCalls [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result); public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result) { _Enum(m_metadataImport2, (int)type, parent, out result); } public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.TypeDef, mdTypeDef, out result); } public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result) { Enum(MetadataTokenType.CustomAttribute, mdToken, out result); } public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result) { Enum(MetadataTokenType.ParamDef, mdMethodDef, out result); } public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.FieldDef, mdTypeDef, out result); } public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Property, mdTypeDef, out result); } public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Event, mdTypeDef, out result); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) { int _corElementType; String stringVal; stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType); corElementType = (CorElementType)_corElementType; return stringVal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length); public unsafe String GetUserString(int mdToken) { void* name; int length; _GetUserString(m_metadataImport2, mdToken, &name, out length); if (name == null) return null; char[] c = new char[length]; for (int i = 0; i < c.Length; i++) { #if ALIGN_ACCESS c[i] = (char)Marshal.ReadInt16( (IntPtr) (((char*)name) + i) ); #else c[i] = ((char*)name)[i]; #endif } return new String(c); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name); public unsafe Utf8String GetName(int mdToken) { void* name; _GetName(m_metadataImport2, mdToken, &name); return new Utf8String(name); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp); public unsafe Utf8String GetNamespace(int mdToken) { void* namesp; _GetNamespace(m_metadataImport2, mdToken, &namesp); return new Utf8String(namesp); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes); public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes) { int _eventAttributes; void* _name; _GetEventProps(m_metadataImport2, mdToken, &_name, out _eventAttributes); name = _name; eventAttributes = (EventAttributes)_eventAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes); public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes) { int _fieldAttributes; _GetFieldDefProps(m_metadataImport2, mdToken, out _fieldAttributes); fieldAttributes = (FieldAttributes)_fieldAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPropertyProps(IntPtr scope, int mdToken, void** name, out int propertyAttributes, out ConstArray signature); public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature) { int _propertyAttributes; void* _name; _GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature); name = _name; propertyAttributes = (PropertyAttributes)_propertyAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetParentToken(IntPtr scope, int mdToken, out int tkParent); public int GetParentToken(int tkToken) { int tkParent; _GetParentToken(m_metadataImport2, tkToken, out tkParent); return tkParent; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetParamDefProps(IntPtr scope, int parameterToken, out int sequence, out int attributes); public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes) { int _attributes; _GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out _attributes); attributes = (ParameterAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetGenericParamProps(IntPtr scope, int genericParameter, out int flags); public void GetGenericParamProps( int genericParameter, out GenericParameterAttributes attributes) { int _attributes; _GetGenericParamProps(m_metadataImport2, genericParameter, out _attributes); attributes = (GenericParameterAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetScopeProps(IntPtr scope, out Guid mvid); public void GetScopeProps( out Guid mvid) { _GetScopeProps(m_metadataImport2, out mvid); } public ConstArray GetMethodSignature(MetadataToken token) { if (token.IsMemberRef) return GetMemberRefProps(token); return GetSigOfMethodDef(token); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfMethodDef(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSigOfMethodDef(int methodToken) { ConstArray signature = new ConstArray(); _GetSigOfMethodDef(m_metadataImport2, methodToken, ref signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSignatureFromToken(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSignatureFromToken(int token) { ConstArray signature = new ConstArray(); _GetSignatureFromToken(m_metadataImport2, token, ref signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMemberRefProps(IntPtr scope, int memberTokenRef, out ConstArray signature); public ConstArray GetMemberRefProps(int memberTokenRef) { ConstArray signature = new ConstArray(); _GetMemberRefProps(m_metadataImport2, memberTokenRef, out signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetCustomAttributeProps(IntPtr scope, int customAttributeToken, out int constructorToken, out ConstArray signature); public void GetCustomAttributeProps( int customAttributeToken, out int constructorToken, out ConstArray signature) { _GetCustomAttributeProps(m_metadataImport2, customAttributeToken, out constructorToken, out signature); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetClassLayout(IntPtr scope, int typeTokenDef, out int packSize, out int classSize); public void GetClassLayout( int typeTokenDef, out int packSize, out int classSize) { _GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _GetFieldOffset(IntPtr scope, int typeTokenDef, int fieldTokenDef, out int offset); public bool GetFieldOffset( int typeTokenDef, int fieldTokenDef, out int offset) { return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfFieldDef(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetSigOfFieldDef(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); _GetSigOfFieldDef(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetFieldMarshal(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetFieldMarshal(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); _GetFieldMarshal(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPInvokeMap(IntPtr scope, int token, out int attributes, void** importName, void** importDll); public unsafe void GetPInvokeMap( int token, out PInvokeAttributes attributes, out String importName, out String importDll) { int _attributes; void* _importName, _importDll; _GetPInvokeMap(m_metadataImport2, token, out _attributes, &_importName, &_importDll); importName = new Utf8String(_importName).ToString(); importDll = new Utf8String(_importDll).ToString(); attributes = (PInvokeAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _IsValidToken(IntPtr scope, int token); public bool IsValidToken(int token) { return _IsValidToken(m_metadataImport2, token); } #endregion } internal class MetadataException : Exception { private int m_hr; internal MetadataException(int hr) { m_hr = hr; } public override string ToString() { return String.Format(CultureInfo.CurrentCulture, "MetadataException HResult = {0:x}.", m_hr); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B06_Country (editable child object).<br/> /// This is a generated base class of <see cref="B06_Country"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B07_RegionObjects"/> of type <see cref="B07_RegionColl"/> (1:M relation to <see cref="B08_Region"/>)<br/> /// This class is an item of <see cref="B05_CountryColl"/> collection. /// </remarks> [Serializable] public partial class B06_Country : BusinessBase<B06_Country> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_SubContinent_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Country ID"); /// <summary> /// Gets the Country ID. /// </summary> /// <value>The Country ID.</value> public int Country_ID { get { return GetProperty(Country_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Country_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Country Name"); /// <summary> /// Gets or sets the Country Name. /// </summary> /// <value>The Country Name.</value> public string Country_Name { get { return GetProperty(Country_NameProperty); } set { SetProperty(Country_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B07_Country_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B07_Country_Child> B07_Country_SingleObjectProperty = RegisterProperty<B07_Country_Child>(p => p.B07_Country_SingleObject, "B07 Country Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B07 Country Single Object ("parent load" child property). /// </summary> /// <value>The B07 Country Single Object.</value> public B07_Country_Child B07_Country_SingleObject { get { return GetProperty(B07_Country_SingleObjectProperty); } private set { LoadProperty(B07_Country_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B07_Country_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B07_Country_ReChild> B07_Country_ASingleObjectProperty = RegisterProperty<B07_Country_ReChild>(p => p.B07_Country_ASingleObject, "B07 Country ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B07 Country ASingle Object ("parent load" child property). /// </summary> /// <value>The B07 Country ASingle Object.</value> public B07_Country_ReChild B07_Country_ASingleObject { get { return GetProperty(B07_Country_ASingleObjectProperty); } private set { LoadProperty(B07_Country_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B07_RegionObjects"/> property. /// </summary> public static readonly PropertyInfo<B07_RegionColl> B07_RegionObjectsProperty = RegisterProperty<B07_RegionColl>(p => p.B07_RegionObjects, "B07 Region Objects", RelationshipTypes.Child); /// <summary> /// Gets the B07 Region Objects ("parent load" child property). /// </summary> /// <value>The B07 Region Objects.</value> public B07_RegionColl B07_RegionObjects { get { return GetProperty(B07_RegionObjectsProperty); } private set { LoadProperty(B07_RegionObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B06_Country"/> object. /// </summary> /// <returns>A reference to the created <see cref="B06_Country"/> object.</returns> internal static B06_Country NewB06_Country() { return DataPortal.CreateChild<B06_Country>(); } /// <summary> /// Factory method. Loads a <see cref="B06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B06_Country"/> object.</returns> internal static B06_Country GetB06_Country(SafeDataReader dr) { B06_Country obj = new B06_Country(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(B07_RegionObjectsProperty, B07_RegionColl.NewB07_RegionColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B06_Country"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B06_Country() { // 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="B06_Country"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B07_Country_SingleObjectProperty, DataPortal.CreateChild<B07_Country_Child>()); LoadProperty(B07_Country_ASingleObjectProperty, DataPortal.CreateChild<B07_Country_ReChild>()); LoadProperty(B07_RegionObjectsProperty, DataPortal.CreateChild<B07_RegionColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID")); LoadProperty(Country_NameProperty, dr.GetString("Country_Name")); // parent properties parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="B07_Country_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B07_Country_Child child) { LoadProperty(B07_Country_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="B07_Country_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B07_Country_ReChild child) { LoadProperty(B07_Country_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="B06_Country"/> 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("AddB06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B06_Country"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateB06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B06_Country"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteB06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(B07_Country_SingleObjectProperty, DataPortal.CreateChild<B07_Country_Child>()); LoadProperty(B07_Country_ASingleObjectProperty, DataPortal.CreateChild<B07_Country_ReChild>()); LoadProperty(B07_RegionObjectsProperty, DataPortal.CreateChild<B07_RegionColl>()); } #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.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.Models; using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.XmlPublishedCache; namespace Umbraco.Tests.PublishedContent { [TestFixture] public class StronglyTypedQueryTests : PublishedContentTestBase { public override void Initialize() { base.Initialize(); } public override void TearDown() { base.TearDown(); } protected override DatabaseBehavior DatabaseTestBehavior { get { return DatabaseBehavior.NoDatabasePerFixture; } } protected override string GetXmlContent(int templateId) { return @"<?xml version=""1.0"" encoding=""utf-8""?> <!DOCTYPE root[ <!ELEMENT Home ANY> <!ATTLIST Home id ID #REQUIRED> <!ELEMENT NewsArticle ANY> <!ATTLIST NewsArticle id ID #REQUIRED> <!ELEMENT NewsLandingPage ANY> <!ATTLIST NewsLandingPage id ID #REQUIRED> <!ELEMENT ContentPage ANY> <!ATTLIST ContentPage id ID #REQUIRED> ]> <root id=""-1""> <Home id=""1"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""10"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1"" isDoc=""""> <siteName><![CDATA[Test site]]></siteName> <siteDescription><![CDATA[this is a test site]]></siteDescription> <bodyContent><![CDATA[This is some body content on the home page]]></bodyContent> <NewsLandingPage id=""2"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""11"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""news"" urlName=""news"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2"" isDoc=""""> <bodyContent><![CDATA[This is some body content on the news landing page]]></bodyContent> <pageTitle><![CDATA[page2/alias, 2ndpagealias]]></pageTitle> <NewsArticle id=""3"" parentID=""2"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""12"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Something happened"" urlName=""something-happened"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2,3"" isDoc=""""> <articleContent><![CDATA[Some cool stuff happened today]]></articleContent> <articleDate><![CDATA[2012-01-02 12:33:44]]></articleDate> <articleAuthor><![CDATA[John doe]]></articleAuthor> </NewsArticle> <NewsArticle id=""4"" parentID=""2"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""12"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Then another thing"" urlName=""then-another-thing"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2,4"" isDoc=""""> <articleContent><![CDATA[Today, other cool things occurred]]></articleContent> <articleDate><![CDATA[2012-01-03 15:33:44]]></articleDate> <articleAuthor><![CDATA[John Smith]]></articleAuthor> </NewsArticle> </NewsLandingPage> <ContentPage id=""5"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""13"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""First Content Page"" urlName=""content-page-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1,5"" isDoc=""""> <bodyContent><![CDATA[This is some body content on the first content page]]></bodyContent> </ContentPage> <ContentPage id=""6"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""13"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""Second Content Page"" urlName=""content-page-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1,6"" isDoc=""""> <bodyContent><![CDATA[This is some body content on the second content page]]></bodyContent> </ContentPage> </Home> </root>"; } internal IPublishedContent GetNode(int id) { var ctx = UmbracoContext.Current; var doc = ctx.ContentCache.GetById(id); Assert.IsNotNull(doc); return doc; } [Test] public void Type_Test() { var doc = GetNode(1); var result = doc.NewsArticles(TraversalType.Descendants).ToArray(); Assert.AreEqual("John doe", result[0].ArticleAuthor); Assert.AreEqual("John Smith", result[1].ArticleAuthor); } [Test] public void As_Test() { var doc = GetNode(1); var result = doc.AsHome(); Assert.AreEqual("Test site", result.SiteName); Assert.Throws<InvalidOperationException>(() => doc.AsContentPage()); } } //NOTE: Some of these class will be moved in to the core once all this is working the way we want #region Gen classes & supporting classes //TOOD: SD: This class could be the way that the UmbracoHelper deals with looking things up in the background, we might not // even expose it publicly but it could handle any caching (per request) that might be required when looking up any objects... // though we might not need it at all, not sure yet. // However, what we need to do is implement the GetDocumentsByType method of the IPublishedStore, see the TODO there. // It might be nicer to have a QueryContext on the UmbracoHelper (we can still keep the Content and TypedContent, etc... // methods, but these would just wrap the QueryContext attached to it. Other methods on the QueryContext will be // ContentByType, TypedContentByType, etc... then we can also have extension methods like below for strongly typed // access like: GetAllHomes, GetAllNewsArticles, etc... //public class QueryDataContext //{ // private readonly IPublishedContentStore _contentStore; // private readonly UmbracoContext _umbracoContext; // internal QueryDataContext(IPublishedContentStore contentStore, UmbracoContext umbracoContext) // { // _contentStore = contentStore; // _umbracoContext = umbracoContext; // } // public IPublishedContent GetDocumentById(int id) // { // return _contentStore.GetDocumentById(_umbracoContext, id); // } // public IEnumerable<IPublishedContent> GetByDocumentType(string alias) // { // } //} public enum TraversalType { Children, Ancestors, AncestorsOrSelf, Descendants, DescendantsOrSelf } public static class StronglyTypedQueryExtensions { private static IEnumerable<IPublishedContent> GetEnumerable(this IPublishedContent content, string docTypeAlias, TraversalType traversalType = TraversalType.Children) { switch (traversalType) { case TraversalType.Children: return content.Children.Where(x => x.DocumentTypeAlias == docTypeAlias); case TraversalType.Ancestors: return content.Ancestors().Where(x => x.DocumentTypeAlias == docTypeAlias); case TraversalType.AncestorsOrSelf: return content.AncestorsOrSelf().Where(x => x.DocumentTypeAlias == docTypeAlias); case TraversalType.Descendants: return content.Descendants().Where(x => x.DocumentTypeAlias == docTypeAlias); case TraversalType.DescendantsOrSelf: return content.DescendantsOrSelf().Where(x => x.DocumentTypeAlias == docTypeAlias); default: throw new ArgumentOutOfRangeException("traversalType"); } } private static T AsDocumentType<T>(this IPublishedContent content, string alias, Func<IPublishedContent, T> creator) { if (content.DocumentTypeAlias == alias) return creator(content); throw new InvalidOperationException("The content type cannot be cast to " + typeof(T).FullName + " since it is type: " + content.DocumentTypeAlias); } public static HomeContentItem AsHome(this IPublishedContent content) { return content.AsDocumentType("Home", x => new HomeContentItem(x)); } public static IEnumerable<HomeContentItem> Homes(this IPublishedContent content, TraversalType traversalType = TraversalType.Children) { return content.GetEnumerable("Home", traversalType).Select(x => new HomeContentItem(x)); } public static NewsArticleContentItem AsNewsArticle(this IPublishedContent content) { return content.AsDocumentType("NewsArticle", x => new NewsArticleContentItem(x)); } public static IEnumerable<NewsArticleContentItem> NewsArticles(this IPublishedContent content, TraversalType traversalType = TraversalType.Children) { return content.GetEnumerable("NewsArticle", traversalType).Select(x => new NewsArticleContentItem(x)); } public static NewsLandingPageContentItem AsNewsLandingPage(this IPublishedContent content) { return content.AsDocumentType("NewsLandingPage", x => new NewsLandingPageContentItem(x)); } public static IEnumerable<NewsLandingPageContentItem> NewsLandingPages(this IPublishedContent content, TraversalType traversalType = TraversalType.Children) { return content.GetEnumerable("NewsLandingPage", traversalType).Select(x => new NewsLandingPageContentItem(x)); } public static ContentPageContentItem AsContentPage(this IPublishedContent content) { return content.AsDocumentType("ContentPage", x => new ContentPageContentItem(x)); } public static IEnumerable<ContentPageContentItem> ContentPages(this IPublishedContent content, TraversalType traversalType = TraversalType.Children) { return content.GetEnumerable("ContentPage", traversalType).Select(x => new ContentPageContentItem(x)); } } public class PublishedContentWrapper : IPublishedContent, IOwnerCollectionAware<IPublishedContent> { protected IPublishedContent WrappedContent { get; private set; } public PublishedContentWrapper(IPublishedContent content) { WrappedContent = content; } public string Url { get { return WrappedContent.Url; } } public PublishedItemType ItemType { get { return WrappedContent.ItemType; } } public IPublishedContent Parent { get { return WrappedContent.Parent; } } public int Id { get { return WrappedContent.Id; } } public int TemplateId { get { return WrappedContent.TemplateId; } } public int SortOrder { get { return WrappedContent.SortOrder; } } public string Name { get { return WrappedContent.Name; } } public string UrlName { get { return WrappedContent.UrlName; } } public string DocumentTypeAlias { get { return WrappedContent.DocumentTypeAlias; } } public int DocumentTypeId { get { return WrappedContent.DocumentTypeId; } } public string WriterName { get { return WrappedContent.WriterName; } } public string CreatorName { get { return WrappedContent.CreatorName; } } public int WriterId { get { return WrappedContent.WriterId; } } public int CreatorId { get { return WrappedContent.CreatorId; } } public string Path { get { return WrappedContent.Path; } } public DateTime CreateDate { get { return WrappedContent.CreateDate; } } public DateTime UpdateDate { get { return WrappedContent.UpdateDate; } } public Guid Version { get { return WrappedContent.Version; } } public int Level { get { return WrappedContent.Level; } } public ICollection<IPublishedContentProperty> Properties { get { return WrappedContent.Properties; } } public object this[string propertyAlias] { get { return GetProperty(propertyAlias).Value; } } public IEnumerable<IPublishedContent> Children { get { return WrappedContent.Children; } } public IPublishedContentProperty GetProperty(string alias) { return WrappedContent.GetProperty(alias); } private IEnumerable<IPublishedContent> _ownersCollection; /// <summary> /// Need to get/set the owner collection when an item is returned from the result set of a query /// </summary> /// <remarks> /// Based on this issue here: http://issues.umbraco.org/issue/U4-1797 /// </remarks> IEnumerable<IPublishedContent> IOwnerCollectionAware<IPublishedContent>.OwnersCollection { get { var publishedContentBase = WrappedContent as IOwnerCollectionAware<IPublishedContent>; if (publishedContentBase != null) { return publishedContentBase.OwnersCollection; } //if the owners collection is null, we'll default to it's siblings if (_ownersCollection == null) { //get the root docs if parent is null _ownersCollection = this.Siblings(); } return _ownersCollection; } set { var publishedContentBase = WrappedContent as IOwnerCollectionAware<IPublishedContent>; if (publishedContentBase != null) { publishedContentBase.OwnersCollection = value; } else { _ownersCollection = value; } } } } public partial class HomeContentItem : ContentPageContentItem { public HomeContentItem(IPublishedContent content) : base(content) { } public string SiteName { get { return WrappedContent.GetPropertyValue<string>("siteName"); } } public string SiteDescription { get { return WrappedContent.GetPropertyValue<string>("siteDescription"); } } } public partial class NewsLandingPageContentItem : ContentPageContentItem { public NewsLandingPageContentItem(IPublishedContent content) : base(content) { } public string PageTitle { get { return WrappedContent.GetPropertyValue<string>("pageTitle"); } } } public partial class NewsArticleContentItem : PublishedContentWrapper { public NewsArticleContentItem(IPublishedContent content) : base(content) { } public string ArticleContent { get { return WrappedContent.GetPropertyValue<string>("articleContent"); } } public DateTime ArticleDate { get { return WrappedContent.GetPropertyValue<DateTime>("articleDate"); } } public string ArticleAuthor { get { return WrappedContent.GetPropertyValue<string>("articleAuthor"); } } } public partial class ContentPageContentItem : PublishedContentWrapper { public ContentPageContentItem(IPublishedContent content) : base(content) { } public string BodyContent { get { return WrappedContent.GetPropertyValue<string>("bodyContent"); } } } #endregion }
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; namespace CH16___Top_Down_Scroller { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // single-instance game objects protected static ScrollingBackground m_background = new ScrollingBackground(); public static Player m_PlayerOne = new Player(); public static Player m_PlayerTwo = new Player(); protected static HUD m_Hud = new HUD(); // the one and only game texture protected static Texture2D m_Texture; public static Texture2D Texture { get { return m_Texture; } set { m_Texture = value; } } // a simple helper property to let supporting // routines know when both players are inactive public static bool GameOver { get { return !(m_PlayerOne.IsActive || m_PlayerTwo.IsActive); } } public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <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() { //// use a fixed frame rate of 30 frames per second //IsFixedTimeStep = true; //TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33); // run at full speed IsFixedTimeStep = false; // set screen size InitScreen(); // initialize the brains of our game GameObjectManager.Init(); // initialize our scrolling background helper m_background.InitTiles(); // data that's specific to player one m_PlayerOne.StartPosition = new Vector2(160, 360); m_PlayerOne.Color = Color.Tomato; m_PlayerOne.HudPosition = new Vector2(64, 64); // data that's specific to player two m_PlayerTwo.StartPosition = new Vector2(480, 360); m_PlayerTwo.Color = Color.SlateBlue; m_PlayerTwo.HudPosition = new Vector2(384, 64); base.Initialize(); } // screen constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; // screen-related init tasks public void InitScreen() { // back buffer graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferMultiSampling = false; graphics.ApplyChanges(); } /// <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); Game1.Texture = Content.Load<Texture2D>(@"media\game"); NumberSprite.Texture = Content.Load<Texture2D>(@"media\numbers"); } /// <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) this.Exit(); // time (in seconds) since the last time Update was called double elapsed = gameTime.ElapsedGameTime.TotalSeconds; // update game state, attempt to add a new enemy ship GameObjectManager.Update(elapsed); AddEnemy(elapsed); // handle player input ProcessInput(elapsed); // update our single-instance game objects m_background.Update(elapsed); m_PlayerOne.Update(elapsed); m_PlayerTwo.Update(elapsed); m_Hud.Update(elapsed); base.Update(gameTime); } // add a new enemy every two seconds protected double EnemyDelay = 2; protected double EnemyCountDown = 0; protected void AddEnemy(double elapsed) { EnemyCountDown -= elapsed; if (!GameOver && EnemyCountDown < 0) { EnemyCountDown = EnemyDelay; GameObjectManager.AddEnemy(); } } // collect and process player input public void ProcessInput(double elapsed) { // collect input data GamePadState pad1 = GamePad.GetState(PlayerIndex.One); GamePadState pad2 = GamePad.GetState(PlayerIndex.Two); KeyboardState key = Keyboard.GetState(); // process collected data ProcessInput(elapsed, m_PlayerOne, pad1); ProcessInput(elapsed, m_PlayerOne, key); ProcessInput(elapsed, m_PlayerTwo, pad2); } // handle game pad input public void ProcessInput(double elapsed, Player player, GamePadState pad) { if (!player.IsActive && pad.Buttons.Start == ButtonState.Pressed) { // start or join the game player.Init(); player.IsActive = true; } else if (player.IsActive) { // change in location Vector2 delta = Vector2.Zero; // moving left or right? if (pad.ThumbSticks.Left.X < 0) { delta.X = (float)(-player.MovePixelsPerSecond * elapsed); } else if (pad.ThumbSticks.Left.X > 0) { delta.X = (float)(player.MovePixelsPerSecond * elapsed); } // moving up or down? if (pad.ThumbSticks.Left.Y > 0) { delta.Y = (float)(-player.MovePixelsPerSecond * elapsed); } else if (pad.ThumbSticks.Left.Y < 0) { delta.Y = (float)(player.MovePixelsPerSecond * elapsed); } // actually move the player player.Location += delta; // if the player is pressing the action // button, try to fire a bullet if (pad.Buttons.A == ButtonState.Pressed && player.Fire()) { GameObjectManager.AddBullet(player, true); } } } // handle player input from the keyboard public void ProcessInput(double elapsed, Player player, KeyboardState key) { if (!player.IsActive && key.IsKeyDown(Keys.Enter)) { // start or join the game player.Init(); player.IsActive = true; } else if (player.IsActive) { // change in location Vector2 delta = Vector2.Zero; // moving left or right? if (key.IsKeyDown(Keys.Left)) { delta.X = (float)(-player.MovePixelsPerSecond * elapsed); } else if (key.IsKeyDown(Keys.Right)) { delta.X = (float)(player.MovePixelsPerSecond * elapsed); } // moving up or down? if (key.IsKeyDown(Keys.Up)) { delta.Y = (float)(-player.MovePixelsPerSecond * elapsed); } else if (key.IsKeyDown(Keys.Down)) { delta.Y = (float)(player.MovePixelsPerSecond * elapsed); } // actually move the player player.Location += delta; // if the player is pressing the action // button, try to fire a bullet if (key.IsKeyDown(Keys.Space) && player.Fire()) { GameObjectManager.AddBullet(player, true); } } } /// <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) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); m_background.Draw(spriteBatch); GameObjectManager.Draw(spriteBatch); m_PlayerOne.Draw(spriteBatch); m_PlayerTwo.Draw(spriteBatch); m_Hud.Draw(spriteBatch, m_PlayerOne); m_Hud.Draw(spriteBatch, m_PlayerTwo); spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Runtime.InteropServices; using WbemClient_v1; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Contains information about a WMI method.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example shows how to obtain meta data /// // about a WMI method with a given name in a given WMI class /// /// class Sample_MethodData /// { /// public static int Main(string[] args) { /// /// // Get the "SetPowerState" method in the Win32_LogicalDisk class /// ManagementClass diskClass = new ManagementClass("win32_logicaldisk"); /// MethodData m = diskClass.Methods["SetPowerState"]; /// /// // Get method name (albeit we already know it) /// Console.WriteLine("Name: " + m.Name); /// /// // Get the name of the top-most class where this specific method was defined /// Console.WriteLine("Origin: " + m.Origin); /// /// // List names and types of input parameters /// ManagementBaseObject inParams = m.InParameters; /// foreach(PropertyData pdata in inParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("InParam_Name: " + pdata.Name); /// Console.WriteLine("InParam_Type: " + pdata.Type); /// } /// /// // List names and types of output parameters /// ManagementBaseObject outParams = m.OutParameters; /// foreach(PropertyData pdata in outParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("OutParam_Name: " + pdata.Name); /// Console.WriteLine("OutParam_Type: " + pdata.Type); /// } /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example shows how to obtain meta data /// ' about a WMI method with a given name in a given WMI class /// /// Class Sample_ManagementClass /// Overloads Public Shared Function Main(args() As String) As Integer /// /// ' Get the "SetPowerState" method in the Win32_LogicalDisk class /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// Dim m As MethodData = diskClass.Methods("SetPowerState") /// /// ' Get method name (albeit we already know it) /// Console.WriteLine("Name: " &amp; m.Name) /// /// ' Get the name of the top-most class where /// ' this specific method was defined /// Console.WriteLine("Origin: " &amp; m.Origin) /// /// ' List names and types of input parameters /// Dim inParams As ManagementBaseObject /// inParams = m.InParameters /// Dim pdata As PropertyData /// For Each pdata In inParams.Properties /// Console.WriteLine() /// Console.WriteLine("InParam_Name: " &amp; pdata.Name) /// Console.WriteLine("InParam_Type: " &amp; pdata.Type) /// Next pdata /// /// ' List names and types of output parameters /// Dim outParams As ManagementBaseObject /// outParams = m.OutParameters /// For Each pdata in outParams.Properties /// Console.WriteLine() /// Console.WriteLine("OutParam_Name: " &amp; pdata.Name) /// Console.WriteLine("OutParam_Type: " &amp; pdata.Type) /// Next pdata /// /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class MethodData { private ManagementObject parent; //needed to be able to get method qualifiers private string methodName; private IWbemClassObjectFreeThreaded wmiInParams; private IWbemClassObjectFreeThreaded wmiOutParams; private QualifierDataCollection qualifiers; internal MethodData(ManagementObject parent, string methodName) { this.parent = parent; this.methodName = methodName; RefreshMethodInfo(); qualifiers = null; } //This private function is used to refresh the information from the Wmi object before returning the requested data private void RefreshMethodInfo() { int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.GetMethod_(methodName, 0, out wmiInParams, out wmiOutParams); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } } /// <summary> /// <para>Gets or sets the name of the method.</para> /// </summary> /// <value> /// <para>The name of the method.</para> /// </value> public string Name { get { return methodName != null ? methodName : ""; } } /// <summary> /// <para> Gets or sets the input parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it appears in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para> /// A <see cref='System.Management.ManagementBaseObject'/> /// containing all the input parameters to the /// method.</para> /// </value> /// <remarks> /// <para>Each parameter in the object should have an /// <see langword='ID'/> /// qualifier, identifying the order of the parameters in the method call.</para> /// </remarks> public ManagementBaseObject InParameters { get { RefreshMethodInfo(); return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams); } } /// <summary> /// <para> Gets or sets the output parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it will appear in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.ManagementBaseObject'/> containing all the output parameters to the method. </para> /// </value> /// <remarks> /// <para>Each parameter in this object should have an /// <see langword='ID'/> qualifier to identify the /// order of the parameters in the method call.</para> /// <para>The ReturnValue property is a special property of /// the <see cref='System.Management.MethodData.OutParameters'/> /// object and /// holds the return value of the method.</para> /// </remarks> public ManagementBaseObject OutParameters { get { RefreshMethodInfo(); return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams); } } /// <summary> /// <para>Gets the name of the management class in which the method was first /// introduced in the class inheritance hierarchy.</para> /// </summary> /// <value> /// A string representing the originating /// management class name. /// </value> public string Origin { get { string className = null; int status = parent.wbemObject.GetMethodOrigin_(methodName, out className); if (status < 0) { if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_OBJECT) className = String.Empty; // Interpret as an unspecified property - return "" else if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status); } return className; } } /// <summary> /// <para>Gets a collection of qualifiers defined in the /// method. Each element is of type <see cref='System.Management.QualifierData'/> /// and contains information such as the qualifier name, value, and /// flavor.</para> /// </summary> /// <value> /// A <see cref='System.Management.QualifierDataCollection'/> containing the /// qualifiers for this method. /// </value> /// <seealso cref='System.Management.QualifierData'/> public QualifierDataCollection Qualifiers { get { if (qualifiers == null) qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); return qualifiers; } } }//MethodData }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WebApiValidation.Areas.HelpPage.Models; namespace WebApiValidation.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// Data sources for logging in RRDs /// First published in XenServer 5.0. /// </summary> public partial class Data_source : XenObject<Data_source> { public Data_source() { } public Data_source(string name_label, string name_description, bool enabled, bool standard, string units, double min, double max, double value) { this.name_label = name_label; this.name_description = name_description; this.enabled = enabled; this.standard = standard; this.units = units; this.min = min; this.max = max; this.value = value; } /// <summary> /// Creates a new Data_source from a Proxy_Data_source. /// </summary> /// <param name="proxy"></param> public Data_source(Proxy_Data_source proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Data_source update) { name_label = update.name_label; name_description = update.name_description; enabled = update.enabled; standard = update.standard; units = update.units; min = update.min; max = update.max; value = update.value; } internal void UpdateFromProxy(Proxy_Data_source proxy) { name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; enabled = (bool)proxy.enabled; standard = (bool)proxy.standard; units = proxy.units == null ? null : (string)proxy.units; min = Convert.ToDouble(proxy.min); max = Convert.ToDouble(proxy.max); value = Convert.ToDouble(proxy.value); } public Proxy_Data_source ToProxy() { Proxy_Data_source result_ = new Proxy_Data_source(); result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.enabled = enabled; result_.standard = standard; result_.units = (units != null) ? units : ""; result_.min = min; result_.max = max; result_.value = value; return result_; } /// <summary> /// Creates a new Data_source from a Hashtable. /// </summary> /// <param name="table"></param> public Data_source(Hashtable table) { name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); enabled = Marshalling.ParseBool(table, "enabled"); standard = Marshalling.ParseBool(table, "standard"); units = Marshalling.ParseString(table, "units"); min = Marshalling.ParseDouble(table, "min"); max = Marshalling.ParseDouble(table, "max"); value = Marshalling.ParseDouble(table, "value"); } public bool DeepEquals(Data_source other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._enabled, other._enabled) && Helper.AreEqual2(this._standard, other._standard) && Helper.AreEqual2(this._units, other._units) && Helper.AreEqual2(this._min, other._min) && Helper.AreEqual2(this._max, other._max) && Helper.AreEqual2(this._value, other._value); } public override string SaveChanges(Session session, string opaqueRef, Data_source server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// true if the data source is being logged /// </summary> public virtual bool enabled { get { return _enabled; } set { if (!Helper.AreEqual(value, _enabled)) { _enabled = value; Changed = true; NotifyPropertyChanged("enabled"); } } } private bool _enabled; /// <summary> /// true if the data source is enabled by default. Non-default data sources cannot be disabled /// </summary> public virtual bool standard { get { return _standard; } set { if (!Helper.AreEqual(value, _standard)) { _standard = value; Changed = true; NotifyPropertyChanged("standard"); } } } private bool _standard; /// <summary> /// the units of the value /// </summary> public virtual string units { get { return _units; } set { if (!Helper.AreEqual(value, _units)) { _units = value; Changed = true; NotifyPropertyChanged("units"); } } } private string _units; /// <summary> /// the minimum value of the data source /// </summary> public virtual double min { get { return _min; } set { if (!Helper.AreEqual(value, _min)) { _min = value; Changed = true; NotifyPropertyChanged("min"); } } } private double _min; /// <summary> /// the maximum value of the data source /// </summary> public virtual double max { get { return _max; } set { if (!Helper.AreEqual(value, _max)) { _max = value; Changed = true; NotifyPropertyChanged("max"); } } } private double _max; /// <summary> /// current value of the data source /// </summary> public virtual double value { get { return _value; } set { if (!Helper.AreEqual(value, _value)) { _value = value; Changed = true; NotifyPropertyChanged("value"); } } } private double _value; } }
using System; using System.Net; using System.Net.Sockets; using CodeCave.NetworkAgilityPack.Web; namespace CodeCave.NetworkAgilityPack.Socks { internal class SocketWithProxy : Socket { #region Constructors /// <summary> /// Initializes a new instance of the ProxySocket class. /// </summary> /// <param name="addressFamily">One of the AddressFamily values.</param> /// <param name="socketType">One of the SocketType values.</param> /// <param name="protocolType">One of the ProtocolType values.</param> /// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception> /// <exception cref="ArgumentNullException"><c>proxyUsername</c> -or- <c>proxyPassword</c> is null.</exception> private SocketWithProxy(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType) { ProxyType = ProxyType.None; Exception = new WebException(); } /// <summary> /// Initializes a new instance of the <see cref="SocketWithProxy"/> class. /// </summary> /// <param name="addressFamily">The address family.</param> /// <param name="socketType">Type of the socket.</param> /// <param name="protocolType">Type of the protocol.</param> /// <param name="proxyType">Type of the proxy.</param> /// <param name="proxyCredentials">The authentication.</param> internal SocketWithProxy(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, ProxyType proxyType, WebProxyCredential proxyCredentials) : this(addressFamily, socketType, protocolType) { ProxyType = proxyType; ProxyCredentials = proxyCredentials; } #endregion #region Methods #region Sync /// <summary> /// Establishes a connection to a remote device. /// </summary> /// <param name="remoteEndPoint">An EndPoint that represents the remote device.</param> /// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception> /// <exception cref="ObjectDisposedException">The Socket has been closed.</exception> public new void Connect(EndPoint remoteEndPoint) { if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint)); if (ProtocolType != ProtocolType.Tcp || ProxyType == ProxyType.None || ProxyIpEndPoint == null) base.Connect(remoteEndPoint); else { base.Connect(ProxyIpEndPoint); switch (ProxyType) { case ProxyType.Socks4: (new Socks4Protocol(this, ProxyCredentials.UserName)).Negotiate((IPEndPoint)remoteEndPoint); break; case ProxyType.Socks5: (new Socks5Protocol(this, ProxyCredentials.UserName, ProxyCredentials.Password)).Negotiate((IPEndPoint)remoteEndPoint); break; default: throw new InvalidOperationException($"Wrong proxy type {ProxyType}"); } } } /// <summary> /// Establishes a connection to a remote device. /// </summary> /// <param name="host">The remote host to connect to.</param> /// <param name="port">The remote port to connect to.</param> /// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException">The port parameter is invalid.</exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception> /// <exception cref="ObjectDisposedException">The Socket has been closed.</exception> /// <remarks> /// If you use this method with a SOCKS4 server, it will let the server resolve the hostname. Not all SOCKS4 servers support this 'remote DNS' though. /// </remarks> new public void Connect(string host, int port) { if (host == null) throw new ArgumentNullException(nameof(host)); if (port <= 0 || port > 65535) throw new ArgumentException("Invalid port."); if (ProtocolType != ProtocolType.Tcp || ProxyType == ProxyType.None || ProxyIpEndPoint == null) { base.Connect(new IPEndPoint(host.ResolveHostDns(), port)); } else { base.Connect(ProxyIpEndPoint); switch (ProxyType) { case ProxyType.Socks4: (new Socks4Protocol(this, ProxyCredentials.UserName)).Negotiate(host, port); break; case ProxyType.Socks5: (new Socks5Protocol(this, ProxyCredentials.UserName, ProxyCredentials.Password)).Negotiate(host, port); break; default: throw new InvalidOperationException($"Wrong proxy type {ProxyType}"); } } } #endregion #region Async /// <summary> /// Begins an asynchronous request for a connection to a network device. /// </summary> /// <param name="remoteEndPoint">An EndPoint that represents the remote device.</param> /// <param name="callback">The AsyncCallback delegate.</param> /// <param name="state">An object that contains state information for this request.</param> /// <returns> /// An IAsyncResult that references the asynchronous connection. /// </returns> /// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception> /// <exception cref="ObjectDisposedException">The Socket has been closed.</exception> public new IAsyncResult BeginConnect(EndPoint remoteEndPoint, AsyncCallback callback, object state) { if (remoteEndPoint == null || callback == null) throw new ArgumentNullException(); if (ProtocolType != ProtocolType.Tcp || ProxyType == ProxyType.None || ProxyIpEndPoint == null) { Exception = null; return base.BeginConnect(remoteEndPoint, callback, state); } CallBack = callback; AsyncResult = null; switch (ProxyType) { case ProxyType.Socks4: AsyncResult = (new Socks4Protocol(this, ProxyCredentials.UserName)).BeginNegotiate((IPEndPoint)remoteEndPoint, OnHandShakeComplete, ProxyIpEndPoint); break; case ProxyType.Socks5: AsyncResult = (new Socks5Protocol(this, ProxyCredentials.UserName, ProxyCredentials.Password)).BeginNegotiate((IPEndPoint)remoteEndPoint, OnHandShakeComplete, ProxyIpEndPoint); break; default: throw new InvalidOperationException($"Wrong proxy type {ProxyType}"); } return AsyncResult; } /// <summary> /// Begins the connect. /// </summary> /// <param name="addresses">The addresses.</param> /// <param name="port">The port.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException"></exception> public new IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback callback, object state) { if (addresses == null || addresses.Length == 0 || callback == null) throw new ArgumentNullException(); var remoteEndPoint = new IPEndPoint(addresses[0], port); if (ProtocolType != ProtocolType.Tcp || ProxyType == ProxyType.None || ProxyIpEndPoint == null) { Exception = null; return base.BeginConnect(addresses, port, callback, state); } CallBack = callback; AsyncResult = null; switch (ProxyType) { case ProxyType.Socks4: AsyncResult = (new Socks4Protocol(this, ProxyCredentials.UserName)).BeginNegotiate(remoteEndPoint, OnHandShakeComplete, ProxyIpEndPoint); break; case ProxyType.Socks5: AsyncResult = (new Socks5Protocol(this, ProxyCredentials.UserName, ProxyCredentials.Password)).BeginNegotiate(remoteEndPoint, OnHandShakeComplete, ProxyIpEndPoint); break; default: throw new InvalidOperationException($"Wrong proxy type {ProxyType}"); } return AsyncResult; } /// <summary> /// Begins an asynchronous request for a connection to a network device. /// </summary> /// <param name="host">The host to connect to.</param> /// <param name="port">The port on the remote host to connect to.</param> /// <param name="callback">The AsyncCallback delegate.</param> /// <param name="state">An object that contains state information for this request.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException">The port parameter is invalid.</exception> /// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception> /// <exception cref="ObjectDisposedException">The Socket has been closed.</exception> new public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state) { if (host == null || callback == null) throw new ArgumentNullException(); if (port <= 0 || port > 65535) throw new ArgumentException(); CallBack = callback; AsyncResult = null; State = state; if (ProtocolType != ProtocolType.Tcp || ProxyType == ProxyType.None || ProxyIpEndPoint == null) { ProxyPort = port; AsyncResult = BeginDns(host, OnHandShakeComplete); } else { switch (ProxyType) { case ProxyType.Socks4: AsyncResult = (new Socks4Protocol(this, ProxyCredentials.UserName)).BeginNegotiate(host, port, OnHandShakeComplete, ProxyIpEndPoint); break; case ProxyType.Socks5: AsyncResult = (new Socks5Protocol(this, ProxyCredentials.UserName, ProxyCredentials.Password)).BeginNegotiate(host, port, OnHandShakeComplete, ProxyIpEndPoint); break; default: throw new InvalidOperationException($"Wrong proxy type {ProxyType}"); } } return AsyncResult; } /// <summary> /// Ends a pending asynchronous connection request. /// </summary> /// <param name="asyncResult">Stores state information for this asynchronous operation as well as any user-defined data.</param> /// <exception cref="ArgumentNullException">The asyncResult parameter is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException">The asyncResult parameter was not returned by a call to the BeginConnect method.</exception> /// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception> /// <exception cref="ObjectDisposedException">The Socket has been closed.</exception> /// <exception cref="InvalidOperationException">EndConnect was previously called for the asynchronous connection.</exception> public new void EndConnect(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(); if (!asyncResult.IsCompleted) throw new ArgumentException(); if (Exception != null) throw Exception; } /// <summary> /// Begins an asynchronous request to resolve a DNS host name or IP address in dotted-quad notation to an IPAddress instance. /// </summary> /// <param name="host">The host to resolve.</param> /// <param name="callback">The method to call when the hostname has been resolved.</param> /// <returns>An IAsyncResult instance that references the asynchronous request.</returns> /// <exception cref="SocketException">There was an error while trying to resolve the host.</exception> internal AsyncSocksResult BeginDns(string host, HandShakeComplete callback) { try { Dns.BeginGetHostEntry(host, OnResolved, this); return new AsyncSocksResult(); } catch { throw new SocketException(); } } /// <summary> /// Called when the specified hostname has been resolved. /// </summary> /// <param name="asyncResult">The result of the asynchronous operation.</param> private void OnResolved(IAsyncResult asyncResult) { try { var dns = Dns.EndGetHostEntry(asyncResult); base.BeginConnect(new IPEndPoint(dns.AddressList[0], ProxyPort), OnConnect, State); } catch (Exception e) { OnHandShakeComplete(e); } } /// <summary> /// Called when the Socket is connected to the remote host. /// </summary> /// <param name="asyncResult">The result of the asynchronous operation.</param> private void OnConnect(IAsyncResult asyncResult) { try { base.EndConnect(asyncResult); OnHandShakeComplete(null); } catch (Exception e) { OnHandShakeComplete(e); } } /// <summary> /// Called when the Socket has finished talking to the proxy server and is ready to relay data. /// </summary> /// <param name="exception">The error to throw when the EndConnect method is called.</param> private void OnHandShakeComplete(Exception exception) { if (exception != null) Close(); Exception = exception; AsyncResult.Reset(); CallBack?.Invoke(AsyncResult); } #endregion #endregion #region Properties /// <summary> /// Gets or sets the EndPoint of the proxy server. /// </summary> /// <value> /// An IPEndPoint object that holds the IP address and the port of the proxy server. /// </value> public IPEndPoint ProxyIpEndPoint => ProxyCredentials?.IPEndPoint; /// <summary> /// Gets or sets the type of proxy server to use. /// </summary> /// <value>One of the ProxyType values.</value> public ProxyType ProxyType { get; internal set; } /// <summary> /// Gets or sets the remote port the user wants to connect to. /// </summary> /// <value>An integer that specifies the port the user wants to connect to.</value> private int ProxyPort { get; set; } /// <summary> /// Gets the credentials. /// </summary> /// <value> /// The credentials. /// </value> private WebProxyCredential ProxyCredentials { get; } /// <summary> /// Gets or sets the asynchronous result. /// </summary> /// <value> /// The asynchronous result. /// </value> private AsyncSocksResult AsyncResult { get; set; } /// <summary> /// Gets or sets the exception to throw when the EndConnect method is called. /// </summary> /// <value>An instance of the Exception class (or subclasses of Exception).</value> private Exception Exception { get; set; } /// <summary> /// Gets or sets the state. /// </summary> /// <value> /// The state. /// </value> private object State { get; set; } /// <summary> /// Gets or sets the call back. /// </summary> /// <value> /// The call back. /// </value> private AsyncCallback CallBack { get; set; } #endregion } }
/* * Copyright 2012-2021 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI; using Net.Pkcs11Interop.HighLevelAPI.MechanismParams; using Net.Pkcs11Interop.LowLevelAPI40.MechanismParams; using NativeULong = System.UInt32; // Note: Code in this file is generated automatically. namespace Net.Pkcs11Interop.HighLevelAPI40.MechanismParams { /// <summary> /// Resulting key handles and initialization vectors after performing a DeriveKey method with the CKM_SSL3_KEY_AND_MAC_DERIVE mechanism /// </summary> public class CkSsl3KeyMatOut : ICkSsl3KeyMatOut { /// <summary> /// Flag indicating whether instance has been disposed /// </summary> private bool _disposed = false; /// <summary> /// Low level structure /// </summary> internal CK_SSL3_KEY_MAT_OUT _lowLevelStruct = new CK_SSL3_KEY_MAT_OUT(); /// <summary> /// Key handle for the resulting Client MAC Secret key /// </summary> public IObjectHandle ClientMacSecret { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return new ObjectHandle(_lowLevelStruct.ClientMacSecret); } } /// <summary> /// Key handle for the resulting Server MAC Secret key /// </summary> public IObjectHandle ServerMacSecret { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return new ObjectHandle(_lowLevelStruct.ServerMacSecret); } } /// <summary> /// Key handle for the resulting Client Secret key /// </summary> public IObjectHandle ClientKey { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return new ObjectHandle(_lowLevelStruct.ClientKey); } } /// <summary> /// Key handle for the resulting Server Secret key /// </summary> public IObjectHandle ServerKey { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return new ObjectHandle(_lowLevelStruct.ServerKey); } } /// <summary> /// Initialization vector (IV) created for the client /// </summary> public byte[] IVClient { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVClient, ConvertUtils.UInt32ToInt32(_ivLength)); } } /// <summary> /// Initialization vector (IV) created for the server /// </summary> public byte[] IVServer { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVServer, ConvertUtils.UInt32ToInt32(_ivLength)); } } /// <summary> /// The length of initialization vectors /// </summary> private NativeULong _ivLength = 0; /// <summary> /// Initializes a new instance of the CkSsl3KeyMatOut class. /// </summary> /// <param name='ivLength'>Length of initialization vectors or 0 if IVs are not required</param> internal CkSsl3KeyMatOut(NativeULong ivLength) { _lowLevelStruct.ClientMacSecret = 0; _lowLevelStruct.ServerMacSecret = 0; _lowLevelStruct.ClientKey = 0; _lowLevelStruct.ServerKey = 0; _lowLevelStruct.IVClient = IntPtr.Zero; _lowLevelStruct.IVServer = IntPtr.Zero; _ivLength = ivLength; if (_ivLength > 0) { _lowLevelStruct.IVClient = UnmanagedMemory.Allocate(ConvertUtils.UInt32ToInt32(_ivLength)); _lowLevelStruct.IVServer = UnmanagedMemory.Allocate(ConvertUtils.UInt32ToInt32(_ivLength)); } } #region IDisposable /// <summary> /// Disposes object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes object /// </summary> /// <param name="disposing">Flag indicating whether managed resources should be disposed</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // Dispose managed objects } // Dispose unmanaged objects UnmanagedMemory.Free(ref _lowLevelStruct.IVClient); UnmanagedMemory.Free(ref _lowLevelStruct.IVServer); _disposed = true; } } /// <summary> /// Class destructor that disposes object if caller forgot to do so /// </summary> ~CkSsl3KeyMatOut() { Dispose(false); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Postcard.Areas.HelpPage.ModelDescriptions; using Postcard.Areas.HelpPage.Models; namespace Postcard.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Microsoft.DotNet.CodeFormatting.Tests { public abstract class ExplicitVisibilityRuleTests : LocalSemanticRuleTestBase { internal override ILocalSemanticFormattingRule Rule { get { return new Rules.ExplicitVisibilityRule(); } } public sealed class CSharpTests : ExplicitVisibilityRuleTests { [Fact] public void TestTypeVisibility() { var text = @" class C1 { } sealed partial class C2 { } struct S1 { } interface I1 { } enum E1 { } delegate void D1() { } "; var expected = @" internal class C1 { } internal sealed partial class C2 { } internal struct S1 { } internal interface I1 { } internal enum E1 { } internal delegate void D1() { } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestNestedTypeVisibility() { var text = @" class C { class C { } struct S { } interface I { } enum E { } delegate void D() { } } "; var expected = @" internal class C { private class C { } private struct S { } private interface I { } private enum E { } private delegate void D() { } } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestMethodVisibility() { var text = @" internal class C { void M1(); internal void M2(); } internal struct S { void M1(); internal void M2(); } internal interface I { void M1(); void M2(); } "; var expected = @" internal class C { private void M1(); internal void M2(); } internal struct S { private void M1(); internal void M2(); } internal interface I { void M1(); void M2(); } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestExplicitInterfaceImplementation() { var text = @" interface I1 { int this[int index] { get; set; } int Prop { get; set; } void M(); event EventHandler E; } class C : I1 { int I1.Prop { get { return 0; } set { } } int I1.this[int index] { get { return 0; } set { } } void I1.M() { } event EventHandler I1.E; void M() { } } "; var expected = @" internal interface I1 { int this[int index] { get; set; } int Prop { get; set; } void M(); event EventHandler E; } internal class C : I1 { int I1.Prop { get { return 0; } set { } } int I1.this[int index] { get { return 0; } set { } } void I1.M() { } event EventHandler I1.E; private void M() { } } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestFieldImplementation() { var text = @" class C { const int Max; int Field1; public int Field2; event EventHandler E1; public event EventHandler E2; } struct C { const int Max; int Field1; public int Field2; event EventHandler E1; public event EventHandler E2; } "; var expected = @" internal class C { private const int Max; private int Field1; public int Field2; private event EventHandler E1; public event EventHandler E2; } internal struct C { private const int Max; private int Field1; public int Field2; private event EventHandler E1; public event EventHandler E2; } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestConstructor() { var text = @" class C { static C() { } C() { } internal C(int p) { } } struct S { static S() { } S(int p) { } internal S(int p1, int p2) { } } "; var expected = @" internal class C { static C() { } private C() { } internal C(int p) { } } internal struct S { static S() { } private S(int p) { } internal S(int p1, int p2) { } } "; Verify(text, expected, runFormatter: false); } [Fact] public void TestPrivateFields() { var text = @" using System; class T { static int x; private static int y; // some trivia protected internal int z; // some trivia int k = 1, s = 2; // some trivia }"; var expected = @" using System; internal class T { private static int x; private static int y; // some trivia protected internal int z; // some trivia private int k = 1, s = 2; // some trivia }"; Verify(text, expected); } [Fact] public void LonePartialType() { var text = @" partial class C { } "; var expected = @" internal partial class C { } "; Verify(text, expected, runFormatter: false); } [Fact] public void CorrectPartialType() { var text = @" partial class C { } public partial class C { } "; var expected = @" public partial class C { } public partial class C { } "; Verify(text, expected, runFormatter: false); } [Fact] public void PartialAcrossFiles() { var text1 = @" public partial class C { } "; var text2 = @" partial class C { } "; var expected1 = @" public partial class C { } "; var expected2 = @" public partial class C { } "; Verify(new[] { text1, text2 }, new[] { expected1, expected2 }, runFormatter: false, languageName: LanguageNames.CSharp); } [Fact] public void PartialTypesWithNestedClasses() { var text = @" partial class C { class N1 { } class N2 { } } public partial class C { } "; var expected = @" public partial class C { private class N1 { } private class N2 { } } public partial class C { } "; Verify(text, expected, runFormatter: false); } [Fact] public void IgnorePartialMethods() { var text = @" class C { void M1(); partial void M2(); } "; var expected = @" internal class C { private void M1(); partial void M2(); } "; Verify(text, expected, runFormatter: false); } [Fact] public void CommentAttributeAndType() { var text = @" // Hello [Attr] // World class C1 { } // Hello [Attr] // World partial class C2 { }"; var expected = @" // Hello [Attr] // World internal class C1 { } // Hello [Attr] // World internal partial class C2 { }"; Verify(text, expected); } [Fact] public void CommentAttributeAndMethod() { var text = @" class C { // Hello [Attr] // World void M1() { } // Hello [Attr] // World static void M2() { } };"; var expected = @" internal class C { // Hello [Attr] // World private void M1() { } // Hello [Attr] // World private static void M2() { } };"; Verify(text, expected); } [Fact] public void CommentAttributeAndMethod2() { var text = @" class C { // Hello [Attr] // World void M1() { } // Hello [Attr] // World override void M2() { } };"; var expected = @" internal class C { // Hello [Attr] // World private void M1() { } // Hello [Attr] // World private override void M2() { } };"; Verify(text, expected); } [Fact] public void CommentAttributeAndProperty() { var text = @" class C { // Hello [Attr] // World int P1 { get { return 0; } } // Hello [Attr] // World static int P2 { get { return 0; } } };"; var expected = @" internal class C { // Hello [Attr] // World private int P1 { get { return 0; } } // Hello [Attr] // World private static int P2 { get { return 0; } } };"; Verify(text, expected); } [Fact] public void CommentAttributeAndConstructor() { var text = @" class C { // Hello [Attr] // World C(int p1) { } // Hello [Attr] // World unsafe C(int p1, int p2) { } };"; var expected = @" internal class C { // Hello [Attr] // World private C(int p1) { } // Hello [Attr] // World private unsafe C(int p1, int p2) { } };"; Verify(text, expected); } [Fact] public void CommentAttributeAndMultipleField() { var text = @" class C { // Hello [Attr] // World int x, y; };"; var expected = @" internal class C { // Hello [Attr] // World private int x, y; };"; Verify(text, expected); } [Fact] public void Issue70() { var source = @" public class MyClass { enum MyEnum { } struct MyStruct { public MyStruct(MyEnum e) { } } }"; var expected = @" public class MyClass { private enum MyEnum { } private struct MyStruct { public MyStruct(MyEnum e) { } } }"; Verify(source, expected); } } public sealed class VisualBasicTests : ExplicitVisibilityRuleTests { [Fact] public void TypeSimple() { var text = @" Class C End Class Structure S End Structure Module M End Module Enum E Value End Enum"; var expected = @" Friend Class C End Class Friend Structure S End Structure Friend Module M End Module Friend Enum E Value End Enum"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void TypeWithCommentAndAttribute() { var text = @" ' Hello <Attr> Class C End Class"; var expected = @" ' Hello <Attr> Friend Class C End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void TypePartialWithCommentAndAttribute() { var text = @" ' Hello <Attr> Partial Class C End Class"; var expected = @" ' Hello <Attr> Friend Partial Class C End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } /// <summary> /// It is interesting to note that nested typs in VB.Net default to public accessibility /// instead of private as C# does. /// </summary> [Fact] public void NestedType() { var text = @" Class Outer Class C End Class Structure S End Structure Enum E Value End Enum End Class"; var expected = @" Friend Class Outer Public Class C End Class Public Structure S End Structure Public Enum E Value End Enum End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void Methods() { var text = @" Class C Sub M1() End Sub Function M2() End Function Private Sub M3() End Sub End Class"; var expected = @" Friend Class C Public Sub M1() End Sub Public Function M2() End Function Private Sub M3() End Sub End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void MethodWithCommentAndAttribute() { var text = @" Class C ' A Comment <Attr> Sub M1() End Sub End Class"; var expected = @" Friend Class C ' A Comment <Attr> Public Sub M1() End Sub End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void Fields() { var text = @" Class C Dim Field1 As Integer Public Field2 As Integer End Class"; var expected = @" Friend Class C Private Field1 As Integer Public Field2 As Integer End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void Constructors() { var text = @" Class C Sub New() End Sub Shared Sub New() End Sub End Class"; var expected = @" Friend Class C Public Sub New() End Sub Shared Sub New() End Sub End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void ConstructorsWithCommentAndAttribute() { var text = @" Class C ' Hello <Attr> Sub New() End Sub ' Hello <Attr> Shared Sub New() End Sub End Class"; var expected = @" Friend Class C ' Hello <Attr> Public Sub New() End Sub ' Hello <Attr> Shared Sub New() End Sub End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } /// <summary> /// Members of a Module are implicitly Shared hence New here is a static ctor and cannot have /// any visibility modifiers. /// </summary> [Fact] public void ConstructorOnModules() { var text = @" Module M Sub New() End Sub End Module"; var expected = @" Friend Module M Sub New() End Sub End Module"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void InterfaceMembers() { var text = @" Interface I1 Property P1 As Integer Sub S1() Function F1() End Interface"; var expected = @" Friend Interface I1 Property P1 As Integer Sub S1() Function F1() End Interface"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } [Fact] public void Delegates() { var text = @" Delegate Function Func1() As Boolean Friend Class Foo Delegate Function Func2() As Boolean End Class "; var expected = @" Friend Delegate Function Func1() As Boolean Friend Class Foo Public Delegate Function Func2() As Boolean End Class "; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } /// <summary> /// VB.Net can have visibility modifiers + explicit interface implementation unlike C#. The /// visibility rules for these members is the same as normal members. /// </summary> [Fact] public void InterfaceImplementation() { var text = @" Interface I1 Property P1 As Integer Sub S1() Function F1() End Interface Class C1 Implements I1 Function F1() As Object Implements I1.F1 Return Nothing End Function Property P1 As Integer Implements I1.P1 Sub S1() Implements I1.S1 End Sub End Class"; var expected = @" Friend Interface I1 Property P1 As Integer Sub S1() Function F1() End Interface Friend Class C1 Implements I1 Public Function F1() As Object Implements I1.F1 Return Nothing End Function Public Property P1 As Integer Implements I1.P1 Public Sub S1() Implements I1.S1 End Sub End Class"; Verify(text, expected, runFormatter: false, languageName: LanguageNames.VisualBasic); } } } }
using System; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using GoogleApi.Entities.Common; using GoogleApi.Entities.Common.Enums; using GoogleApi.Entities.Places.Common.Enums; using GoogleApi.Entities.Places.Search.Common.Enums; using GoogleApi.Entities.Places.Search.Text.Request; using NUnit.Framework; namespace GoogleApi.UnitTests.Places.Search.Text { [TestFixture] public class TextSearchRequestTests { [Test] public void ConstructorDefaultTest() { var request = new PlacesTextSearchRequest(); Assert.IsNull(request.Type); Assert.IsNull(request.Radius); Assert.IsNull(request.Location); Assert.IsNull(request.Minprice); Assert.IsNull(request.Maxprice); Assert.IsFalse(request.OpenNow); Assert.AreEqual(Language.English, request.Language); } [Test] public void GetQueryStringParametersTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query" }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var key = queryStringParameters.FirstOrDefault(x => x.Key == "key"); var keyExpected = request.Key; Assert.IsNotNull(key); Assert.AreEqual(keyExpected, key.Value); var query = queryStringParameters.FirstOrDefault(x => x.Key == "query"); var queryExpected = request.Query; Assert.IsNotNull(query); Assert.AreEqual(queryExpected, query.Value); var language = queryStringParameters.FirstOrDefault(x => x.Key == "language"); Assert.IsNotNull(language); Assert.AreEqual("en", language.Value); } [Test] public void GetQueryStringParametersWhenRegionTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Region = "region" }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var region = queryStringParameters.FirstOrDefault(x => x.Key == "region"); var regionExpected = request.Region; Assert.IsNotNull(region); Assert.AreEqual(regionExpected, region.Value); } [Test] public void GetQueryStringParametersWhenRadiusTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Radius = 100 }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var radius = queryStringParameters.FirstOrDefault(x => x.Key == "radius"); var radiusExpected = request.Radius?.ToString(); Assert.IsNotNull(radius); Assert.AreEqual(radiusExpected, radius.Value); } [Test] public void GetQueryStringParametersWhenRadiusAndLocationTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Radius = 100, Location = new Coordinate(1, 1) }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var radius = queryStringParameters.FirstOrDefault(x => x.Key == "radius"); var radiusExpected = request.Radius?.ToString(); Assert.IsNotNull(radius); Assert.AreEqual(radiusExpected, radius.Value); var location = queryStringParameters.FirstOrDefault(x => x.Key == "location"); var locationExpected = request.Location.ToString(); Assert.IsNotNull(location); Assert.AreEqual(locationExpected, location.Value); } [Test] public void GetQueryStringParametersWhenTypeTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Type = SearchPlaceType.Accounting }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var type = queryStringParameters.FirstOrDefault(x => x.Key == "type"); var typeAttribute = request.Type?.GetType().GetMembers().FirstOrDefault(x => x.Name == request.Type.ToString())?.GetCustomAttribute<EnumMemberAttribute>(); var typeExpected = typeAttribute?.Value.ToLower(); Assert.IsNotNull(type); Assert.AreEqual(typeExpected, type.Value); } [Test] public void GetQueryStringParametersWhenOpenNowTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", OpenNow = true }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var radius = queryStringParameters.FirstOrDefault(x => x.Key == "opennow"); Assert.IsNotNull(radius); } [Test] public void GetQueryStringParametersWhenMinpriceTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Minprice = PriceLevel.Expensive }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var minprice = queryStringParameters.FirstOrDefault(x => x.Key == "minprice"); var minpriceExpected = ((int)request.Minprice.GetValueOrDefault()).ToString(); Assert.IsNotNull(minprice); Assert.AreEqual(minpriceExpected, minprice.Value); } [Test] public void GetQueryStringParametersWhenMaxpriceTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "query", Maxprice = PriceLevel.Free }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var maxprice = queryStringParameters.FirstOrDefault(x => x.Key == "maxprice"); var maxpriceExpected = ((int)request.Maxprice.GetValueOrDefault()).ToString(); Assert.IsNotNull(maxprice); Assert.AreEqual(maxpriceExpected, maxprice.Value); } [Test] public void GetQueryStringParametersWhenPageTokenTest() { var request = new PlacesTextSearchRequest { Key = "key", PageToken = "pagetoken" }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var pagetoken = queryStringParameters.FirstOrDefault(x => x.Key == "pagetoken"); var pagetokenExpected = request.PageToken; Assert.IsNotNull(pagetoken); Assert.AreEqual(pagetokenExpected, pagetoken.Value); } [Test] public void GetQueryStringParametersWhenKeyIsNullTest() { var request = new PlacesTextSearchRequest { Key = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Key' is required"); } [Test] public void GetQueryStringParametersWhenKeyIsStringEmptyTest() { var request = new PlacesTextSearchRequest { Key = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Key' is required"); } [Test] public void GetQueryStringParametersWhenQueryIsNullTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Query' is required"); } [Test] public void GetQueryStringParametersWhenQueryIsStringEmptyTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Query' is required"); } [Test] public void GetQueryStringParametersWhenLocationAndRadiusIsNullTest() { var request = new PlacesTextSearchRequest { Key = "key", Query = "picadelly circus", Location = new Coordinate(0, 0) }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Radius' is required when 'Location' is specified"); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Internal; /// <summary> /// Provides asynchronous, buffered execution of target writes. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// <p> /// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing /// messages and processing them in a separate thread. You should wrap targets /// that spend a non-trivial amount of time in their Write() method with asynchronous /// target to speed up logging. /// </p> /// <p> /// Because asynchronous logging is quite a common scenario, NLog supports a /// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to /// the &lt;targets/&gt; element in the configuration file. /// </p> /// <code lang="XML"> /// <![CDATA[ /// <targets async="true"> /// ... your targets go here ... /// </targets> /// ]]></code> /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" /> /// </example> [Target("AsyncWrapper", IsWrapper = true)] public class AsyncTargetWrapper : WrapperTargetBase { private readonly object _writeLockObject = new object(); private readonly object _timerLockObject = new object(); private Timer _lazyWriterTimer; private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private event EventHandler<LogEventDroppedEventArgs> _logEventDroppedEvent; private event EventHandler<LogEventQueueGrowEventArgs> _eventQueueGrowEvent; private bool _missingServiceTypes; /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> public AsyncTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="queueLimit">Maximum number of requests in the queue.</param> /// <param name="overflowAction">The action to be taken when the queue overflows.</param> public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { #if NETSTANDARD2_0 // NetStandard20 includes many optimizations for ConcurrentQueue: // - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/ // Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue // - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/ _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #else _requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #endif WrappedTarget = wrappedTarget; QueueLimit = queueLimit; OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events that should be processed in a batch /// by the lazy writer thread. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int BatchSize { get; set; } = 200; /// <summary> /// Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity) /// </summary> /// <docgen category='Buffering Options' order='100' /> public int TimeToSleepBetweenBatches { get; set; } = 1; /// <summary> /// Raise event when Target cannot store LogEvent. /// Event arg contains lost LogEvents /// </summary> public event EventHandler<LogEventDroppedEventArgs> LogEventDropped { add { if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventDropped += OnRequestQueueDropItem; } _logEventDroppedEvent += value; } remove { _logEventDroppedEvent -= value; if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventDropped -= OnRequestQueueDropItem; } } } /// <summary> /// Raises when event queue grow. /// Queue can grow when <see cref="OverflowAction"/> was set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/> /// </summary> public event EventHandler<LogEventQueueGrowEventArgs> EventQueueGrow { add { if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow += OnRequestQueueGrow; } _eventQueueGrowEvent += value; } remove { _eventQueueGrowEvent -= value; if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow -= OnRequestQueueGrow; } } } /// <summary> /// Gets or sets the action to be taken when the lazy writer thread request queue count /// exceeds the set limit. /// </summary> /// <docgen category='Buffering Options' order='10' /> public AsyncTargetWrapperOverflowAction OverflowAction { get => _requestQueue.OnOverflow; set => _requestQueue.OnOverflow = value; } /// <summary> /// Gets or sets the limit on the number of requests in the lazy writer thread request queue. /// </summary> /// <docgen category='Buffering Options' order='10' /> public int QueueLimit { get => _requestQueue.RequestLimit; set => _requestQueue.RequestLimit = value; } /// <summary> /// Gets or sets the limit of full <see cref="BatchSize"/>s to write before yielding into <see cref="TimeToSleepBetweenBatches"/> /// Performance is better when writing many small batches, than writing a single large batch /// </summary> /// <docgen category='Buffering Options' order='100' /> public int FullBatchSizeWriteLimit { get; set; } = 5; /// <summary> /// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue /// The locking queue is less concurrent when many logger threads, but reduces memory allocation /// </summary> /// <docgen category='Buffering Options' order='100' /> public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; } private bool? _forceLockingQueue; /// <summary> /// Gets the queue of lazy writer thread requests. /// </summary> AsyncRequestQueueBase _requestQueue; /// <summary> /// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (_flushEventsInQueueDelegate is null) _flushEventsInQueueDelegate = new AsyncHelpersTask(FlushEventsInQueue); AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation); } private AsyncHelpersTask? _flushEventsInQueueDelegate; /// <summary> /// Initializes the target by starting the lazy writer timer. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit) { ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit } #if !NET35 if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue)) { _requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction); } #endif if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1) { BatchSize = QueueLimit; // Avoid too much throttling } LayoutWithLock = LayoutWithLock || (WrappedTarget?.LayoutWithLock ?? false); if (WrappedTarget != null && WrappedTarget.InitializeException is Config.NLogDependencyResolveException && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { _missingServiceTypes = true; InternalLogger.Debug("{0} WrappedTarget has unresolved missing dependencies.", this); } _requestQueue.Clear(); InternalLogger.Trace("{0}: Start Timer", this); _lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite); StartLazyWriterTimer(); } /// <summary> /// Shuts down the lazy writer timer. /// </summary> protected override void CloseTarget() { StopLazyWriterThread(); if (Monitor.TryEnter(_writeLockObject, 500)) { try { WriteEventsInQueue(int.MaxValue, "Closing Target"); } finally { Monitor.Exit(_writeLockObject); } } if (OverflowAction == AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Clear(); // Try to eject any threads, that are blocked in the RequestQueue } base.CloseTarget(); } /// <summary> /// Starts the lazy writer thread which periodically writes /// queued log messages. /// </summary> protected virtual void StartLazyWriterTimer() { if (TimeToSleepBetweenBatches <= 1) { StartTimerUnlessWriterActive(false); } else { lock (_timerLockObject) { _lazyWriterTimer?.Change(TimeToSleepBetweenBatches, Timeout.Infinite); } } } /// <summary> /// Attempts to start an instant timer-worker-thread which can write /// queued log messages. /// </summary> /// <returns>Returns true when scheduled a timer-worker-thread</returns> protected virtual bool StartInstantWriterTimer() { return StartTimerUnlessWriterActive(true); } private bool StartTimerUnlessWriterActive(bool instant) { bool lockTaken = false; try { lockTaken = Monitor.TryEnter(_writeLockObject); if (lockTaken) { lock (_timerLockObject) { if (_lazyWriterTimer != null) { // Lock taken means no other timer-worker-thread is trying to write, schedule timer now if (instant) { // Not optimal to schedule timer-worker-thread while holding lock, // as the newly scheduled timer-worker-thread will hammer into the writeLockObject InternalLogger.Trace("{0}: Timer scheduled instantly", this); _lazyWriterTimer.Change(0, Timeout.Infinite); } else { InternalLogger.Trace("{0}: Timer scheduled throttled", this); _lazyWriterTimer.Change(1, Timeout.Infinite); } return true; } } } InternalLogger.Trace("{0}: Timer not scheduled, since already active", this); } finally { // If not able to take lock, then it means timer-worker-thread is already active, // and timer-worker-thread will check RequestQueue after leaving writeLockObject if (lockTaken) Monitor.Exit(_writeLockObject); } return false; } /// <summary> /// Stops the lazy writer thread. /// </summary> protected virtual void StopLazyWriterThread() { lock (_timerLockObject) { var currentTimer = _lazyWriterTimer; if (currentTimer != null) { _lazyWriterTimer = null; currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)); } } } /// <summary> /// Adds the log event to asynchronous queue to be processed by /// the lazy writer thread. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// The <see cref="Target.PrecalculateVolatileLayouts"/> is called /// to ensure that the log event can be processed in another thread. /// </remarks> protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); bool queueWasEmpty = _requestQueue.Enqueue(logEvent); if (queueWasEmpty) { if (TimeToSleepBetweenBatches == 0) StartInstantWriterTimer(); else if (TimeToSleepBetweenBatches <= 1) StartLazyWriterTimer(); } } /// <summary> /// Write to queue without locking <see cref="Target.SyncRoot"/> /// </summary> /// <param name="logEvent"></param> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } logEvent.Continuation(exception); } } private void ProcessPendingEvents(object state) { if (_lazyWriterTimer is null) return; bool wroteFullBatchSize = false; try { lock (_writeLockObject) { int count = WriteEventsInQueue(BatchSize, "Timer"); if (count == BatchSize) wroteFullBatchSize = true; if (wroteFullBatchSize && TimeToSleepBetweenBatches <= 1) StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up) } } catch (Exception exception) { wroteFullBatchSize = false; // Something went wrong, lets throttle retry #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(exception, "{0}: Error in lazy writer timer procedure.", this); } finally { if (TimeToSleepBetweenBatches <= 1) { if (!wroteFullBatchSize) { if (!_requestQueue.IsEmpty) { // If queue was not empty, then more might have arrived while writing the first batch // Do not use instant timer, so we can process in larger batches (faster) StartLazyWriterTimer(); } else { InternalLogger.Trace("{0}: Timer not scheduled, since queue empty", this); } } } else { StartLazyWriterTimer(); } } } private void FlushEventsInQueue(object state) { try { var asyncContinuation = state as AsyncContinuation; lock (_writeLockObject) { WriteEventsInQueue(int.MaxValue, "Flush Async"); if (asyncContinuation != null) base.FlushAsync(asyncContinuation); } } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(exception, "{0}: Error in flush procedure.", this); } finally { if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty) { StartLazyWriterTimer(); } } } private int WriteEventsInQueue(int batchSize, string reason) { if (WrappedTarget is null) { InternalLogger.Error("{0}: WrappedTarget is NULL", this); return 0; } if (_missingServiceTypes) { if (WrappedTarget.InitializeException is Config.NLogDependencyResolveException) { return 0; } _missingServiceTypes = false; InternalLogger.Debug("{0}: WrappedTarget has resolved missing dependency", this); } int count = 0; for (int i = 0; i < FullBatchSizeWriteLimit; ++i) { if (batchSize == int.MaxValue) { var logEvents = _requestQueue.DequeueBatch(batchSize); if (logEvents.Length > 0) { if (reason != null) InternalLogger.Trace("{0}: Writing {1} events ({2})", this, logEvents.Length, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } count = logEvents.Length; } else { using (var targetList = _reusableAsyncLogEventList.Allocate()) { var logEvents = targetList.Result; _requestQueue.DequeueBatch(batchSize, logEvents); if (logEvents.Count > 0) { if (reason != null) InternalLogger.Trace("{0}: Writing {1} events ({2})", this, logEvents.Count, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } count = logEvents.Count; } } if (count < batchSize) break; } return count; } private void OnRequestQueueDropItem(object sender, LogEventDroppedEventArgs logEventDroppedEventArgs) { _logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs); } private void OnRequestQueueGrow(object sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs) { _eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs); } } }
// Author: Dwivedi, Ajay kumar // [email protected] // // 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; using System.Globalization; using Mono.System.Xml.Serialization; namespace Mono.System.Xml.Schema { /// <summary> /// Summary description for XmlSchemaParticle. /// </summary> public abstract class XmlSchemaParticle : XmlSchemaAnnotated { internal static XmlSchemaParticle Empty { get { if (empty == null) { empty = new EmptyParticle (); } return empty; } } decimal minOccurs, maxOccurs; string minstr, maxstr; static XmlSchemaParticle empty; decimal validatedMinOccurs = 1, validatedMaxOccurs = 1; internal int recursionDepth = -1; private decimal minEffectiveTotalRange = -1; internal bool parentIsGroupDefinition; protected XmlSchemaParticle() { minOccurs = decimal.One; maxOccurs = decimal.One; } #region Attributes [Mono.System.Xml.Serialization.XmlAttribute("minOccurs")] public string MinOccursString { get{ return minstr; } set { if (value == null) { minOccurs = decimal.One; minstr = value; return; } decimal val = decimal.Parse (value, CultureInfo.InvariantCulture); if(val >= 0 && (val == Decimal.Truncate(val))) { minOccurs = val; minstr = val.ToString (CultureInfo.InvariantCulture); } else { throw new XmlSchemaException ("MinOccursString must be a non-negative number",null); } } } [Mono.System.Xml.Serialization.XmlAttribute("maxOccurs")] public string MaxOccursString { get{ return maxstr; } set { if(value == "unbounded") { maxstr = value; maxOccurs = decimal.MaxValue; } else { decimal val = decimal.Parse (value, CultureInfo.InvariantCulture); if(val >= 0 && (val == Decimal.Truncate(val))) { maxOccurs = val; maxstr = val.ToString (CultureInfo.InvariantCulture); } else { throw new XmlSchemaException ("MaxOccurs must be a non-negative integer",null); } if (val == 0 && minstr == null) minOccurs = 0; } } } #endregion #region XmlIgnore [XmlIgnore] public decimal MinOccurs { get{ return minOccurs; } set { MinOccursString = value.ToString (CultureInfo.InvariantCulture); } } [XmlIgnore] public decimal MaxOccurs { get{ return maxOccurs; } set { if (value == decimal.MaxValue) MaxOccursString = "unbounded"; else MaxOccursString = value.ToString (CultureInfo.InvariantCulture); } } internal decimal ValidatedMinOccurs { get { return validatedMinOccurs; } } internal decimal ValidatedMaxOccurs { get { return validatedMaxOccurs; } // set { validatedMaxOccurs = value; } } #endregion internal XmlSchemaParticle OptimizedParticle; internal virtual XmlSchemaParticle GetOptimizedParticle (bool isTop) { return null; } internal XmlSchemaParticle GetShallowClone () { return (XmlSchemaParticle) MemberwiseClone (); } internal void CompileOccurence (ValidationEventHandler h, XmlSchema schema) { if (MinOccurs > MaxOccurs && !(MaxOccurs == 0 && MinOccursString == null)) error(h,"minOccurs must be less than or equal to maxOccurs"); else { if (MaxOccursString == "unbounded") this.validatedMaxOccurs = decimal.MaxValue; else this.validatedMaxOccurs = maxOccurs; if (this.validatedMaxOccurs == 0) this.validatedMinOccurs = 0; else this.validatedMinOccurs = minOccurs; } } internal override void CopyInfo (XmlSchemaParticle obj) { base.CopyInfo (obj); if (MaxOccursString == "unbounded") obj.maxOccurs = obj.validatedMaxOccurs = decimal.MaxValue; else obj.maxOccurs = obj.validatedMaxOccurs = this.ValidatedMaxOccurs; if (MaxOccurs == 0) obj.minOccurs = obj.validatedMinOccurs = 0; else obj.minOccurs = obj.validatedMinOccurs = this.ValidatedMinOccurs; if (MinOccursString != null) obj.MinOccursString = MinOccursString; if (MaxOccursString != null) obj.MaxOccursString = MaxOccursString; } internal virtual bool ValidateOccurenceRangeOK (XmlSchemaParticle other, ValidationEventHandler h, XmlSchema schema, bool raiseError) { if ((this.ValidatedMinOccurs < other.ValidatedMinOccurs) || (other.ValidatedMaxOccurs != decimal.MaxValue && this.ValidatedMaxOccurs > other.ValidatedMaxOccurs)) { if (raiseError) error (h, "Invalid derivation occurence range was found."); return false; } return true; } internal virtual decimal GetMinEffectiveTotalRange () { return ValidatedMinOccurs; } internal decimal GetMinEffectiveTotalRangeAllAndSequence () { if (minEffectiveTotalRange >= 0) return minEffectiveTotalRange; decimal product = 0; //this.ValidatedMinOccurs; XmlSchemaObjectCollection col = null; if (this is XmlSchemaAll) col = ((XmlSchemaAll) this).Items; else col = ((XmlSchemaSequence) this).Items; foreach (XmlSchemaParticle p in col) product += p.GetMinEffectiveTotalRange (); minEffectiveTotalRange = product; return product; } // 3.9.6 Particle Emptiable internal virtual bool ValidateIsEmptiable () { return this.validatedMinOccurs == 0 || this.GetMinEffectiveTotalRange () == 0; } internal virtual bool ValidateDerivationByRestriction (XmlSchemaParticle baseParticle, ValidationEventHandler h, XmlSchema schema, bool raiseError) { return false; } internal virtual void ValidateUniqueParticleAttribution ( XmlSchemaObjectTable qnames, ArrayList nsNames, ValidationEventHandler h, XmlSchema schema) { } internal virtual void ValidateUniqueTypeAttribution (XmlSchemaObjectTable labels, ValidationEventHandler h, XmlSchema schema) { } internal virtual void CheckRecursion (Stack stack, ValidationEventHandler h, XmlSchema schema) { } internal virtual bool ParticleEquals (XmlSchemaParticle other) { return false; } #region Internal Class internal class EmptyParticle : XmlSchemaParticle { internal EmptyParticle () { } internal override XmlSchemaParticle GetOptimizedParticle (bool isTop) { return this; } internal override bool ParticleEquals (XmlSchemaParticle other) { return other == this || other == XmlSchemaParticle.Empty; } internal override bool ValidateDerivationByRestriction (XmlSchemaParticle baseParticle, ValidationEventHandler h, XmlSchema schema, bool raiseError) { return true; } internal override void CheckRecursion (Stack stack, ValidationEventHandler h, XmlSchema schema) { // do nothing } internal override void ValidateUniqueParticleAttribution (XmlSchemaObjectTable qnames, ArrayList nsNames, ValidationEventHandler h, XmlSchema schema) { // do nothing } internal override void ValidateUniqueTypeAttribution (XmlSchemaObjectTable labels, ValidationEventHandler h, XmlSchema schema) { // do nothing } } #endregion } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using SharpDX.Direct3D11; using SharpDX.IO; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A Texture 1D front end to <see cref="SharpDX.Direct3D11.Texture1D"/>. /// </summary> public class Texture1D : Texture1DBase { internal Texture1D(Device device, Texture1DDescription description1D, params DataBox[] dataBox) : base(device, description1D, dataBox) { } internal Texture1D(Device device, Direct3D11.Texture1D texture) : base(device, texture) { } internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice) { throw new System.NotSupportedException(); } /// <summary> /// Makes a copy of this texture. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public override Texture Clone() { return new Texture1D(GraphicsDevice, this.Description); } /// <summary> /// Creates a new texture from a <see cref="Texture1DDescription"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="description">The description.</param> /// <returns> /// A new instance of <see cref="Texture1D"/> class. /// </returns> /// <msdn-id>ff476520</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> public static Texture1D New(Device device, Texture1DDescription description) { return new Texture1D(device, description); } /// <summary> /// Creates a new texture from a <see cref="Direct3D11.Texture1D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="texture">The native texture <see cref="Direct3D11.Texture1D"/>.</param> /// <returns> /// A new instance of <see cref="Texture1D"/> class. /// </returns> /// <msdn-id>ff476520</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> public static Texture1D New(Device device, Direct3D11.Texture1D texture) { return new Texture1D(device, texture); } /// <summary> /// Creates a new <see cref="Texture1D"/> with a single mipmap. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <returns> /// A new instance of <see cref="Texture1D"/> class. /// </returns> /// <msdn-id>ff476520</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> public static Texture1D New(Device device, int width, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default) { return New(device, width, false, format, flags, arraySize, usage); } /// <summary> /// Creates a new <see cref="Texture1D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <returns> /// A new instance of <see cref="Texture1D"/> class. /// </returns> /// <msdn-id>ff476520</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> public static Texture1D New(Device device, int width, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default) { return new Texture1D(device, NewDescription(width, format, flags, mipCount, arraySize, usage)); } /// <summary> /// Creates a new <see cref="Texture1D" /> with a single level of mipmap. /// </summary> /// <typeparam name="T">Type of the initial data to upload to the texture</typeparam> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="textureData">Texture data. Size of must be equal to sizeof(Format) * width </param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns>A new instance of <see cref="Texture1D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_Texture1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> /// <remarks> /// The first dimension of mipMapTextures describes the number of array (Texture1D Array), second dimension is the mipmap, the third is the texture data for a particular mipmap. /// </remarks> public unsafe static Texture1D New<T>(Device device, int width, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct { Texture1D texture = null; Utilities.Pin(textureData, ptr => { texture = new Texture1D(device, NewDescription(width, format, flags, 1, 1, usage), GetDataBox(format, width, 1, 1, textureData, ptr)); }); return texture; } /// <summary> /// Creates a new <see cref="Texture1D" /> directly from an <see cref="Image"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="image">An image in CPU memory.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture1D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short> public static Texture1D New(Device device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { if (image == null) throw new ArgumentNullException("image"); if (image.Description.Dimension != TextureDimension.Texture1D) throw new ArgumentException("Invalid image. Must be 1D", "image"); return new Texture1D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox()); } /// <summary> /// Loads a 1D texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="stream">The stream to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 1D</exception> /// <returns>A texture</returns> public static new Texture1D Load(Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { var texture = Texture.Load(device, stream, flags, usage); if (!(texture is Texture1D)) throw new ArgumentException(string.Format("Texture is not type of [Texture1D] but [{0}]", texture.GetType().Name)); return (Texture1D)texture; } /// <summary> /// Loads a 1D texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="filePath">The file to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 1D</exception> /// <returns>A texture</returns> public static new Texture1D Load(Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, flags, usage); } } }
namespace MobileApp.Core.Services.AccountService { #region using System; using System.Globalization; using Cirrious.MvvmCross.Plugins.Messenger; using MobileApp.Core.Interfaces; using MobileApp.Core.Models; using MobileApp.Core.Models.DataContracts; using MobileApp.Core.Models.Messages; using MobileApp.Core.Properties; using MobileApp.Core.Services.HttpService; using MobileApp.Core.Services.UtilityService.Logger; using Newtonsoft.Json; using Responce = MobileApp.Core.Services.HttpService.Responce; #endregion /// <summary> /// The auth service. /// </summary> public class UserDataService : IAccountService { #region Fields private readonly ILogger logger; private readonly IMvxMessenger messenger; private Action<Exception> error; private bool isAuthorized = true; private bool isValid; private Action<Responce> success; private bool isTransferAvailable; private readonly MvxSubscriptionToken contactToken; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserDataService" /> class. /// </summary> public UserDataService(ILogger logger, IMvxMessenger messenger) { this.logger = logger; this.messenger = messenger; this.contactToken = this.messenger.Subscribe<Message<Contact>>(this.OnContactReceived); } private void OnContactReceived(Message<Contact> message) { if (message == null) { return; } if (message.Data == null || !message.Data.Equals(this.UserData)) { return; } this.UserData.Registered = message.Data.Registered; this.messenger.Publish(new Message<ContactStatus>(this, this.UserData.Status)); } #endregion #region Public Properties /// <summary> /// Gets the credentials. /// </summary> public CredentialsModel? Credentials { get; private set; } /// <summary> /// Gets or sets a value indicating whether is authorized. /// </summary> public bool IsAuthorized { get { return this.isAuthorized; } set { this.isAuthorized = value; } } /// <summary> /// Gets or sets the user data. /// </summary> public Contact UserData { get; set; } /// <summary> /// Get or set transfer availability /// </summary> public bool IsTransferAvailable { get { return this.isTransferAvailable; } set { this.isTransferAvailable = value; this.messenger.Publish(new TransferMessage(this)); } } #endregion #region Public Methods and Operators /// <summary> /// The authorize. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="userId"> /// The user id. /// </param> /// <param name="userPin"> /// The user pin. /// </param> /// <param name="externalSuccess"> /// The success. /// </param> /// <param name="externalError"> /// The error. /// </param> public void Authorize(string instance, string userId, string userPin, Action<Responce> externalSuccess, Action<Exception> externalError = null) { this.error = externalError; this.success = externalSuccess; var valid = this.ValidateAuthData(instance, userId, userPin); if (this.isValid) { var cred = this.Credentials.Value; ApiInteraction.Create( ApiMethodType.GetAuth, this.OnSuccess, this.OnError, new { INSTANCE = cred.Instance, PIN = cred.Pin, USERID = cred.UserId, VERSION = Resources.BuildVersion }); } else { externalSuccess(new Responce { Result = false, Data = valid }); } } /// <summary> /// The clear. /// </summary> public void Clear() { this.Credentials = null; this.UserData = null; } #endregion #region Methods private void OnError(Exception webError) { var action = this.error; if (action != null) { action(webError); } } private void OnSuccess(object data) { var result = data as Responce ?? JsonConvert.DeserializeObject<Responce>(data.ToString()); if (!result.Result) { var cred = this.Credentials.Value; this.logger.Debug( string.Format( "{0} - Loggin failed {1}@{2} - {4} : {3}", this.GetType().Name, cred.UserId, cred.Instance, result.Message, result.ErrorCode), this); this.success(new Responce { Result = false, Message = result.Message}); } else { this.IsAuthorized = true; this.logger.Debug(string.Format("{0} - Logged : {1}@{2}", this.GetType().Name, this.Credentials.Value.UserId, this.Credentials.Value.Instance), this); var contact = result.Data.ToString(); this.UserData = JsonConvert.DeserializeObject<Contact>(contact, new JsonSerializerSettings()); ApiInteraction.Authentication = this.Credentials.Value; this.success(Responce.Ok); } } /// <summary> /// The validate auth data. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="userId"> /// The user id. /// </param> /// <param name="userPin"> /// The user pin. /// </param> /// <returns> /// The <see cref="ValidationReport" />. /// </returns> private ValidationReport ValidateAuthData(string instance, string userId, string userPin) { var validation = new bool[3]; if (!string.IsNullOrEmpty(instance) && !string.IsNullOrWhiteSpace(instance)) { validation[0] = true; } int id; if (!string.IsNullOrEmpty(userId) && !string.IsNullOrWhiteSpace(userId)) { validation[1] = true; } if (int.TryParse(userId, NumberStyles.Integer, CultureInfo.CurrentCulture, out id)) { validation[1] = true; } if (!string.IsNullOrEmpty(userPin) && !string.IsNullOrWhiteSpace(userPin)) { validation[2] = true; } this.isValid = validation[0] && validation[1] && validation[2]; if (this.isValid) { this.Credentials = new CredentialsModel { Instance = instance, UserId = userId, Pin = userPin }; } return new ValidationReport(validation); } #endregion } }
// created on 12/7/2003 at 18:36 // Npgsql.NpgsqlError.cs // // Author: // Francisco Jr. ([email protected]) // // Copyright (C) 2002 The Npgsql Development Team // [email protected] // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.IO; using System.Text; namespace Npgsql { /// <summary> /// EventArgs class to send Notice parameters, which are just NpgsqlError's in a lighter context. /// </summary> public class NpgsqlNoticeEventArgs : EventArgs { /// <summary> /// Notice information. /// </summary> public NpgsqlError Notice = null; internal NpgsqlNoticeEventArgs(NpgsqlError eNotice) { Notice = eNotice; } } /// <summary> /// This class represents the ErrorResponse and NoticeResponse /// message sent from PostgreSQL server. /// </summary> public sealed class NpgsqlError { // Logging related values private static readonly String CLASSNAME = "NpgsqlError"; private ProtocolVersion protocol_version; private String _severity = ""; private String _code = ""; private String _message = ""; private String _detail = ""; private String _hint = ""; private String _position = ""; private String _where = ""; private String _file = ""; private String _line = ""; private String _routine = ""; /// <summary> /// Severity code. All versions. /// </summary> public String Severity { get { return _severity; } } /// <summary> /// Error code. PostgreSQL 7.4 and up. /// </summary> public String Code { get { return _code; } } /// <summary> /// Terse error message. All versions. /// </summary> public String Message { get { return _message; } } /// <summary> /// Detailed error message. PostgreSQL 7.4 and up. /// </summary> public String Detail { get { return _detail; } } /// <summary> /// Suggestion to help resolve the error. PostgreSQL 7.4 and up. /// </summary> public String Hint { get { return _hint; } } /// <summary> /// Position (one based) within the query string where the error was encounterd. PostgreSQL 7.4 and up. /// </summary> public String Position { get { return _position; } } /// <summary> /// Trace back information. PostgreSQL 7.4 and up. /// </summary> public String Where { get { return _where; } } /// <summary> /// Source file (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public String File { get { return _file; } } /// <summary> /// Source file line number (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public String Line { get { return _line; } } /// <summary> /// Source routine (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public String Routine { get { return _routine; } } /// <summary> /// Return a string representation of this error object. /// </summary> public override String ToString() { StringBuilder B = new StringBuilder(); if (Severity.Length > 0) { B.AppendFormat("{0}: ", Severity); } if (Code.Length > 0) { B.AppendFormat("{0}: ", Code); } B.AppendFormat("{0}", Message); // CHECKME - possibly multi-line, that is yucky // if (Hint.Length > 0) { // B.AppendFormat(" ({0})", Hint); // } return B.ToString(); } internal NpgsqlError(ProtocolVersion protocolVersion) { protocol_version = protocolVersion; } internal NpgsqlError(ProtocolVersion protocolVersion, String errorMessage) { protocol_version = protocolVersion; _message = errorMessage; } /// <summary> /// Backend protocol version in use. /// </summary> internal ProtocolVersion BackendProtocolVersion { get { return protocol_version; } } internal void ReadFromStream(Stream inputStream, Encoding encoding) { switch (protocol_version) { case ProtocolVersion.Version2 : ReadFromStream_Ver_2(inputStream, encoding); break; case ProtocolVersion.Version3 : ReadFromStream_Ver_3(inputStream, encoding); break; } } private void ReadFromStream_Ver_2(Stream inputStream, Encoding encoding) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ReadFromStream_Ver_2"); String Raw; String[] Parts; Raw = PGUtil.ReadString(inputStream, encoding); Parts = Raw.Split(new char[] {':'}, 2); if (Parts.Length == 2) { _severity = Parts[0].Trim(); _message = Parts[1].Trim(); } else { _message = Parts[0].Trim(); } } private void ReadFromStream_Ver_3(Stream inputStream, Encoding encoding) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ReadFromStream_Ver_3"); Int32 messageLength = PGUtil.ReadInt32(inputStream, new Byte[4]); // [TODO] Would this be the right way to do? // Check the messageLength value. If it is 1178686529, this would be the // "FATA" string, which would mean a protocol 2.0 error string. if (messageLength == 1178686529) { String Raw; String[] Parts; Raw = "FATA" + PGUtil.ReadString(inputStream, encoding); Parts = Raw.Split(new char[] {':'}, 2); if (Parts.Length == 2) { _severity = Parts[0].Trim(); _message = Parts[1].Trim(); } else { _message = Parts[0].Trim(); } protocol_version = ProtocolVersion.Version2; return; } Char field; String fieldValue; field = (Char) inputStream.ReadByte(); // Now start to read fields. while (field != 0) { fieldValue = PGUtil.ReadString(inputStream, encoding); switch (field) { case 'S': _severity = fieldValue; break; case 'C': _code = fieldValue; break; case 'M': _message = fieldValue; break; case 'D': _detail = fieldValue; break; case 'H': _hint = fieldValue; break; case 'P': _position = fieldValue; break; case 'W': _where = fieldValue; break; case 'F': _file = fieldValue; break; case 'L': _line = fieldValue; break; case 'R': _routine = fieldValue; break; } field = (Char) inputStream.ReadByte(); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.Diagnostics; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using System.Workflow.Runtime.Configuration; using System.Workflow.Runtime.Hosting; using System.Runtime.Serialization; using System.Globalization; using System.Threading; using System.Runtime.Serialization.Formatters.Binary; using System.Configuration; namespace System.Workflow.Activities { internal interface IDeliverMessage { object[] PrepareEventArgsArray(object sender, ExternalDataEventArgs eventArgs, out object workItem, out IPendingWork workHandler); void DeliverMessage(ExternalDataEventArgs eventArgs, IComparable queueName, object message, object workItem, IPendingWork workHandler); } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ExternalDataExchangeServiceSection : ConfigurationSection { private const string _services = "Services"; /// <summary> The providers to be instantiated by the service container. </summary> [ConfigurationProperty(_services, DefaultValue = null)] public WorkflowRuntimeServiceElementCollection Services { get { return (WorkflowRuntimeServiceElementCollection)base[_services]; } } } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ExternalDataExchangeService : WorkflowRuntimeService { Dictionary<int, WorkflowMessageEventHandler> eventHandlers = null; object handlersLock = new object(); private const string configurationSectionAttributeName = "ConfigurationSection"; ExternalDataExchangeServiceSection settings = null; IDeliverMessage enqueueMessageWrapper = null; List<object> services; object servicesLock = new object(); public ExternalDataExchangeService() { this.eventHandlers = new Dictionary<int, WorkflowMessageEventHandler>(); this.services = new List<object>(); this.enqueueMessageWrapper = new EnqueueMessageWrapper(this); } public ExternalDataExchangeService(string configSectionName) : this() { if (configSectionName == null) throw new ArgumentNullException("configSectionName"); settings = ConfigurationManager.GetSection(configSectionName) as ExternalDataExchangeServiceSection; if (settings == null) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_ConfigurationSectionNotFound), configSectionName)); } public ExternalDataExchangeService(NameValueCollection parameters) : this() { if (parameters == null) throw new ArgumentNullException("parameters"); string configurationSectionName = null; foreach (string key in parameters.Keys) { if (key.Equals(configurationSectionAttributeName, StringComparison.OrdinalIgnoreCase)) { configurationSectionName = parameters[key]; } else { throw new ArgumentException( String.Format(Thread.CurrentThread.CurrentCulture, SR.GetString(SR.Error_UnknownConfigurationParameter), key), "parameters"); } } if (configurationSectionName != null) { settings = ConfigurationManager.GetSection(configurationSectionName) as ExternalDataExchangeServiceSection; if (settings == null) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_ConfigurationSectionNotFound), configurationSectionName)); } } public ExternalDataExchangeService(ExternalDataExchangeServiceSection settings) : this() { if (settings == null) throw new ArgumentNullException("settings"); this.settings = settings; } internal ReadOnlyCollection<object> GetAllServices() { ReadOnlyCollection<object> collection; lock (this.servicesLock) { collection = this.services.AsReadOnly(); } return collection; } protected override void Start() { if (settings != null) { foreach (WorkflowRuntimeServiceElement service in settings.Services) { AddService(ServiceFromSettings(service)); } } if (this.Runtime != null) { base.Start(); } } internal void SetEnqueueMessageWrapper(IDeliverMessage wrapper) { this.enqueueMessageWrapper = wrapper; foreach (WorkflowMessageEventHandler eventHandler in this.eventHandlers.Values) { eventHandler.EnqueueWrapper = wrapper; } } // Todo: This is duplicate of code in WorkflowRuntime internal object ServiceFromSettings(WorkflowRuntimeServiceElement serviceSettings) { object service = null; Type t = Type.GetType(serviceSettings.Type, true); ConstructorInfo serviceProviderAndSettingsConstructor = null; ConstructorInfo serviceProviderConstructor = null; ConstructorInfo settingsConstructor = null; foreach (ConstructorInfo ci in t.GetConstructors()) { ParameterInfo[] pi = ci.GetParameters(); if (pi.Length == 1) { if (typeof(IServiceProvider).IsAssignableFrom(pi[0].ParameterType)) { serviceProviderConstructor = ci; } else if (typeof(NameValueCollection).IsAssignableFrom(pi[0].ParameterType)) { settingsConstructor = ci; } } else if (pi.Length == 2) { if (typeof(IServiceProvider).IsAssignableFrom(pi[0].ParameterType) && typeof(NameValueCollection).IsAssignableFrom(pi[1].ParameterType)) { serviceProviderAndSettingsConstructor = ci; break; } } } if (serviceProviderAndSettingsConstructor != null) { service = serviceProviderAndSettingsConstructor.Invoke( new object[] { Runtime, serviceSettings.Parameters }); } else if (serviceProviderConstructor != null) { service = serviceProviderConstructor.Invoke(new object[] { Runtime }); } else if (settingsConstructor != null) { service = settingsConstructor.Invoke(new object[] { serviceSettings.Parameters }); } else { service = Activator.CreateInstance(t); } return service; } public virtual void AddService(object service) { if (service == null) throw new ArgumentNullException("service"); InterceptService(service, true); if (this.Runtime != null) { this.Runtime.AddService(service); } else { lock (this.servicesLock) { this.services.Add(service); } } } public virtual void RemoveService(object service) { if (service == null) throw new ArgumentNullException("service"); InterceptService(service, false); if (this.Runtime != null) { this.Runtime.RemoveService(service); } else { lock (this.servicesLock) { this.services.Remove(service); } } } public virtual object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); if (this.Runtime != null) { return this.Runtime.GetService(serviceType); } else { lock (this.servicesLock) { foreach (object service in this.services) { if (serviceType.IsAssignableFrom(service.GetType())) { return service; } } return null; } } } internal void InterceptService(object service, bool add) { bool isDataExchangeService = false; Type[] interfaceTypes = service.GetType().GetInterfaces(); foreach (Type type in interfaceTypes) { object[] attributes = type.GetCustomAttributes(typeof(ExternalDataExchangeAttribute), false); if (attributes.Length == 0) continue; if (this.Runtime != null && this.Runtime.GetService(type) != null && add) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_ExternalDataExchangeServiceExists), type)); isDataExchangeService = true; EventInfo[] events = type.GetEvents(); if (events == null) continue; foreach (EventInfo e in events) { WorkflowMessageEventHandler handler = null; int hash = type.GetHashCode() ^ e.Name.GetHashCode(); lock (handlersLock) { if (!this.eventHandlers.ContainsKey(hash)) { handler = new WorkflowMessageEventHandler(type, e, this.enqueueMessageWrapper); this.eventHandlers.Add(hash, handler); } else { handler = this.eventHandlers[hash]; } } AddRemove(service, handler.Delegate, add, e.Name); } } if (!isDataExchangeService) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_ServiceMissingExternalDataExchangeInterface))); } private void AddRemove(object addedservice, Delegate delg, bool add, string eventName) { try { string eventAction; if (add) eventAction = "add_" + eventName; else eventAction = "remove_" + eventName; Type serviceType = addedservice.GetType(); if (delg != null) { // add or remove interception handler object[] del = { delg }; serviceType.InvokeMember(eventAction, BindingFlags.InvokeMethod, null, addedservice, del, null); } } catch (Exception e) { if (IsIrrecoverableException(e)) { throw; } // cannot intercept this event } } internal static bool IsIrrecoverableException(Exception e) { return ((e is OutOfMemoryException) || (e is StackOverflowException) || (e is ThreadInterruptedException) || (e is ThreadAbortException)); } class EnqueueMessageWrapper : IDeliverMessage { ExternalDataExchangeService eds; public EnqueueMessageWrapper(ExternalDataExchangeService eds) { this.eds = eds; } public object[] PrepareEventArgsArray(object sender, ExternalDataEventArgs eventArgs, out object workItem, out IPendingWork workHandler) { // remove the batch items from the event args, only the runtime needs this data // and it is not necessarily serializable. workItem = eventArgs.WorkItem; eventArgs.WorkItem = null; workHandler = eventArgs.WorkHandler; eventArgs.WorkHandler = null; return new object[] { sender, eventArgs }; } public void DeliverMessage(ExternalDataEventArgs eventArgs, IComparable queueName, object message, object workItem, IPendingWork workHandler) { WorkflowInstance workflowInstance = this.eds.Runtime.GetWorkflow(eventArgs.InstanceId); if (eventArgs.WaitForIdle) { workflowInstance.EnqueueItemOnIdle(queueName, message, workHandler, workItem); } else { workflowInstance.EnqueueItem(queueName, message, workHandler, workItem); } } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using AutoMapper; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Recovery services convenience client. /// </summary> public partial class PSRecoveryServicesClient { /// <summary> /// Pair Cloud /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Input</param> /// <param name="mappingName">Mapping Name</param> /// <param name="input">Pairing input</param> /// <returns></returns> public PSSiteRecoveryLongRunningOperation ConfigureProtection( string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings.BeginCreateWithHttpMessagesAsync( fabricName, protectionContainerName, mappingName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Create protection container. /// </summary> /// <param name="fabricName">Fabric Name.</param> /// <param name="protectionContainerName">Protection Container name.</param> /// <param name="input">Creation input.</param> /// <returns>A long running operation response.</returns> public PSSiteRecoveryLongRunningOperation CreateProtectionContainer( string fabricName, string protectionContainerName, CreateProtectionContainerInput input) { var op = this.GetSiteRecoveryClient().ReplicationProtectionContainers.BeginCreateWithHttpMessagesAsync( fabricName, protectionContainerName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Gets Azure Site Recovery Protection Container. /// </summary> /// <returns>Protection Container list response</returns> public List<ProtectionContainer> GetAzureSiteRecoveryProtectionContainer() { var firstPage = this.GetSiteRecoveryClient() .ReplicationProtectionContainers .ListWithHttpMessagesAsync(this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; var pages = Utilities.GetAllFurtherPages( this.GetSiteRecoveryClient() .ReplicationProtectionContainers.ListNextWithHttpMessagesAsync, firstPage.NextPageLink, this.GetRequestHeaders(true)); pages.Insert( 0, firstPage); return Utilities.IpageToList(pages); } /// <summary> /// Gets Azure Site Recovery Protection Container. /// </summary> /// <returns>Protection Container list response</returns> public List<ProtectionContainer> GetAzureSiteRecoveryProtectionContainer( string fabricName) { var firstPage = this.GetSiteRecoveryClient() .ReplicationProtectionContainers.ListByReplicationFabricsWithHttpMessagesAsync( fabricName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; var pages = Utilities.GetAllFurtherPages( this.GetSiteRecoveryClient() .ReplicationProtectionContainers .ListByReplicationFabricsNextWithHttpMessagesAsync, firstPage.NextPageLink, this.GetRequestHeaders(true)); pages.Insert( 0, firstPage); return Utilities.IpageToList(pages); } /// <summary> /// Gets Azure Site Recovery Protection Container. /// </summary> /// <param name="protectionContainerName">Protection Container ID</param> /// <returns>Protection Container response</returns> public ProtectionContainer GetAzureSiteRecoveryProtectionContainer( string fabricName, string protectionContainerName) { return this.GetSiteRecoveryClient() .ReplicationProtectionContainers.GetWithHttpMessagesAsync( fabricName, protectionContainerName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; } /// <summary> /// Gets Azure Site Recovery Protection Container Mapping. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <returns></returns> public List<ProtectionContainerMapping> GetAzureSiteRecoveryProtectionContainerMapping( string fabricName, string protectionContainerName) { var firstPage = this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings .ListByReplicationProtectionContainersWithHttpMessagesAsync( fabricName, protectionContainerName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; var pages = Utilities.GetAllFurtherPages( this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings .ListByReplicationProtectionContainersNextWithHttpMessagesAsync, firstPage.NextPageLink, this.GetRequestHeaders(true)); pages.Insert( 0, firstPage); return Utilities.IpageToList(pages); } /// <summary> /// Gets Azure Site Recovery Protection Container Mapping. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <param name="mappingName">Mapping Name</param> /// <returns></returns> public ProtectionContainerMapping GetAzureSiteRecoveryProtectionContainerMapping( string fabricName, string protectionContainerName, string mappingName) { return this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings.GetWithHttpMessagesAsync( fabricName, protectionContainerName, mappingName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; } /// <summary> /// Purge Cloud Mapping /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Input</param> /// <param name="mappingName">Mapping Name</param> /// <returns></returns> public PSSiteRecoveryLongRunningOperation PurgeCloudMapping( string fabricName, string protectionContainerName, string mappingName) { var op = this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings.BeginPurgeWithHttpMessagesAsync( fabricName, protectionContainerName, mappingName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Remove protection container. /// </summary> /// <param name="fabricName">Fabric Name.</param> /// <param name="protectionContainerName">Protection Container name.</param> /// <returns>A long running operation response.</returns> public PSSiteRecoveryLongRunningOperation RemoveProtectionContainer( string fabricName, string protectionContainerName) { var op = this.GetSiteRecoveryClient().ReplicationProtectionContainers.BeginDeleteWithHttpMessagesAsync( fabricName, protectionContainerName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// UnPair Cloud /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Input</param> /// <param name="mappingName">Mapping Name</param> /// <param name="input">UnPairing input</param> /// <returns></returns> public PSSiteRecoveryLongRunningOperation UnConfigureProtection( string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectionContainerMappings.BeginDeleteWithHttpMessagesAsync( fabricName, protectionContainerName, mappingName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AgeRangeView</c> resource.</summary> public sealed partial class AgeRangeViewName : gax::IResourceName, sys::IEquatable<AgeRangeViewName> { /// <summary>The possible contents of <see cref="AgeRangeViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/ageRangeViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="AgeRangeViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AgeRangeViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AgeRangeViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AgeRangeViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AgeRangeViewName"/> with the pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AgeRangeViewName"/> constructed from the provided ids.</returns> public static AgeRangeViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new AgeRangeViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AgeRangeViewName"/> with pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AgeRangeViewName"/> with pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AgeRangeViewName"/> with pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AgeRangeViewName"/> with pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary>Parses the given resource name string into a new <see cref="AgeRangeViewName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="ageRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AgeRangeViewName"/> if successful.</returns> public static AgeRangeViewName Parse(string ageRangeViewName) => Parse(ageRangeViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AgeRangeViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="ageRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AgeRangeViewName"/> if successful.</returns> public static AgeRangeViewName Parse(string ageRangeViewName, bool allowUnparsed) => TryParse(ageRangeViewName, allowUnparsed, out AgeRangeViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AgeRangeViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="ageRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AgeRangeViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string ageRangeViewName, out AgeRangeViewName result) => TryParse(ageRangeViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AgeRangeViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="ageRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AgeRangeViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string ageRangeViewName, bool allowUnparsed, out AgeRangeViewName result) { gax::GaxPreconditions.CheckNotNull(ageRangeViewName, nameof(ageRangeViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(ageRangeViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(ageRangeViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AgeRangeViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AgeRangeViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/ageRangeViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public AgeRangeViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AgeRangeViewName); /// <inheritdoc/> public bool Equals(AgeRangeViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AgeRangeViewName a, AgeRangeViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AgeRangeViewName a, AgeRangeViewName b) => !(a == b); } public partial class AgeRangeView { /// <summary> /// <see cref="AgeRangeViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AgeRangeViewName ResourceNameAsAgeRangeViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AgeRangeViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Documents; using Lucene.Net.Support; using Document = Lucene.Net.Documents.Document; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using StringHelper = Lucene.Net.Util.StringHelper; namespace Lucene.Net.Index { /// <summary>Access to the Fieldable Info file that describes document fields and whether or /// not they are indexed. Each segment has a separate Fieldable Info file. Objects /// of this class are thread-safe for multiple readers, but only one thread can /// be adding documents at a time, with no other reader or writer threads /// accessing this object. /// </summary> public sealed class FieldInfos : ICloneable { // Used internally (ie not written to *.fnm files) for pre-2.9 files public const int FORMAT_PRE = - 1; // First used in 2.9; prior to 2.9 there was no format header public const int FORMAT_START = - 2; internal static readonly int CURRENT_FORMAT = FORMAT_START; internal const byte IS_INDEXED = (0x1); internal const byte STORE_TERMVECTOR = (0x2); internal const byte STORE_POSITIONS_WITH_TERMVECTOR =(0x4); internal const byte STORE_OFFSET_WITH_TERMVECTOR = (0x8); internal const byte OMIT_NORMS = (0x10); internal const byte STORE_PAYLOADS = (0x20); internal const byte OMIT_TERM_FREQ_AND_POSITIONS = (0x40); private readonly System.Collections.Generic.List<FieldInfo> byNumber = new System.Collections.Generic.List<FieldInfo>(); private readonly HashMap<string, FieldInfo> byName = new HashMap<string, FieldInfo>(); private int format; public /*internal*/ FieldInfos() { } /// <summary> Construct a FieldInfos object using the directory and the name of the file /// IndexInput /// </summary> /// <param name="d">The directory to open the IndexInput from /// </param> /// <param name="name">The name of the file to open the IndexInput from in the Directory /// </param> /// <throws> IOException </throws> public /*internal*/ FieldInfos(Directory d, String name) { IndexInput input = d.OpenInput(name); try { try { Read(input, name); } catch (System.IO.IOException) { if (format == FORMAT_PRE) { // LUCENE-1623: FORMAT_PRE (before there was a // format) may be 2.3.2 (pre-utf8) or 2.4.x (utf8) // encoding; retry with input set to pre-utf8 input.Seek(0); input.SetModifiedUTF8StringsMode(); byNumber.Clear(); byName.Clear(); bool rethrow = false; try { Read(input, name); } catch (Exception) { // Ignore any new exception & set to throw original IOE rethrow = true; } if(rethrow) { // Preserve stack trace throw; } } else { // The IOException cannot be caused by // LUCENE-1623, so re-throw it throw; } } } finally { input.Close(); } } /// <summary> Returns a deep clone of this FieldInfos instance.</summary> public Object Clone() { lock (this) { var fis = new FieldInfos(); int numField = byNumber.Count; for (int i = 0; i < numField; i++) { var fi = (FieldInfo)byNumber[i].Clone(); fis.byNumber.Add(fi); fis.byName[fi.name] = fi; } return fis; } } /// <summary>Adds field info for a Document. </summary> public void Add(Document doc) { lock (this) { System.Collections.Generic.IList<IFieldable> fields = doc.GetFields(); foreach(IFieldable field in fields) { Add(field.Name, field.IsIndexed, field.IsTermVectorStored, field.IsStorePositionWithTermVector, field.IsStoreOffsetWithTermVector, field.OmitNorms, false, field.OmitTermFreqAndPositions); } } } /// <summary>Returns true if any fields do not omitTermFreqAndPositions </summary> internal bool HasProx() { int numFields = byNumber.Count; for (int i = 0; i < numFields; i++) { FieldInfo fi = FieldInfo(i); if (fi.isIndexed && !fi.omitTermFreqAndPositions) { return true; } } return false; } /// <summary> Add fields that are indexed. Whether they have termvectors has to be specified. /// /// </summary> /// <param name="names">The names of the fields /// </param> /// <param name="storeTermVectors">Whether the fields store term vectors or not /// </param> /// <param name="storePositionWithTermVector">true if positions should be stored. /// </param> /// <param name="storeOffsetWithTermVector">true if offsets should be stored /// </param> public void AddIndexed(System.Collections.Generic.ICollection<string> names, bool storeTermVectors, bool storePositionWithTermVector, bool storeOffsetWithTermVector) { lock (this) { foreach(string name in names) { Add(name, true, storeTermVectors, storePositionWithTermVector, storeOffsetWithTermVector); } } } /// <summary> Assumes the fields are not storing term vectors. /// /// </summary> /// <param name="names">The names of the fields /// </param> /// <param name="isIndexed">Whether the fields are indexed or not /// /// </param> /// <seealso cref="Add(String, bool)"> /// </seealso> public void Add(System.Collections.Generic.ICollection<string> names, bool isIndexed) { lock (this) { foreach(string name in names) { Add(name, isIndexed); } } } /// <summary> Calls 5 parameter add with false for all TermVector parameters. /// /// </summary> /// <param name="name">The name of the Fieldable /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <seealso cref="Add(String, bool, bool, bool, bool)"> /// </seealso> public void Add(String name, bool isIndexed) { lock (this) { Add(name, isIndexed, false, false, false, false); } } /// <summary> Calls 5 parameter add with false for term vector positions and offsets. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed"> true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector) { lock (this) { Add(name, isIndexed, storeTermVector, false, false, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector) { lock (this) { Add(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> /// <param name="omitNorms">true if the norms for the indexed field should be omitted /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms) { lock (this) { Add(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, false, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> /// <param name="omitNorms">true if the norms for the indexed field should be omitted /// </param> /// <param name="storePayloads">true if payloads should be stored for this field /// </param> /// <param name="omitTermFreqAndPositions">true if term freqs should be omitted for this field /// </param> public FieldInfo Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms, bool storePayloads, bool omitTermFreqAndPositions) { lock (this) { FieldInfo fi = FieldInfo(name); if (fi == null) { return AddInternal(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } else { fi.Update(isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } return fi; } } private FieldInfo AddInternal(String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms, bool storePayloads, bool omitTermFreqAndPositions) { name = StringHelper.Intern(name); var fi = new FieldInfo(name, isIndexed, byNumber.Count, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); byNumber.Add(fi); byName[name] = fi; return fi; } public int FieldNumber(System.String fieldName) { FieldInfo fi = FieldInfo(fieldName); return (fi != null)?fi.number:- 1; } public FieldInfo FieldInfo(System.String fieldName) { return byName[fieldName]; } /// <summary> Return the fieldName identified by its number. /// /// </summary> /// <param name="fieldNumber"> /// </param> /// <returns> the fieldName or an empty string when the field /// with the given number doesn't exist. /// </returns> public System.String FieldName(int fieldNumber) { FieldInfo fi = FieldInfo(fieldNumber); return (fi != null) ? fi.name : ""; } /// <summary> Return the fieldinfo object referenced by the fieldNumber.</summary> /// <param name="fieldNumber"> /// </param> /// <returns> the FieldInfo object or null when the given fieldNumber /// doesn't exist. /// </returns> public FieldInfo FieldInfo(int fieldNumber) { return (fieldNumber >= 0) ? byNumber[fieldNumber] : null; } public int Size() { return byNumber.Count; } public bool HasVectors() { bool hasVectors = false; for (int i = 0; i < Size(); i++) { if (FieldInfo(i).storeTermVector) { hasVectors = true; break; } } return hasVectors; } public void Write(Directory d, System.String name) { IndexOutput output = d.CreateOutput(name); try { Write(output); } finally { output.Close(); } } public void Write(IndexOutput output) { output.WriteVInt(CURRENT_FORMAT); output.WriteVInt(Size()); for (int i = 0; i < Size(); i++) { FieldInfo fi = FieldInfo(i); var bits = (byte) (0x0); if (fi.isIndexed) bits |= IS_INDEXED; if (fi.storeTermVector) bits |= STORE_TERMVECTOR; if (fi.storePositionWithTermVector) bits |= STORE_POSITIONS_WITH_TERMVECTOR; if (fi.storeOffsetWithTermVector) bits |= STORE_OFFSET_WITH_TERMVECTOR; if (fi.omitNorms) bits |= OMIT_NORMS; if (fi.storePayloads) bits |= STORE_PAYLOADS; if (fi.omitTermFreqAndPositions) bits |= OMIT_TERM_FREQ_AND_POSITIONS; output.WriteString(fi.name); output.WriteByte(bits); } } private void Read(IndexInput input, String fileName) { int firstInt = input.ReadVInt(); if (firstInt < 0) { // This is a real format format = firstInt; } else { format = FORMAT_PRE; } if (format != FORMAT_PRE & format != FORMAT_START) { throw new CorruptIndexException("unrecognized format " + format + " in file \"" + fileName + "\""); } int size; if (format == FORMAT_PRE) { size = firstInt; } else { size = input.ReadVInt(); //read in the size } for (int i = 0; i < size; i++) { String name = StringHelper.Intern(input.ReadString()); byte bits = input.ReadByte(); bool isIndexed = (bits & IS_INDEXED) != 0; bool storeTermVector = (bits & STORE_TERMVECTOR) != 0; bool storePositionsWithTermVector = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; bool storeOffsetWithTermVector = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; bool omitNorms = (bits & OMIT_NORMS) != 0; bool storePayloads = (bits & STORE_PAYLOADS) != 0; bool omitTermFreqAndPositions = (bits & OMIT_TERM_FREQ_AND_POSITIONS) != 0; AddInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } if (input.FilePointer != input.Length()) { throw new CorruptIndexException("did not read all bytes from file \"" + fileName + "\": read " + input.FilePointer + " vs size " + input.Length()); } } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Controls { public class GlassPanel : Panel { private int cornerRadius = 10; private Color hilightColor; private Color backColor; private Color borderColor = Color.WhiteSmoke; private int borderSize = 3; private float hilightBrightness = 21; private bool pressed = false; private GraphicsPath borderRectPath; private GraphicsPath topArcPath; private Bitmap outputImage; private Bitmap bevelOverlayImage; private Bitmap shadowImage; private float bevelOverlayImageAlpha = 0.9f; System.Drawing.Imaging.ImageAttributes backgroundImageAttributes; System.Drawing.Imaging.ImageAttributes overlayImageAttributes; private int shadowSize = 0; private Color shadowColor = Color.FromArgb(255, 0, 0, 0); private Blur blur; public GlassPanel() { borderRectPath = new GraphicsPath(); topArcPath = new GraphicsPath(); bevelOverlayImage = Properties.Resources.bevelOverlay; CalculateBackColors(Color.FromArgb(125, 44, 61, 90)); blur = new Blur(); blur.BlurType = BlurType.Both; } [DefaultValue(0)] public int ShadowSize { get { return shadowSize; } set { shadowSize = value; if (shadowSize > 0) { blur.Radius = shadowSize; } RecreateBorderRectPath(); ReCreateShadowImage(); RecreateImage(); this.Invalidate(); } } public Color ShadowColor { get { return shadowColor; } set { shadowColor = value; ReCreateShadowImage(); RecreateImage(); this.Invalidate(); } } [DefaultValue(10)] public int CornerRadius { get { return cornerRadius; } set { cornerRadius = value; RecreateBorderRectPath(); RecreateImage(); this.Invalidate(); } } [DefaultValue(false)] public bool Pressed { get { return pressed; } set { pressed = value; RecreateImage(); this.Invalidate(); } } public Color ButtonBackColor { get { return backColor; } set { CalculateBackColors(value); RecreateImage(); this.Invalidate(); } } public Color BorderColor { get { return borderColor; } set { borderColor = value; RecreateImage(); this.Invalidate(); } } [DefaultValue(3)] public int BorderSize { get { return borderSize; } set { borderSize = value; RecreateBorderRectPath(); RecreateImage(); this.Invalidate(); } } private void CalculateBackColors(Color backColor) { this.backColor = backColor; hilightColor = Color.FromArgb(backColor.A, Math.Min(255, (int)((float)backColor.R + hilightBrightness)), Math.Min(255, (int)((float)backColor.G + hilightBrightness)), Math.Min(255, (int)((float)backColor.B + hilightBrightness))); //hilightColor = Color.FromArgb(backColor.A, Math.Min(255, (int)((float)backColor.R + 21)), Math.Min(255, (int)((float)backColor.G + 21)), Math.Min(255, (int)((float)backColor.B + 21))); backgroundImageAttributes = GetImageAlphaAttributes(backColor.A); //overlayImageAttributes = GetImageAlphaAttributes(1.0f * ((float)backColor.A / 255.0f) * bevelOverlayImageAlpha); overlayImageAttributes = GetImageAlphaAttributes(backColor.A); } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); if (outputImage != null) { e.Graphics.DrawImage(outputImage, 0, 0, this.Width, this.Height); } } private static System.Drawing.Imaging.ImageAttributes GetImageAlphaAttributes(float alpha) { float[][] ptsArray ={ new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, alpha, 0}, new float[] {0, 0, 0, 0, 1}}; System.Drawing.Imaging.ColorMatrix clrMatrix = new System.Drawing.Imaging.ColorMatrix(ptsArray); System.Drawing.Imaging.ImageAttributes imgAttrs = new System.Drawing.Imaging.ImageAttributes(); imgAttrs.SetColorMatrix(clrMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap); return imgAttrs; } private static System.Drawing.Imaging.ImageAttributes GetImageAlphaAttributes(int alpha) { return GetImageAlphaAttributes(1.0f * ((float)alpha / 255.0f)); } protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); RecreateBorderRectPath(); ReCreateShadowImage(); RecreateImage(); } private void ReCreateShadowImage() { if (shadowImage != null) shadowImage.Dispose(); // Draw a drop shadow if one is needed if (shadowSize > 0 && this.Parent != null) { using (Bitmap tmpShadowImage = new Bitmap(this.Width, this.Height)) { using (Graphics sg = Graphics.FromImage(tmpShadowImage)) { using (SolidBrush sBrush = new SolidBrush(shadowColor)) { sg.FillPath(sBrush, borderRectPath); } } shadowImage = (Bitmap)blur.ProcessImage(tmpShadowImage); } // Clear out the center of our shadow image using (Graphics g = Graphics.FromImage(shadowImage)) { g.CompositingMode = CompositingMode.SourceCopy; using (SolidBrush sBrush = new SolidBrush(Color.Transparent)) { g.FillPath(sBrush, borderRectPath); } } } } private void RecreateBorderRectPath() { if (this.Parent == null || this.Width == 0 || this.Height == 0) return; borderRectPath.Reset(); int borderOffset = (int)((float)borderSize / 2.0f) + shadowSize; Rectangle tl = new Rectangle(borderOffset, borderOffset, cornerRadius, cornerRadius); Rectangle tr = new Rectangle(this.Width - cornerRadius - borderOffset - 1, borderOffset, cornerRadius, cornerRadius); Rectangle bl = new Rectangle(borderOffset, this.Height - cornerRadius - borderOffset - 1, cornerRadius, cornerRadius); Rectangle br = new Rectangle(this.Width - cornerRadius - borderOffset - 1, this.Height - cornerRadius - borderOffset - 1, cornerRadius, cornerRadius); borderRectPath.AddArc(tl, 180, 90); borderRectPath.AddArc(tr, 270, 90); borderRectPath.AddArc(br, 360, 90); borderRectPath.AddArc(bl, 90, 90); borderRectPath.CloseFigure(); Rectangle dividerArc = new Rectangle(borderOffset, (this.Height / 2) - 20, this.Width - (borderOffset * 2) - 1, 20); topArcPath.Reset(); topArcPath.AddArc(tl, 180, 90); topArcPath.AddArc(tr, 270, 90); if (pressed) { topArcPath.AddArc(dividerArc, 0, -180); } else { topArcPath.AddArc(dividerArc, 360, 180); } topArcPath.CloseFigure(); } private void RecreateImage() { if (this.Parent == null || this.Width == 0 || this.Height == 0) return; // Create our background Image Bitmap backgroundImage = new Bitmap(this.Width, this.Height); using (Graphics g = Graphics.FromImage(backgroundImage)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // Draw our background using (SolidBrush backBrush = new SolidBrush(Color.FromArgb(255, pressed ? hilightColor : backColor))) { g.FillPath(backBrush, borderRectPath); } // Draw our hilight using (SolidBrush topBrush = new SolidBrush(Color.FromArgb(255, pressed ? backColor : hilightColor))) { g.FillPath(topBrush, topArcPath); } } // Create our output image if (outputImage != null) outputImage.Dispose(); outputImage = new Bitmap(this.Width, this.Height); using (Graphics og = Graphics.FromImage(outputImage)) { // Draw our shadow image onto our output image if (shadowSize > 0 && shadowImage != null) { og.DrawImage(shadowImage, 0, 0, this.Width, this.Height); } // Draw our background onto our output image og.DrawImage(backgroundImage, new Rectangle(0, 0, this.Width, this.Height), 0, 0, this.Width, this.Height, GraphicsUnit.Pixel, backgroundImageAttributes); backgroundImage.Dispose(); // Stretch our bevel overlay image out using (Bitmap tmpBevelOverlayImage = new Bitmap(this.Width, this.Height)) { using (Graphics bg = Graphics.FromImage(tmpBevelOverlayImage)) { //bg.DrawImage(bevelOverlayImage, 0, 0, this.Width, this.Height); bg.DrawImage(bevelOverlayImage, new Rectangle(0, 0, this.Width, this.Height), 0, 0, bevelOverlayImage.Width, bevelOverlayImage.Height, GraphicsUnit.Pixel, overlayImageAttributes); } if (pressed) tmpBevelOverlayImage.RotateFlip(RotateFlipType.Rotate180FlipNone); // Draw our overlay using (TextureBrush tb = new TextureBrush(tmpBevelOverlayImage)) { og.FillPath(tb, borderRectPath); } } // Draw our border using (Pen borderPen = new Pen(borderColor, borderSize)) { og.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; borderPen.Alignment = System.Drawing.Drawing2D.PenAlignment.Center; og.DrawPath(borderPen, borderRectPath); } } } protected override void OnSizeChanged(EventArgs e) { RecreateBorderRectPath(); ReCreateShadowImage(); RecreateImage(); base.OnSizeChanged(e); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Notifications; using QuantConnect.Orders.Serialization; using QuantConnect.Packets; using QuantConnect.Util; namespace QuantConnect.Messaging { /// <summary> /// Local/desktop implementation of messaging system for Lean Engine. /// </summary> public class Messaging : IMessagingHandler { private static readonly bool UpdateRegressionStatistics = Config.GetBool("regression-update-statistics", false); private AlgorithmNodePacket _job; private OrderEventJsonConverter _orderEventJsonConverter; /// <summary> /// This implementation ignores the <seealso cref="HasSubscribers"/> flag and /// instead will always write to the log. /// </summary> public bool HasSubscribers { get; set; } /// <summary> /// Initialize the messaging system /// </summary> public void Initialize() { // } /// <summary> /// Set the messaging channel /// </summary> public void SetAuthentication(AlgorithmNodePacket job) { _job = job; _orderEventJsonConverter = new OrderEventJsonConverter(job.AlgorithmId); } /// <summary> /// Send a generic base packet without processing /// </summary> public void Send(Packet packet) { switch (packet.Type) { case PacketType.Debug: var debug = (DebugPacket) packet; Log.Trace("Debug: " + debug.Message); break; case PacketType.SystemDebug: var systemDebug = (SystemDebugPacket)packet; Log.Trace("Debug: " + systemDebug.Message); break; case PacketType.Log: var log = (LogPacket) packet; Log.Trace("Log: " + log.Message); break; case PacketType.RuntimeError: var runtime = (RuntimeErrorPacket) packet; var rstack = (!string.IsNullOrEmpty(runtime.StackTrace) ? (Environment.NewLine + " " + runtime.StackTrace) : string.Empty); Log.Error(runtime.Message + rstack); break; case PacketType.HandledError: var handled = (HandledErrorPacket) packet; var hstack = (!string.IsNullOrEmpty(handled.StackTrace) ? (Environment.NewLine + " " + handled.StackTrace) : string.Empty); Log.Error(handled.Message + hstack); break; case PacketType.AlphaResult: // spams the logs //var insights = ((AlphaResultPacket) packet).Insights; //foreach (var insight in insights) //{ // Log.Trace("Insight: " + insight); //} break; case PacketType.BacktestResult: var result = (BacktestResultPacket) packet; if (result.Progress == 1) { // inject alpha statistics into backtesting result statistics // this is primarily so we can easily regression test these values var alphaStatistics = result.Results.AlphaRuntimeStatistics?.ToDictionary() ?? Enumerable.Empty<KeyValuePair<string, string>>(); foreach (var kvp in alphaStatistics) { result.Results.Statistics.Add(kvp); } var orderHash = result.Results.Orders.GetHash(); result.Results.Statistics.Add("OrderListHash", orderHash); if (UpdateRegressionStatistics && _job.Language == Language.CSharp) { UpdateRegressionStatisticsInSourceFile(result); } var statisticsStr = $"{Environment.NewLine}" + $"{string.Join(Environment.NewLine,result.Results.Statistics.Select(x => $"STATISTICS:: {x.Key} {x.Value}"))}"; Log.Trace(statisticsStr); } break; } } /// <summary> /// Send any notification with a base type of Notification. /// </summary> public void SendNotification(Notification notification) { var type = notification.GetType(); if (type == typeof (NotificationEmail) || type == typeof (NotificationWeb) || type == typeof (NotificationSms) || type == typeof(NotificationTelegram)) { Log.Error("Messaging.SendNotification(): Send not implemented for notification of type: " + type.Name); return; } notification.Send(); } private void UpdateRegressionStatisticsInSourceFile(BacktestResultPacket result) { if (!result.Results.Statistics.Any()) { Log.Error("Messaging.UpdateRegressionStatisticsInSourceFile(): No statistics generated. Skipping update."); return; } var algorithmSource = Directory.EnumerateFiles("../../../Algorithm.CSharp", $"{_job.AlgorithmId}.cs", SearchOption.AllDirectories).SingleOrDefault(); if (algorithmSource == null) { algorithmSource = Directory.EnumerateFiles("../../../Algorithm.CSharp", $"*{_job.AlgorithmId}.cs", SearchOption.AllDirectories).Single(); } var file = File.ReadAllLines(algorithmSource).ToList().GetEnumerator(); var lines = new List<string>(); while (file.MoveNext()) { var line = file.Current; if (line == null) { continue; } if (line.Contains("Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>") || line.Contains("Dictionary<string, string> ExpectedStatistics => new()")) { lines.Add(line); lines.Add(" {"); foreach (var pair in result.Results.Statistics) { lines.Add($" {{\"{pair.Key}\", \"{pair.Value}\"}},"); } // remove trailing comma var lastLine = lines[lines.Count - 1]; lines[lines.Count - 1] = lastLine.Substring(0, lastLine.Length - 1); // now we skip existing expected statistics in file while (file.MoveNext()) { line = file.Current; if (line != null && line.Contains("};")) { lines.Add(line); break; } } } else { lines.Add(line); } } file.DisposeSafely(); File.WriteAllLines(algorithmSource, lines); } /// <summary> /// Dispose of any resources /// </summary> public void Dispose() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DrillTime.WebApiNoOwEf.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using CocosSharp; using CrashDrone.Common.Entities; using Microsoft.Xna.Framework; namespace CrashDrone.Common { public class HudLayer : CCLayerColor { CCSprite Battery10; CCSprite Battery20; CCSprite Battery30; CCSprite Battery40; CCSprite Battery50; CCSprite Battery60; CCSprite Battery70; CCSprite Battery80; CCSprite Battery90; CCSprite Battery100; CCSprite energySprite; public int energy; CCLabel energyLabel; public int Score; CCLabel ScoreLabel; CCLabel RestartLabel; NavigateButton buttonUp; NavigateButton buttonDown; public HudLayer(Action up, Action down) : base(CCColor4B.Transparent) { Score = 0; energy = 100; Battery10 = new CCSprite("/Assets/Content/Images/Hud/red_block_battery.png"); Battery10.Scale = 0.5f; AddChild(Battery10); Battery20 = new CCSprite("/Assets/Content/Images/Hud/red_block_battery.png"); Battery20.Scale = 0.5f; AddChild(Battery20); Battery30 = new CCSprite("/Assets/Content/Images/Hud/orange_block_battery.png"); Battery30.Scale = 0.5f; AddChild(Battery30); Battery40 = new CCSprite("/Assets/Content/Images/Hud/orange_block_battery.png"); Battery40.Scale = 0.5f; AddChild(Battery40); Battery50 = new CCSprite("/Assets/Content/Images/Hud/orange_block_battery.png"); Battery50.Scale = 0.5f; AddChild(Battery50); Battery60 = new CCSprite("/Assets/Content/Images/Hud/green_block_battery.png"); Battery60.Scale = 0.5f; AddChild(Battery60); Battery70 = new CCSprite("/Assets/Content/Images/Hud/green_block_battery.png"); Battery70.Scale = 0.5f; AddChild(Battery70); Battery80 = new CCSprite("/Assets/Content/Images/Hud/green_block_battery.png"); Battery80.Scale = 0.5f; AddChild(Battery80); Battery90 = new CCSprite("/Assets/Content/Images/Hud/green_block_battery.png"); Battery90.Scale = 0.5f; AddChild(Battery90); Battery100 = new CCSprite("/Assets/Content/Images/Hud/green_block_battery.png"); Battery100.Scale = 0.5f; AddChild(Battery100); energySprite = new CCSprite("/Assets/Content/Images/Hud/battery.png"); energySprite.Scale = 0.5f; AddChild(energySprite); energyLabel = new CCLabel("100%", "Fonts/MarkerFelt", 22, CCLabelFormat.SpriteFont); energyLabel.Color = CCColor3B.Green; AddChild(energyLabel); ScoreLabel = new CCLabel("Score: 0", "Fonts/MarkerFelt", 22, CCLabelFormat.SpriteFont); ScoreLabel.Color = new CCColor3B(200, 48, 255); AddChild(ScoreLabel); buttonUp = new NavigateButton("up", 100, up); AddChild(buttonUp); buttonDown = new NavigateButton("down", -100, down); AddChild(buttonDown); } protected override void AddedToScene() { base.AddedToScene(); var bounds = VisibleBoundsWorldspace; energySprite.Position = new CCPoint(bounds.MaxX * 0.1f, bounds.MaxY * 0.95f); energyLabel.Position = new CCPoint(bounds.MaxX * 0.1f, bounds.MaxY * 0.89f); ScoreLabel.Position = new CCPoint(bounds.MaxX * 0.25f, bounds.MaxY * 0.95f); Battery10.Position = new CCPoint(bounds.MaxX * 0.05f, bounds.MaxY * 0.95f); Battery20.Position = new CCPoint(bounds.MaxX * 0.06f, bounds.MaxY * 0.95f); Battery30.Position = new CCPoint(bounds.MaxX * 0.07f, bounds.MaxY * 0.95f); Battery40.Position = new CCPoint(bounds.MaxX * 0.08f, bounds.MaxY * 0.95f); Battery50.Position = new CCPoint(bounds.MaxX * 0.09f, bounds.MaxY * 0.95f); Battery60.Position = new CCPoint(bounds.MaxX * 0.10f, bounds.MaxY * 0.95f); Battery70.Position = new CCPoint(bounds.MaxX * 0.11f, bounds.MaxY * 0.95f); Battery80.Position = new CCPoint(bounds.MaxX * 0.12f, bounds.MaxY * 0.95f); Battery90.Position = new CCPoint(bounds.MaxX * 0.13f, bounds.MaxY * 0.95f); Battery100.Position = new CCPoint(bounds.MaxX * 0.14f, bounds.MaxY * 0.95f); buttonUp.Position = new CCPoint(bounds.MaxX * 0.9f, bounds.MaxY * 0.12f); buttonDown.Position = new CCPoint(bounds.MaxX * 0.1f, bounds.MaxY * 0.12f); } public void AddScore(int increase) { Score += increase; ScoreLabel.Text = string.Format("Score: {0}", Score); } public void AddEnergy(int addedAmount) { addedAmount = Math.Abs(addedAmount); energy = energy + addedAmount; if (energy > 100) { energy = 100; } energyLabel.Text = energy + "%"; SetBatteryVisibility(); } public void RemoveEnergy(int removedAmount) { removedAmount = Math.Abs(removedAmount); energy = energy - removedAmount; energyLabel.Text = energy + "%"; SetBatteryVisibility(); } private void SetBatteryVisibility() { Battery10.Visible = this.energy >= 10; Battery20.Visible = this.energy >= 20; Battery30.Visible = this.energy >= 30; Battery40.Visible = this.energy >= 40; Battery50.Visible = this.energy >= 50; Battery60.Visible = this.energy >= 60; Battery70.Visible = this.energy >= 70; Battery80.Visible = this.energy >= 80; Battery90.Visible = this.energy >= 90; Battery100.Visible = this.energy >= 100; if (this.energy >= 60) { energyLabel.Color = CCColor3B.Green; } else if (this.energy >= 30) { energyLabel.Color = CCColor3B.Yellow; } else if (this.energy > 0) { energyLabel.Color = CCColor3B.Red; } else { energyLabel.Color = CCColor3B.Black; energyLabel.Text = "GAME OVER"; } } Drone drone; public void FlashRestart(Drone drone) { this.drone = drone; Schedule(CheckFlashStart); } private void CheckFlashStart(float frameTimeInSeconds) { if (drone != null && drone.PositionY < 0) { RestartLabel = new CCLabel("Touch to restart", "Fonts/MarkerFelt", 22, CCLabelFormat.SpriteFont); RestartLabel.Color = new CCColor3B(200, 48, 255); RestartLabel.Position = new CCPoint(VisibleBoundsWorldspace.MaxX * 0.5f, VisibleBoundsWorldspace.MaxY * 0.5f); AddChild(RestartLabel); Schedule(FlashRestartInner); Unschedule(CheckFlashStart); } } private CCColor3B[] FlashColors = { CCColor3B.Black, CCColor3B.White, CCColor3B.DarkGray, CCColor3B.Yellow, CCColor3B.Gray, CCColor3B.Magenta, CCColor3B.Blue, CCColor3B.Orange, CCColor3B.Green, CCColor3B.Red }; private int _flashIndex = 1; private CCColor3B GetNextFlashColor() { if (_flashIndex < 9) { _flashIndex++; } else { _flashIndex = 0; } return FlashColors[_flashIndex]; } private void FlashRestartInner(float frameTimeInSeconds) { RestartLabel.Color = GetNextFlashColor(); } } }
using nHydrate.Generator.Common.EventArgs; using nHydrate.Generator.Common.GeneratorFramework; using nHydrate.Generator.Common.ProjectItemGenerators; using nHydrate.Generator.Common.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace nHydrate.Command.Core { internal class GeneratorHelper : nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper { private readonly string _outputFolder; public GeneratorHelper(string outputFolder) { _outputFolder = outputFolder; } protected override void GenerateProject(IGenerator generator, Type projectGeneratorType) { try { var projectGenerator = GetProjectGenerator(projectGeneratorType); projectGenerator.Initialize(generator.Model); CreateProject(generator, projectGeneratorType, _outputFolder); GenerateProjectItems(projectGenerator); } catch (Exception ex) { throw; } } protected override string GetExtensionsFolder() { return new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName; } protected override IProjectGeneratorProjectCreator GetProjectGeneratorProjectCreator(string outputFolder) { return new ProjectGeneratorProjectCreator(outputFolder); } protected override void LogError(string message) { //TODO: log to file } protected override void projectItemGenerator_ProjectItemDeleted(object sender, ProjectItemDeletedEventArgs e) { var name = e.ProjectItemName; if (name.StartsWith(Path.DirectorySeparatorChar)) name = name.Substring(1, name.Length - 1); e.FullName = System.IO.Path.Combine(_outputFolder, e.ProjectName, name); if (File.Exists(e.FullName)) File.Delete(e.FullName); e.FileState = Generator.Common.Util.FileStateConstants.Success; } protected override void projectItemGenerator_ProjectItemExists(object sender, ProjectItemExistsEventArgs e) { var name = e.ProjectItemName; if (name.StartsWith(Path.DirectorySeparatorChar)) name = name.Substring(1, name.Length - 1); var fileName = System.IO.Path.Combine(_outputFolder, e.ProjectName, name); e.Exists = File.Exists(fileName); } protected override void projectItemGenerator_ProjectItemGenerated(object sender, ProjectItemGeneratedEventArgs e) { var name = e.ProjectItemName; if (name.StartsWith(Path.DirectorySeparatorChar)) name = name.Substring(1, name.Length - 1); var pathsRelative = new List<string>(); var paths = new List<string>(); paths.AddRange(_outputFolder.Split(Path.DirectorySeparatorChar)); paths.AddRange(e.ProjectName.Split(Path.DirectorySeparatorChar)); if (!e.ParentItemName.IsEmpty() && !e.ParentItemName.Contains(".")) { paths.AddRange(e.ParentItemName.Split(Path.DirectorySeparatorChar)); pathsRelative.AddRange(e.ParentItemName.Split(Path.DirectorySeparatorChar)); } else if (!e.ParentItemName.IsEmpty() && e.ParentItemName.Contains(".")) { var arr = e.ParentItemName.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).ToList(); if (arr.Count > 1) { arr.RemoveAt(arr.Count - 1); paths.AddRange(arr); pathsRelative.AddRange(arr); } } paths.AddRange(name.Split(Path.DirectorySeparatorChar)); pathsRelative.AddRange(name.Split(Path.DirectorySeparatorChar)); var fileName = System.IO.Path.Combine(paths.ToArray()); //On linux the pasrsing of an absolute path will leave the first element of "paths" as empty string //Prepend file with path separator to signify absolute path if (paths.Any() && paths.FirstOrDefault() == string.Empty && !fileName.StartsWith(Path.DirectorySeparatorChar)) { fileName = Path.DirectorySeparatorChar + fileName; } var fileStateInfo = new Generator.Common.Util.FileStateInfo { FileName = fileName }; if (!File.Exists(fileName) || e.Overwrite) { var folderName = new FileInfo(fileName).DirectoryName; //In case this is a parent nested file, do not try to create if (!File.Exists(folderName)) { Directory.CreateDirectory(folderName); File.WriteAllText(fileName, e.ProjectItemContent); } else { fileName = System.IO.Path.Combine(_outputFolder, e.ProjectName, name); File.WriteAllText(fileName, e.ProjectItemContent); } } else fileStateInfo.FileState = Generator.Common.Util.FileStateConstants.Skipped; //Embed the file in the project if need be if (e.Properties.ContainsKey("BuildAction") && (int)e.Properties["BuildAction"] == 3) { var projectFileName = System.IO.Path.Combine(_outputFolder, e.ProjectName, $"{e.ProjectName}.csproj"); if (File.Exists(projectFileName)) { var includeFile = System.IO.Path.Combine(pathsRelative.ToArray()); var document = new XmlDocument(); document.PreserveWhitespace = true; document.Load(projectFileName); var groups = document.DocumentElement.SelectNodes("ItemGroup"); //Ensure file is not already embedded var checkFile = includeFile.Replace("/", @"\"); //in case linux if (document.DocumentElement.SelectSingleNode($"ItemGroup/EmbeddedResource[@Include='{checkFile}']") == null) { var whiteSpace = " "; XmlNode targetGroup = null; foreach (XmlElement g in groups) { //Find the first "ItemGroup" with a "EmbeddedResource" item //This will be the one to which we add the new embedded file if (g.SelectSingleNode("EmbeddedResource") != null) { if (g.FirstChild.NodeType == XmlNodeType.Whitespace) { if (g.FirstChild.Value.Replace("\r", "").Replace("\n", "").Contains('\t')) whiteSpace = "\t"; } targetGroup = g; break; } } //If there is no group create a new one if (targetGroup == null) targetGroup = document.DocumentElement.AppendChild(document.CreateElement("ItemGroup")); //Add whitespace and the item targetGroup.AppendChild(document.CreateSignificantWhitespace(whiteSpace)); var node = targetGroup.AppendChild(document.CreateElement("EmbeddedResource")); var attr = node.Attributes.Append(document.CreateAttribute("Include")); attr.Value = checkFile; targetGroup.AppendChild(document.CreateSignificantWhitespace("\r\n" + whiteSpace)); document.Save(projectFileName); } } } //Write Log Generator.Common.Logging.nHydrateLog.LogInfo("Project Item Generated: {0}", e.ProjectItemName); e.FileState = fileStateInfo.FileState; e.FullName = fileStateInfo.FileName; this.OnProjectItemGenerated(sender, e); } protected override void projectItemGenerator_ProjectItemGenerationError(object sender, ProjectItemGeneratedErrorEventArgs e) { if (e.ShowError) LogError(e.Text); } } internal class ProjectGeneratorProjectCreator : IProjectGeneratorProjectCreator { private string _outputFolder = ""; public ProjectGeneratorProjectCreator(string outputFolder) { _outputFolder = outputFolder; } public void CreateProject(IProjectGenerator projectGenerator) { var folder = Path.Combine(_outputFolder, projectGenerator.ProjectName); var csProjFile = Path.Combine(folder, projectGenerator.ProjectName + ".csproj"); //Do not overgen the project file if (File.Exists(csProjFile)) return; //If the project file does not exist then create it if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); var projectFileName = projectGenerator.ProjectTemplate.Replace(".vstemplate", ".csproj"); var embedPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + $".Resources.{projectFileName}"; var content = GetResource(embedPath); //Copy the template and project file to a temp folder and perform replacements var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); File.WriteAllText(csProjFile, content); projectGenerator.OnAfterGenerate(); } private string GetResource(string name) { var retVal = string.Empty; var asm = System.Reflection.Assembly.GetExecutingAssembly(); var manifestStream = asm.GetManifestResourceStream(name); try { using (var sr = new System.IO.StreamReader(manifestStream)) { retVal = sr.ReadToEnd(); } } catch { } finally { manifestStream.Close(); } return retVal; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace Telerivet.Client { /** Represents an automated service on Telerivet, for example a poll, auto-reply, webhook service, etc. A service, generally, defines some automated behavior that can be invoked/triggered in a particular context, and may be invoked either manually or when a particular event occurs. Most commonly, services work in the context of a particular message, when the message is originally received by Telerivet. Fields: - id (string, max 34 characters) * ID of the service * Read-only - name * Name of the service * Updatable via API - active (bool) * Whether the service is active or inactive. Inactive services are not automatically triggered and cannot be invoked via the API. * Updatable via API - priority (int) * A number that determines the order that services are triggered when a particular event occurs (smaller numbers are triggered first). Any service can determine whether or not execution "falls-through" to subsequent services (with larger priority values) by setting the return_value variable within Telerivet's Rules Engine. * Updatable via API - contexts (JObject) * A key/value map where the keys are the names of contexts supported by this service (e.g. message, contact), and the values are themselves key/value maps where the keys are event names and the values are all true. (This structure makes it easy to test whether a service can be invoked for a particular context and event.) * Read-only - vars (JObject) * Custom variables stored for this service * Updatable via API - project_id * ID of the project this service belongs to * Read-only - label_id * ID of the label containing messages sent or received by this service (currently only used for polls) * Read-only - response_table_id * ID of the data table where responses to this service will be stored (currently only used for polls) * Read-only - sample_group_id * ID of the group containing contacts that have been invited to interact with this service (currently only used for polls) * Read-only - respondent_group_id * ID of the group containing contacts that have completed an interaction with this service (currently only used for polls) * Read-only - questions (array) * Array of objects describing each question in a poll (only used for polls). Each object has the properties `"id"` (the question ID), `"content"` (the text of the question), and `"question_type"` (either `"multiple_choice"`, `"missed_call"`, or `"open"`). * Read-only */ public class Service : Entity { /** Gets the current state for a particular contact for this service. If the contact doesn't already have a state, this method will return a valid state object with id=null. However this object would not be returned by queryContactStates() unless it is saved with a non-null state id. */ public async Task<ContactServiceState> GetContactStateAsync(Contact contact) { return new ContactServiceState(api, (JObject) await api.DoRequestAsync("GET", GetBaseApiPath() + "/states/" + contact.Id)); } /** Initializes or updates the current state for a particular contact for the given service. If the state id is null, the contact's state will be reset. */ public async Task<ContactServiceState> SetContactStateAsync(Contact contact, JObject options) { return new ContactServiceState(api, (JObject) await api.DoRequestAsync("POST", GetBaseApiPath() + "/states/" + contact.Id, options)); } /** Resets the current state for a particular contact for the given service. */ public async Task<ContactServiceState> ResetContactStateAsync(Contact contact) { return new ContactServiceState(api, (JObject) await api.DoRequestAsync("DELETE", GetBaseApiPath() + "/states/" + contact.Id)); } /** Manually invoke this service in a particular context. For example, to send a poll to a particular contact (or resend the current question), you can invoke the poll service with context=contact, and `contact_id` as the ID of the contact to send the poll to. (To trigger a service to multiple contacts, use [project.sendBroadcast](#Project.sendBroadcast). To schedule a service in the future, use [project.scheduleMessage](#Project.scheduleMessage).) Or, to manually apply a service for an incoming message, you can invoke the service with `context`=`message`, `event`=`incoming_message`, and `message_id` as the ID of the incoming message. (This is normally not necessary, but could be used if you want to override Telerivet's standard priority-ordering of services.) */ public async Task<JObject> InvokeAsync(JObject options) { return (JObject) await api.DoRequestAsync("POST", GetBaseApiPath() + "/invoke", options); } /** Query the current states of contacts for this service. */ public APICursor<ContactServiceState> QueryContactStates(JObject options = null) { return api.NewCursor<ContactServiceState>(GetBaseApiPath() + "/states", options); } /** Saves any fields or custom variables that have changed for this service. */ public override async Task SaveAsync() { await base.SaveAsync(); } public string Id { get { return (string) Get("id"); } } public String Name { get { return (String) Get("name"); } set { Set("name", value); } } public bool Active { get { return (bool) Get("active"); } set { Set("active", value); } } public int Priority { get { return (int) Get("priority"); } set { Set("priority", value); } } public JObject Contexts { get { return (JObject) Get("contexts"); } } public String ProjectId { get { return (String) Get("project_id"); } } public String LabelId { get { return (String) Get("label_id"); } } public String ResponseTableId { get { return (String) Get("response_table_id"); } } public String SampleGroupId { get { return (String) Get("sample_group_id"); } } public String RespondentGroupId { get { return (String) Get("respondent_group_id"); } } public JArray Questions { get { return (JArray) Get("questions"); } } public override string GetBaseApiPath() { return "/projects/" + ProjectId + "/services/" + Id + ""; } public Service(TelerivetAPI api, JObject data, bool isLoaded = true) : base(api, data, isLoaded) { } } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Google.OrTools.ConstraintSolver; public class KillerSudoku { /** * Ensure that the sum of the segments * in cc == res * */ public static void calc(Solver solver, int[] cc, IntVar[,] x, int res) { // sum the numbers int len = cc.Length / 2; solver.Add( (from i in Enumerable.Range(0, len) select x[cc[i*2]-1,cc[i*2+1]-1]).ToArray().Sum() == res); } /** * * Killer Sudoku. * * http://en.wikipedia.org/wiki/Killer_Sudoku * """ * Killer sudoku (also killer su doku, sumdoku, sum doku, addoku, or * samunamupure) is a puzzle that combines elements of sudoku and kakuro. * Despite the name, the simpler killer sudokus can be easier to solve * than regular sudokus, depending on the solver's skill at mental arithmetic; * the hardest ones, however, can take hours to crack. * * ... * * The objective is to fill the grid with numbers from 1 to 9 in a way that * the following conditions are met: * * - Each row, column, and nonet contains each number exactly once. * - The sum of all numbers in a cage must match the small number printed * in its corner. * - No number appears more than once in a cage. (This is the standard rule * for killer sudokus, and implies that no cage can include more * than 9 cells.) * * In 'Killer X', an additional rule is that each of the long diagonals * contains each number once. * """ * * Here we solve the problem from the Wikipedia page, also shown here * http://en.wikipedia.org/wiki/File:Killersudoku_color.svg * * The output is: * 2 1 5 6 4 7 3 9 8 * 3 6 8 9 5 2 1 7 4 * 7 9 4 3 8 1 6 5 2 * 5 8 6 2 7 4 9 3 1 * 1 4 2 5 9 3 8 6 7 * 9 7 3 8 1 6 4 2 5 * 8 2 1 7 3 9 5 4 6 * 6 5 9 4 2 8 7 1 3 * 4 3 7 1 6 5 2 8 9 * * Also see http://www.hakank.org/or-tools/killer_sudoku.py * though this C# model has another representation of * the problem instance. * */ private static void Solve() { Solver solver = new Solver("KillerSudoku"); // size of matrix int cell_size = 3; IEnumerable<int> CELL = Enumerable.Range(0, cell_size); int n = cell_size*cell_size; IEnumerable<int> RANGE = Enumerable.Range(0, n); // For a better view of the problem, see // http://en.wikipedia.org/wiki/File:Killersudoku_color.svg // hints // sum, the hints // Note: this is 1-based int[][] problem = { new int[] { 3, 1,1, 1,2}, new int[] {15, 1,3, 1,4, 1,5}, new int[] {22, 1,6, 2,5, 2,6, 3,5}, new int[] {4, 1,7, 2,7}, new int[] {16, 1,8, 2,8}, new int[] {15, 1,9, 2,9, 3,9, 4,9}, new int[] {25, 2,1, 2,2, 3,1, 3,2}, new int[] {17, 2,3, 2,4}, new int[] { 9, 3,3, 3,4, 4,4}, new int[] { 8, 3,6, 4,6, 5,6}, new int[] {20, 3,7, 3,8, 4,7}, new int[] { 6, 4,1, 5,1}, new int[] {14, 4,2, 4,3}, new int[] {17, 4,5, 5,5, 6,5}, new int[] {17, 4,8, 5,7, 5,8}, new int[] {13, 5,2, 5,3, 6,2}, new int[] {20, 5,4, 6,4, 7,4}, new int[] {12, 5,9, 6,9}, new int[] {27, 6,1, 7,1, 8,1, 9,1}, new int[] { 6, 6,3, 7,2, 7,3}, new int[] {20, 6,6, 7,6, 7,7}, new int[] { 6, 6,7, 6,8}, new int[] {10, 7,5, 8,4, 8,5, 9,4}, new int[] {14, 7,8, 7,9, 8,8, 8,9}, new int[] { 8, 8,2, 9,2}, new int[] {16, 8,3, 9,3}, new int[] {15, 8,6, 8,7}, new int[] {13, 9,5, 9,6, 9,7}, new int[] {17, 9,8, 9,9} }; int num_p = 29; // Number of segments // // Decision variables // IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, 9, "x"); IntVar[] x_flat = x.Flatten(); // // Constraints // // // The first three constraints is the same as for sudokus.cs // // alldifferent rows and columns foreach(int i in RANGE) { // rows solver.Add( (from j in RANGE select x[i,j]).ToArray().AllDifferent()); // cols solver.Add( (from j in RANGE select x[j,i]).ToArray().AllDifferent()); } // cells foreach(int i in CELL) { foreach(int j in CELL) { solver.Add( (from di in CELL from dj in CELL select x[i*cell_size+di, j*cell_size+dj] ).ToArray().AllDifferent()); } } // Sum the segments and ensure alldifferent for(int i = 0; i < num_p; i++) { int[] segment = problem[i]; // Remove the sum from the segment int[] s2 = new int[segment.Length-1]; for(int j = 1; j < segment.Length; j++) { s2[j-1] = segment[j]; } // sum this segment calc(solver, s2, x, segment[0]); // all numbers in this segment must be distinct int len = segment.Length / 2; solver.Add( (from j in Enumerable.Range(0, len) select x[s2[j*2]-1, s2[j*2+1]-1]) .ToArray().AllDifferent()); } // // Search // DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { int v = (int)x[i,j].Value(); if (v > 0) { Console.Write(v + " "); } else { Console.Write(" "); } } Console.WriteLine(); } } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } public static void Main(String[] args) { Solve(); } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading; using System.Threading.Tasks; using Cassandra.DataStax.Insights.MessageFactories; using Cassandra.DataStax.Insights.Schema.StartupMessage; using Cassandra.DataStax.Insights.Schema.StatusMessage; using Cassandra.Responses; using Cassandra.SessionManagement; using Cassandra.Tasks; using Newtonsoft.Json; namespace Cassandra.DataStax.Insights { internal class InsightsClient : IInsightsClient { private const string ReportInsightRpc = "CALL InsightsRpc.reportInsight(?)"; private const int ErrorCountThresholdForLogging = 5; private static readonly Logger Logger = new Logger(typeof(InsightsClient)); private readonly IInternalCluster _cluster; private readonly IInternalSession _session; private readonly MonitorReportingOptions _monitorReportingOptions; private readonly IInsightsMessageFactory<InsightsStartupData> _startupMessageFactory; private readonly IInsightsMessageFactory<InsightsStatusData> _statusMessageFactory; private Task _insightsTask = null; private CancellationTokenSource _cancellationTokenSource; private volatile int _errorCount = 0; public InsightsClient( IInternalCluster cluster, IInternalSession session, IInsightsMessageFactory<InsightsStartupData> startupMessageFactory, IInsightsMessageFactory<InsightsStatusData> statusMessageFactory) { _cluster = cluster; _session = session; _monitorReportingOptions = cluster.Configuration.MonitorReportingOptions; _startupMessageFactory = startupMessageFactory; _statusMessageFactory = statusMessageFactory; } private bool Initialized => _insightsTask != null; private async Task<bool> SendStartupMessageAsync() { try { await SendJsonMessageAsync(_startupMessageFactory.CreateMessage(_cluster, _session)).ConfigureAwait(false); _errorCount = 0; return true; } catch (Exception ex) { if (_cancellationTokenSource.IsCancellationRequested || _errorCount >= InsightsClient.ErrorCountThresholdForLogging) { return false; } _errorCount++; InsightsClient.Logger.Verbose("Could not send insights startup event. Exception: {0}", ex.ToString()); return false; } } private async Task<bool> SendStatusMessageAsync() { try { await SendJsonMessageAsync(_statusMessageFactory.CreateMessage(_cluster, _session)).ConfigureAwait(false); _errorCount = 0; return true; } catch (Exception ex) { if (_cancellationTokenSource.IsCancellationRequested || _errorCount >= InsightsClient.ErrorCountThresholdForLogging) { return false; } _errorCount++; InsightsClient.Logger.Verbose("Could not send insights status event. Exception: {0}", ex.ToString()); return false; } } public void Init() { if (!ShouldStartInsightsTask()) { _insightsTask = null; return; } _cancellationTokenSource = new CancellationTokenSource(); _insightsTask = Task.Run(MainLoopAsync); } public Task ShutdownAsync() { if (!Initialized) { return TaskHelper.Completed; } _cancellationTokenSource.Cancel(); return _insightsTask; } public void Dispose() { ShutdownAsync().GetAwaiter().GetResult(); } private bool ShouldStartInsightsTask() { return _monitorReportingOptions.MonitorReportingEnabled && _cluster.Configuration.InsightsSupportVerifier.SupportsInsights(_cluster); } private async Task MainLoopAsync() { try { var startupSent = false; var isFirstDelay = true; // The initial delay should contain some random portion // Initial delay should be statusEventDelay - (0 to 10%) var percentageToSubtract = new Random(Guid.NewGuid().GetHashCode()).NextDouble() * 0.1; var delay = _monitorReportingOptions.StatusEventDelayMilliseconds - (_monitorReportingOptions.StatusEventDelayMilliseconds * percentageToSubtract); while (!_cancellationTokenSource.IsCancellationRequested) { if (!startupSent) { startupSent = await SendStartupMessageAsync().ConfigureAwait(false); } else { await SendStatusMessageAsync().ConfigureAwait(false); } await TaskHelper.DelayWithCancellation( TimeSpan.FromMilliseconds(delay), _cancellationTokenSource.Token).ConfigureAwait(false); if (isFirstDelay) { isFirstDelay = false; delay = _monitorReportingOptions.StatusEventDelayMilliseconds; } } } catch (Exception ex) { InsightsClient.Logger.Verbose("Unhandled exception in Insights task. Insights metrics will not be sent to the server anymore.", ex); } InsightsClient.Logger.Verbose("Insights task is ending."); } private async Task SendJsonMessageAsync<T>(T message) { var queryProtocolOptions = new QueryProtocolOptions( ConsistencyLevel.One, new object[] { JsonConvert.SerializeObject(message, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) }, false, 0, null, ConsistencyLevel.Any); var response = await RunWithTokenAsync(() => _cluster.Metadata.ControlConnection.UnsafeSendQueryRequestAsync( InsightsClient.ReportInsightRpc, queryProtocolOptions)).ConfigureAwait(false); if (response == null) { throw new DriverInternalError("Received null response."); } if (!(response is ResultResponse resultResponse)) { throw new DriverInternalError("Expected ResultResponse but received: " + response.GetType()); } if (resultResponse.Kind != ResultResponse.ResultResponseKind.Void) { throw new DriverInternalError("Expected ResultResponse of Kind \"Void\" but received: " + resultResponse.Kind); } } private Task<Response> RunWithTokenAsync(Func<Task<Response>> func) { var task = Task.Run(func, _cancellationTokenSource.Token); // (A canceled task will raise an exception when awaited). return task; } } }
// // Mono.CSharp.Debugger/MonoSymbolTable.cs // // Author: // Martin Baulig ([email protected]) // // (C) 2002 Ximian, Inc. http://www.ximian.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Cryptography; using System.Collections.Generic; using System.Text; using System.IO; // // Parts which are actually written into the symbol file are marked with // // #region This is actually written to the symbol file // #endregion // // Please do not modify these regions without previously talking to me. // // All changes to the file format must be synchronized in several places: // // a) The fields in these regions (and their order) must match the actual // contents of the symbol file. // // This helps people to understand the symbol file format without reading // too much source code, ie. you look at the appropriate region and then // you know what's actually in the file. // // It is also required to help me enforce b). // // b) The regions must be kept in sync with the unmanaged code in // mono/metadata/debug-mono-symfile.h // // When making changes to the file format, you must also increase two version // numbers: // // i) OffsetTable.Version in this file. // ii) MONO_SYMBOL_FILE_VERSION in mono/metadata/debug-mono-symfile.h // // After doing so, recompile everything, including the debugger. Symbol files // with different versions are incompatible to each other and the debugger and // the runtime enfore this, so you need to recompile all your assemblies after // changing the file format. // namespace Mono.CompilerServices.SymbolWriter { public class OffsetTable { public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 0x45e82623fd7fa614; #region This is actually written to the symbol file public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public Flags FileFlags; public int LineNumberTable_LineBase = LineNumberTable.Default_LineBase; public int LineNumberTable_LineRange = LineNumberTable.Default_LineRange; public int LineNumberTable_OpcodeBase = LineNumberTable.Default_OpcodeBase; #endregion internal OffsetTable () { int platform = (int) Environment.OSVersion.Platform; if ((platform != 4) && (platform != 128)) FileFlags |= Flags.WindowsFileNames; } internal OffsetTable (BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32 (); DataSectionOffset = reader.ReadInt32 (); DataSectionSize = reader.ReadInt32 (); CompileUnitCount = reader.ReadInt32 (); CompileUnitTableOffset = reader.ReadInt32 (); CompileUnitTableSize = reader.ReadInt32 (); SourceCount = reader.ReadInt32 (); SourceTableOffset = reader.ReadInt32 (); SourceTableSize = reader.ReadInt32 (); MethodCount = reader.ReadInt32 (); MethodTableOffset = reader.ReadInt32 (); MethodTableSize = reader.ReadInt32 (); TypeCount = reader.ReadInt32 (); AnonymousScopeCount = reader.ReadInt32 (); AnonymousScopeTableOffset = reader.ReadInt32 (); AnonymousScopeTableSize = reader.ReadInt32 (); LineNumberTable_LineBase = reader.ReadInt32 (); LineNumberTable_LineRange = reader.ReadInt32 (); LineNumberTable_OpcodeBase = reader.ReadInt32 (); FileFlags = (Flags) reader.ReadInt32 (); } internal void Write (BinaryWriter bw, int major_version, int minor_version) { bw.Write (TotalFileSize); bw.Write (DataSectionOffset); bw.Write (DataSectionSize); bw.Write (CompileUnitCount); bw.Write (CompileUnitTableOffset); bw.Write (CompileUnitTableSize); bw.Write (SourceCount); bw.Write (SourceTableOffset); bw.Write (SourceTableSize); bw.Write (MethodCount); bw.Write (MethodTableOffset); bw.Write (MethodTableSize); bw.Write (TypeCount); bw.Write (AnonymousScopeCount); bw.Write (AnonymousScopeTableOffset); bw.Write (AnonymousScopeTableSize); bw.Write (LineNumberTable_LineBase); bw.Write (LineNumberTable_LineRange); bw.Write (LineNumberTable_OpcodeBase); bw.Write ((int) FileFlags); } public override string ToString () { return String.Format ( "OffsetTable [{0} - {1}:{2} - {3}:{4}:{5} - {6}:{7}:{8} - {9}]", TotalFileSize, DataSectionOffset, DataSectionSize, SourceCount, SourceTableOffset, SourceTableSize, MethodCount, MethodTableOffset, MethodTableSize, TypeCount); } } public class LineNumberEntry { #region This is actually written to the symbol file public readonly int Row; public readonly int File; public readonly int Offset; public readonly bool IsHidden; #endregion public LineNumberEntry (int file, int row, int offset) : this (file, row, offset, false) { } public LineNumberEntry (int file, int row, int offset, bool is_hidden) { this.File = file; this.Row = row; this.Offset = offset; this.IsHidden = is_hidden; } public static LineNumberEntry Null = new LineNumberEntry (0, 0, 0); private class OffsetComparerClass : IComparer<LineNumberEntry> { public int Compare (LineNumberEntry l1, LineNumberEntry l2) { if (l1.Offset < l2.Offset) return -1; else if (l1.Offset > l2.Offset) return 1; else return 0; } } private class RowComparerClass : IComparer<LineNumberEntry> { public int Compare (LineNumberEntry l1, LineNumberEntry l2) { if (l1.Row < l2.Row) return -1; else if (l1.Row > l2.Row) return 1; else return 0; } } public static readonly IComparer<LineNumberEntry> OffsetComparer = new OffsetComparerClass (); public static readonly IComparer<LineNumberEntry> RowComparer = new RowComparerClass (); public override string ToString () { return String.Format ("[Line {0}:{1}:{2}]", File, Row, Offset); } } public class CodeBlockEntry { public int Index; #region This is actually written to the symbol file public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; #endregion public enum Type { Lexical = 1, CompilerGenerated = 2, IteratorBody = 3, IteratorDispatcher = 4 } public CodeBlockEntry (int index, int parent, Type type, int start_offset) { this.Index = index; this.Parent = parent; this.BlockType = type; this.StartOffset = start_offset; } internal CodeBlockEntry (int index, MyBinaryReader reader) { this.Index = index; int type_flag = reader.ReadLeb128 (); BlockType = (Type) (type_flag & 0x3f); this.Parent = reader.ReadLeb128 (); this.StartOffset = reader.ReadLeb128 (); this.EndOffset = reader.ReadLeb128 (); /* Reserved for future extensions. */ if ((type_flag & 0x40) != 0) { int data_size = reader.ReadInt16 (); reader.BaseStream.Position += data_size; } } public void Close (int end_offset) { this.EndOffset = end_offset; } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 ((int) BlockType); bw.WriteLeb128 (Parent); bw.WriteLeb128 (StartOffset); bw.WriteLeb128 (EndOffset); } public override string ToString () { return String.Format ("[CodeBlock {0}:{1}:{2}:{3}:{4}]", Index, Parent, BlockType, StartOffset, EndOffset); } } public struct LocalVariableEntry { #region This is actually written to the symbol file public readonly int Index; public readonly string Name; public readonly int BlockIndex; #endregion public LocalVariableEntry (int index, string name, int block) { this.Index = index; this.Name = name; this.BlockIndex = block; } internal LocalVariableEntry (MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128 (); Name = reader.ReadString (); BlockIndex = reader.ReadLeb128 (); } internal void Write (MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128 (Index); bw.Write (Name); bw.WriteLeb128 (BlockIndex); } public override string ToString () { return String.Format ("[LocalVariable {0}:{1}:{2}]", Name, Index, BlockIndex - 1); } } public struct CapturedVariable { #region This is actually written to the symbol file public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; #endregion public enum CapturedKind : byte { Local, Parameter, This } public CapturedVariable (string name, string captured_name, CapturedKind kind) { this.Name = name; this.CapturedName = captured_name; this.Kind = kind; } internal CapturedVariable (MyBinaryReader reader) { Name = reader.ReadString (); CapturedName = reader.ReadString (); Kind = (CapturedKind) reader.ReadByte (); } internal void Write (MyBinaryWriter bw) { bw.Write (Name); bw.Write (CapturedName); bw.Write ((byte) Kind); } public override string ToString () { return String.Format ("[CapturedVariable {0}:{1}:{2}]", Name, CapturedName, Kind); } } public struct CapturedScope { #region This is actually written to the symbol file public readonly int Scope; public readonly string CapturedName; #endregion public CapturedScope (int scope, string captured_name) { this.Scope = scope; this.CapturedName = captured_name; } internal CapturedScope (MyBinaryReader reader) { Scope = reader.ReadLeb128 (); CapturedName = reader.ReadString (); } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (Scope); bw.Write (CapturedName); } public override string ToString () { return String.Format ("[CapturedScope {0}:{1}]", Scope, CapturedName); } } public struct ScopeVariable { #region This is actually written to the symbol file public readonly int Scope; public readonly int Index; #endregion public ScopeVariable (int scope, int index) { this.Scope = scope; this.Index = index; } internal ScopeVariable (MyBinaryReader reader) { Scope = reader.ReadLeb128 (); Index = reader.ReadLeb128 (); } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (Scope); bw.WriteLeb128 (Index); } public override string ToString () { return String.Format ("[ScopeVariable {0}:{1}]", Scope, Index); } } public class AnonymousScopeEntry { #region This is actually written to the symbol file public readonly int ID; #endregion List<CapturedVariable> captured_vars = new List<CapturedVariable> (); List<CapturedScope> captured_scopes = new List<CapturedScope> (); public AnonymousScopeEntry (int id) { this.ID = id; } internal AnonymousScopeEntry (MyBinaryReader reader) { ID = reader.ReadLeb128 (); int num_captured_vars = reader.ReadLeb128 (); for (int i = 0; i < num_captured_vars; i++) captured_vars.Add (new CapturedVariable (reader)); int num_captured_scopes = reader.ReadLeb128 (); for (int i = 0; i < num_captured_scopes; i++) captured_scopes.Add (new CapturedScope (reader)); } internal void AddCapturedVariable (string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add (new CapturedVariable (name, captured_name, kind)); } public CapturedVariable[] CapturedVariables { get { CapturedVariable[] retval = new CapturedVariable [captured_vars.Count]; captured_vars.CopyTo (retval, 0); return retval; } } internal void AddCapturedScope (int scope, string captured_name) { captured_scopes.Add (new CapturedScope (scope, captured_name)); } public CapturedScope[] CapturedScopes { get { CapturedScope[] retval = new CapturedScope [captured_scopes.Count]; captured_scopes.CopyTo (retval, 0); return retval; } } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (ID); bw.WriteLeb128 (captured_vars.Count); foreach (CapturedVariable cv in captured_vars) cv.Write (bw); bw.WriteLeb128 (captured_scopes.Count); foreach (CapturedScope cs in captured_scopes) cs.Write (bw); } public override string ToString () { return String.Format ("[AnonymousScope {0}]", ID); } } public class CompileUnitEntry : ICompileUnit { #region This is actually written to the symbol file public readonly int Index; int DataOffset; #endregion MonoSymbolFile file; SourceFileEntry source; List<SourceFileEntry> include_files; List<NamespaceEntry> namespaces; bool creating; public static int Size { get { return 8; } } CompileUnitEntry ICompileUnit.Entry { get { return this; } } public CompileUnitEntry (MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; this.Index = file.AddCompileUnit (this); creating = true; namespaces = new List<NamespaceEntry> (); } public void AddFile (SourceFileEntry file) { if (!creating) throw new InvalidOperationException (); if (include_files == null) include_files = new List<SourceFileEntry> (); include_files.Add (file); } public SourceFileEntry SourceFile { get { if (creating) return source; ReadData (); return source; } } public int DefineNamespace (string name, string[] using_clauses, int parent) { if (!creating) throw new InvalidOperationException (); int index = file.GetNextNamespaceIndex (); NamespaceEntry ns = new NamespaceEntry (name, index, using_clauses, parent); namespaces.Add (ns); return index; } internal void WriteData (MyBinaryWriter bw) { DataOffset = (int) bw.BaseStream.Position; bw.WriteLeb128 (source.Index); int count_includes = include_files != null ? include_files.Count : 0; bw.WriteLeb128 (count_includes); if (include_files != null) { foreach (SourceFileEntry entry in include_files) bw.WriteLeb128 (entry.Index); } bw.WriteLeb128 (namespaces.Count); foreach (NamespaceEntry ns in namespaces) ns.Write (file, bw); } internal void Write (BinaryWriter bw) { bw.Write (Index); bw.Write (DataOffset); } internal CompileUnitEntry (MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); } void ReadData () { if (creating) throw new InvalidOperationException (); lock (file) { if (namespaces != null) return; MyBinaryReader reader = file.BinaryReader; int old_pos = (int) reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; int source_idx = reader.ReadLeb128 (); source = file.GetSourceFile (source_idx); int count_includes = reader.ReadLeb128 (); if (count_includes > 0) { include_files = new List<SourceFileEntry> (); for (int i = 0; i < count_includes; i++) include_files.Add (file.GetSourceFile (reader.ReadLeb128 ())); } int count_ns = reader.ReadLeb128 (); namespaces = new List<NamespaceEntry> (); for (int i = 0; i < count_ns; i ++) namespaces.Add (new NamespaceEntry (file, reader)); reader.BaseStream.Position = old_pos; } } public NamespaceEntry[] Namespaces { get { ReadData (); NamespaceEntry[] retval = new NamespaceEntry [namespaces.Count]; namespaces.CopyTo (retval, 0); return retval; } } public SourceFileEntry[] IncludeFiles { get { ReadData (); if (include_files == null) return new SourceFileEntry [0]; SourceFileEntry[] retval = new SourceFileEntry [include_files.Count]; include_files.CopyTo (retval, 0); return retval; } } } public class SourceFileEntry { #region This is actually written to the symbol file public readonly int Index; int DataOffset; #endregion MonoSymbolFile file; string file_name; byte[] guid; byte[] hash; bool creating; bool auto_generated; public static int Size { get { return 8; } } public SourceFileEntry (MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; this.Index = file.AddSource (this); creating = true; } public SourceFileEntry (MonoSymbolFile file, string file_name, byte[] guid, byte[] checksum) : this (file, file_name) { this.guid = guid; this.hash = checksum; } internal void WriteData (MyBinaryWriter bw) { DataOffset = (int) bw.BaseStream.Position; bw.Write (file_name); if (guid == null) { guid = Guid.NewGuid ().ToByteArray (); //try { // using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) { // MD5 md5 = MD5.Create (); // hash = md5.ComputeHash (fs); // } //} catch { hash = new byte [16]; //} } bw.Write (guid); bw.Write (hash); bw.Write ((byte) (auto_generated ? 1 : 0)); } internal void Write (BinaryWriter bw) { bw.Write (Index); bw.Write (DataOffset); } internal SourceFileEntry (MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); int old_pos = (int) reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; file_name = reader.ReadString (); guid = reader.ReadBytes (16); hash = reader.ReadBytes (16); auto_generated = reader.ReadByte () == 1; reader.BaseStream.Position = old_pos; } public string FileName { get { return file_name; } } public bool AutoGenerated { get { return auto_generated; } } public void SetAutoGenerated () { if (!creating) throw new InvalidOperationException (); auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum () { return true; //try { // using (FileStream fs = new FileStream (file_name, FileMode.Open)) { // MD5 md5 = MD5.Create (); // byte[] data = md5.ComputeHash (fs); // for (int i = 0; i < 16; i++) // if (data [i] != hash [i]) // return false; // return true; // } //} catch { // return false; //} } public override string ToString () { return String.Format ("SourceFileEntry ({0}:{1})", Index, DataOffset); } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public LineNumberEntry[] LineNumbers { get { return _line_numbers; } } public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; #region Configurable constants public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; public const bool SuppressDuplicates = true; #endregion public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; // MONO extensions. public const byte DW_LNE_MONO_negate_is_hidden = 0x40; internal const byte DW_LNE_MONO__extensions_start = 0x40; internal const byte DW_LNE_MONO__extensions_end = 0x7f; protected LineNumberTable (MonoSymbolFile file) { this.LineBase = file.OffsetTable.LineNumberTable_LineBase; this.LineRange = file.OffsetTable.LineNumberTable_LineRange; this.OpcodeBase = (byte) file.OffsetTable.LineNumberTable_OpcodeBase; this.MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable (MonoSymbolFile file, LineNumberEntry[] lines) : this (file) { this._line_numbers = lines; } internal void Write (MonoSymbolFile file, MyBinaryWriter bw) { int start = (int) bw.BaseStream.Position; bool last_is_hidden = false; int last_line = 1, last_offset = 0, last_file = 1; for (int i = 0; i < LineNumbers.Length; i++) { int line_inc = LineNumbers [i].Row - last_line; int offset_inc = LineNumbers [i].Offset - last_offset; if (SuppressDuplicates && (i+1 < LineNumbers.Length)) { if (LineNumbers [i+1].Equals (LineNumbers [i])) continue; } if (LineNumbers [i].File != last_file) { bw.Write (DW_LNS_set_file); bw.WriteLeb128 (LineNumbers [i].File); last_file = LineNumbers [i].File; } if (LineNumbers [i].IsHidden != last_is_hidden) { bw.Write ((byte) 0); bw.Write ((byte) 1); bw.Write (DW_LNE_MONO_negate_is_hidden); last_is_hidden = LineNumbers [i].IsHidden; } if (offset_inc >= MaxAddressIncrement) { if (offset_inc < 2 * MaxAddressIncrement) { bw.Write (DW_LNS_const_add_pc); offset_inc -= MaxAddressIncrement; } else { bw.Write (DW_LNS_advance_pc); bw.WriteLeb128 (offset_inc); offset_inc = 0; } } if ((line_inc < LineBase) || (line_inc >= LineBase + LineRange)) { bw.Write (DW_LNS_advance_line); bw.WriteLeb128 (line_inc); if (offset_inc != 0) { bw.Write (DW_LNS_advance_pc); bw.WriteLeb128 (offset_inc); } bw.Write (DW_LNS_copy); } else { byte opcode; opcode = (byte) (line_inc - LineBase + (LineRange * offset_inc) + OpcodeBase); bw.Write (opcode); } last_line = LineNumbers [i].Row; last_offset = LineNumbers [i].Offset; } bw.Write ((byte) 0); bw.Write ((byte) 1); bw.Write (DW_LNE_end_sequence); file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start; } internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br) { LineNumberTable lnt = new LineNumberTable (file); lnt.DoRead (file, br); return lnt; } void DoRead (MonoSymbolFile file, MyBinaryReader br) { var lines = new List<LineNumberEntry> (); bool is_hidden = false, modified = false; int stm_line = 1, stm_offset = 0, stm_file = 1; while (true) { byte opcode = br.ReadByte (); if (opcode == 0) { byte size = br.ReadByte (); long end_pos = br.BaseStream.Position + size; opcode = br.ReadByte (); if (opcode == DW_LNE_end_sequence) { if (modified) lines.Add (new LineNumberEntry ( stm_file, stm_line, stm_offset, is_hidden)); break; } else if (opcode == DW_LNE_MONO_negate_is_hidden) { is_hidden = !is_hidden; modified = true; } else if ((opcode >= DW_LNE_MONO__extensions_start) && (opcode <= DW_LNE_MONO__extensions_end)) { ; // reserved for future extensions } else { throw new MonoSymbolFileException ( "Unknown extended opcode {0:x} in LNT ({1})", opcode, file.FileName); } br.BaseStream.Position = end_pos; continue; } else if (opcode < OpcodeBase) { switch (opcode) { case DW_LNS_copy: lines.Add (new LineNumberEntry ( stm_file, stm_line, stm_offset, is_hidden)); modified = false; break; case DW_LNS_advance_pc: stm_offset += br.ReadLeb128 (); modified = true; break; case DW_LNS_advance_line: stm_line += br.ReadLeb128 (); modified = true; break; case DW_LNS_set_file: stm_file = br.ReadLeb128 (); modified = true; break; case DW_LNS_const_add_pc: stm_offset += MaxAddressIncrement; modified = true; break; default: throw new MonoSymbolFileException ( "Unknown standard opcode {0:x} in LNT", opcode); } } else { opcode -= OpcodeBase; stm_offset += opcode / LineRange; stm_line += LineBase + (opcode % LineRange); lines.Add (new LineNumberEntry ( stm_file, stm_line, stm_offset, is_hidden)); modified = false; } } _line_numbers = new LineNumberEntry [lines.Count]; lines.CopyTo (_line_numbers, 0); } public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers [0]; end = _line_numbers [_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { #region This is actually written to the symbol file public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; int DataOffset; int LocalVariableTableOffset; int LineNumberTableOffset; int CodeBlockTableOffset; int ScopeVariableTableOffset; int RealNameOffset; Flags flags; #endregion int index; public Flags MethodFlags { get { return flags; } } public readonly CompileUnitEntry CompileUnit; LocalVariableEntry[] locals; CodeBlockEntry[] code_blocks; ScopeVariable[] scope_vars; LineNumberTable lnt; string real_name; public readonly MonoSymbolFile SymbolFile; public int Index { get { return index; } set { index = value; } } [Flags] public enum Flags { LocalNamesAmbiguous = 1 } public const int Size = 12; internal MethodEntry (MonoSymbolFile file, MyBinaryReader reader, int index) { this.SymbolFile = file; this.index = index; Token = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); LineNumberTableOffset = reader.ReadInt32 (); long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128 (); LocalVariableTableOffset = reader.ReadLeb128 (); NamespaceID = reader.ReadLeb128 (); CodeBlockTableOffset = reader.ReadLeb128 (); ScopeVariableTableOffset = reader.ReadLeb128 (); RealNameOffset = reader.ReadLeb128 (); flags = (Flags) reader.ReadLeb128 (); reader.BaseStream.Position = old_pos; CompileUnit = file.GetCompileUnit (CompileUnitIndex); } internal MethodEntry (MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { this.SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable (lines); lnt = new LineNumberTable (file, lines); file.NumLineNumbers += lines.Length; int num_locals = locals != null ? locals.Length : 0; if (num_locals <= 32) { // Most of the time, the O(n^2) factor is actually // less than the cost of allocating the hash table, // 32 is a rough number obtained through some testing. for (int i = 0; i < num_locals; i ++) { string nm = locals [i].Name; for (int j = i + 1; j < num_locals; j ++) { if (locals [j].Name == nm) { flags |= Flags.LocalNamesAmbiguous; goto locals_check_done; } } } locals_check_done : ; } else { var local_names = new Dictionary<string, LocalVariableEntry> (); foreach (LocalVariableEntry local in locals) { if (local_names.ContainsKey (local.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } local_names.Add (local.Name, local); } } } void CheckLineNumberTable (LineNumberEntry[] line_numbers) { int last_offset = -1; int last_row = -1; if (line_numbers == null) return; for (int i = 0; i < line_numbers.Length; i++) { LineNumberEntry line = line_numbers [i]; if (line.Equals (LineNumberEntry.Null)) throw new MonoSymbolFileException (); if (line.Offset < last_offset) throw new MonoSymbolFileException (); if (line.Offset > last_offset) { last_row = line.Row; last_offset = line.Offset; } else if (line.Row > last_row) { last_row = line.Row; } } } internal void Write (MyBinaryWriter bw) { if ((index <= 0) || (DataOffset == 0)) throw new InvalidOperationException (); bw.Write (Token); bw.Write (DataOffset); bw.Write (LineNumberTableOffset); } internal void WriteData (MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) throw new InvalidOperationException (); LocalVariableTableOffset = (int) bw.BaseStream.Position; int num_locals = locals != null ? locals.Length : 0; bw.WriteLeb128 (num_locals); for (int i = 0; i < num_locals; i++) locals [i].Write (file, bw); file.LocalCount += num_locals; CodeBlockTableOffset = (int) bw.BaseStream.Position; int num_code_blocks = code_blocks != null ? code_blocks.Length : 0; bw.WriteLeb128 (num_code_blocks); for (int i = 0; i < num_code_blocks; i++) code_blocks [i].Write (bw); ScopeVariableTableOffset = (int) bw.BaseStream.Position; int num_scope_vars = scope_vars != null ? scope_vars.Length : 0; bw.WriteLeb128 (num_scope_vars); for (int i = 0; i < num_scope_vars; i++) scope_vars [i].Write (bw); if (real_name != null) { RealNameOffset = (int) bw.BaseStream.Position; bw.Write (real_name); } LineNumberTableOffset = (int) bw.BaseStream.Position; lnt.Write (file, bw); DataOffset = (int) bw.BaseStream.Position; bw.WriteLeb128 (CompileUnitIndex); bw.WriteLeb128 (LocalVariableTableOffset); bw.WriteLeb128 (NamespaceID); bw.WriteLeb128 (CodeBlockTableOffset); bw.WriteLeb128 (ScopeVariableTableOffset); bw.WriteLeb128 (RealNameOffset); bw.WriteLeb128 ((int) flags); } public LineNumberTable GetLineNumberTable () { lock (SymbolFile) { if (lnt != null) return lnt; if (LineNumberTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read (SymbolFile, reader); reader.BaseStream.Position = old_pos; return lnt; } } public LocalVariableEntry[] GetLocals () { lock (SymbolFile) { if (locals != null) return locals; if (LocalVariableTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = LocalVariableTableOffset; int num_locals = reader.ReadLeb128 (); locals = new LocalVariableEntry [num_locals]; for (int i = 0; i < num_locals; i++) locals [i] = new LocalVariableEntry (SymbolFile, reader); reader.BaseStream.Position = old_pos; return locals; } } public CodeBlockEntry[] GetCodeBlocks () { lock (SymbolFile) { if (code_blocks != null) return code_blocks; if (CodeBlockTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = CodeBlockTableOffset; int num_code_blocks = reader.ReadLeb128 (); code_blocks = new CodeBlockEntry [num_code_blocks]; for (int i = 0; i < num_code_blocks; i++) code_blocks [i] = new CodeBlockEntry (i, reader); reader.BaseStream.Position = old_pos; return code_blocks; } } public ScopeVariable[] GetScopeVariables () { lock (SymbolFile) { if (scope_vars != null) return scope_vars; if (ScopeVariableTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ScopeVariableTableOffset; int num_scope_vars = reader.ReadLeb128 (); scope_vars = new ScopeVariable [num_scope_vars]; for (int i = 0; i < num_scope_vars; i++) scope_vars [i] = new ScopeVariable (reader); reader.BaseStream.Position = old_pos; return scope_vars; } } public string GetRealName () { lock (SymbolFile) { if (real_name != null) return real_name; if (RealNameOffset == 0) return null; real_name = SymbolFile.BinaryReader.ReadString (RealNameOffset); return real_name; } } public int CompareTo (object obj) { MethodEntry method = (MethodEntry) obj; if (method.Token < Token) return 1; else if (method.Token > Token) return -1; else return 0; } public override string ToString () { return String.Format ("[Method {0}:{1:x}:{2}:{3}]", index, Token, CompileUnitIndex, CompileUnit); } } public struct NamespaceEntry { #region This is actually written to the symbol file public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; #endregion public NamespaceEntry (string name, int index, string[] using_clauses, int parent) { this.Name = name; this.Index = index; this.Parent = parent; this.UsingClauses = using_clauses != null ? using_clauses : new string [0]; } internal NamespaceEntry (MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString (); Index = reader.ReadLeb128 (); Parent = reader.ReadLeb128 (); int count = reader.ReadLeb128 (); UsingClauses = new string [count]; for (int i = 0; i < count; i++) UsingClauses [i] = reader.ReadString (); } internal void Write (MonoSymbolFile file, MyBinaryWriter bw) { bw.Write (Name); bw.WriteLeb128 (Index); bw.WriteLeb128 (Parent); bw.WriteLeb128 (UsingClauses.Length); foreach (string uc in UsingClauses) bw.Write (uc); } public override string ToString () { return String.Format ("[Namespace {0}:{1}:{2}]", Name, Index, Parent); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Lab3.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace AngleSharp.Css.Tests.Declarations { using NUnit.Framework; using static CssConstructionFunctions; [TestFixture] public class CssMarginPropertyTests { [Test] public void CssMarginLeftLengthLegal() { var snippet = "margin-left: 15px "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("15px", property.Value); } [Test] public void CssMarginLeftTinyValue_Issue80() { var snippet = "margin-left: 0.00001px"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("0.00001px", property.Value); } [Test] public void CssMarginLeftExponentialValue_Issue79() { var snippet = "margin-left: 1E5px"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("100000px", property.Value); } [Test] public void CssMarginLeftExponentialValueWithPlus_Issue79() { var snippet = "margin-left: 1E+5px"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("100000px", property.Value); } [Test] public void CssMarginLeftExponentialValueWithMinus_Issue79() { var snippet = "margin-left: 1E-2px"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("0.01px", property.Value); } [Test] public void CssMarginLeftInitialLegal() { var snippet = "margin-left: initial "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-left", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("initial", property.Value); } [Test] public void CssMarginRightLengthImportantLegal() { var snippet = "margin-right: 3em!important"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-right", property.Name); Assert.IsTrue(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("3em", property.Value); } [Test] public void CssMarginRightPercentLegal() { var snippet = "margin-right: 10%"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-right", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("10%", property.Value); } [Test] public void CssMarginTopPercentLegal() { var snippet = "margin-top: 4% "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-top", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("4%", property.Value); } [Test] public void CssMarginBottomZeroLegal() { var snippet = "margin-bottom: 0 "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-bottom", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("0", property.Value); } [Test] public void CssMarginBottomNegativeLegal() { var snippet = "margin-bottom: -3px "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-bottom", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("-3px", property.Value); } [Test] public void CssMarginBottomAutoLegal() { var snippet = "margin-bottom: auto "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin-bottom", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("auto", property.Value); } [Test] public void CssMarginAllZeroLegal() { var snippet = "margin: 0 "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("0", property.Value); } [Test] public void CssMarginAllPercentLegal() { var snippet = "margin: 25% "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("25%", property.Value); } [Test] public void CssMarginSidesLengthLegal() { var snippet = "margin: 10px 3em "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("10px 3em", property.Value); } [Test] public void CssMarginSidesLengthAndAutoLegal() { var snippet = "margin: 10px auto "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("10px auto", property.Value); } [Test] public void CssMarginAutoLegal() { var snippet = "margin: auto "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("auto", property.Value); } [Test] public void CssMarginThreeValuesLegal() { var snippet = "margin: 10px 3em 5px"; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("10px 3em 5px", property.Value); } [Test] public void CssMarginAllValuesWithPercentAndAutoLegal() { var snippet = "margin: 10px 5% auto 2% "; var property = ParseDeclaration(snippet); Assert.AreEqual("margin", property.Name); Assert.IsFalse(property.IsImportant); Assert.IsFalse(property.IsInherited); Assert.IsTrue(property.HasValue); Assert.AreEqual("10px 5% auto 2%", property.Value); } [Test] public void CssMarginTooManyValuesIllegal() { var snippet = "margin: 10px 5% 8px 2% 3px auto"; var property = ParseDeclaration(snippet); Assert.IsFalse(property.HasValue); } [Test] public void CssMarginShouldBeRecombinedCorrectly() { var snippet = ".centered {margin-bottom: 1px; margin-top: 2px; margin-left: 3px; margin-right: 4px}"; var expected = ".centered { margin: 2px 4px 1px 3px }"; var result = ParseRule(snippet); var actual = result.CssText; Assert.AreEqual(expected, actual); } [Test] public void CssMarginShouldBeSimplifiedCorrectly() { var snippet = ".centered {margin:0;margin-left:auto;margin-right:auto;text-align:left;}"; var expected = ".centered { margin: 0 auto; text-align: left }"; var result = ParseRule(snippet); var actual = result.CssText; Assert.AreEqual(expected, actual); } [Test] public void CssMarginShouldBeReducedCompletely() { var snippet = ".centered {margin-bottom: 0px; margin-top: 0; margin-left: 0px; margin-right: 0}"; var expected = ".centered { margin: 0 }"; var result = ParseRule(snippet); var actual = result.CssText; Assert.AreEqual(expected, actual); } [Test] public void CssMarginReductionForPeriodicExpansion() { var snippet = "p { margin: 0 auto; }"; var expected = "p { margin: 0 auto }"; var result = ParseRule(snippet); var actual = result.CssText; Assert.AreEqual(expected, actual); } } }
// 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 Bridge.Test.NUnit; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Bridge.ClientTest.IO { [Category(Constants.MODULE_IO)] [TestFixture(TestNameFormat = "WriteTests - {0}")] public class WriteTests { protected virtual Stream CreateStream() { return new MemoryStream(); } [Test] public void Synchronized_NewObject() { using (Stream str = CreateStream()) { StreamWriter writer = new StreamWriter(str); TextWriter synced = TextWriter.Synchronized(writer); // different with .NET, Bridge return the same writer in Synchronized Assert.True(writer == synced); writer.Write("app"); synced.Write("pad"); writer.Flush(); synced.Flush(); str.Position = 0; StreamReader reader = new StreamReader(str); Assert.AreEqual("apppad", reader.ReadLine()); } } [Test] public void WriteChars() { char[] chArr = setupArray(); // [] Write a wide variety of characters and read them back Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; for (int i = 0; i < chArr.Length; i++) sw.Write(chArr[i]); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.AreEqual((int)chArr[i], sr.Read()); } } private static char[] setupArray() { return new char[]{ char.MinValue ,char.MaxValue ,'\t' ,' ' ,'$' ,'@' ,'#' ,'\0' ,'\v' ,'\'' ,'\u3190' ,'\uC3A0' ,'A' ,'5' ,'\uFE70' ,'-' ,';' ,'\u00E6' }; } [Test] public void NullArray() { // [] Exception for null array Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0)); sw.Dispose(); } [Test] public void NegativeOffset() { char[] chArr = setupArray(); // [] Exception if offset is negative Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(chArr, -1, 0)); sw.Dispose(); } [Test] public void NegativeCount() { char[] chArr = setupArray(); // [] Exception if count is negative Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(chArr, 0, -1)); sw.Dispose(); } [Test] public void WriteCustomLenghtStrings() { char[] chArr = setupArray(); // [] Write some custom length strings Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; sw.Write(chArr, 2, 5); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); int tmp = 0; for (int i = 2; i < 7; i++) { tmp = sr.Read(); Assert.AreEqual((int)chArr[i], tmp); } ms.Dispose(); } [Test] public void WriteToStreamWriter() { char[] chArr = setupArray(); // [] Just construct a streamwriter and write to it //------------------------------------------------- Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; sw.Write(chArr, 0, chArr.Length); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.AreEqual((int)chArr[i], sr.Read()); } ms.Dispose(); } [Test] public void TestWritingPastEndOfArray() { char[] chArr = setupArray(); Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentException>(() => sw.Write(chArr, 1, chArr.Length)); sw.Dispose(); } [Test] public void VerifyWrittenString() { char[] chArr = setupArray(); // [] Write string with wide selection of characters and read it back StringBuilder sb = new StringBuilder(40); Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; for (int i = 0; i < chArr.Length; i++) sb.Append(chArr[i]); sw.Write(sb.ToString()); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.AreEqual((int)chArr[i], sr.Read()); } } [Test] public void NullStreamThrows() { // [] Null string should write nothing Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); sw.Write((string)null); sw.Flush(); Assert.True(0 == ms.Length); } [Test] public void NullNewLineAsync() { using (MemoryStream ms = new MemoryStream()) { string newLine; using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8, 16, true)) { newLine = sw.NewLine; sw.WriteLine(default(string)); sw.WriteLine(default(string)); } ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { Assert.AreEqual(newLine + newLine, sr.ReadToEnd()); } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Animation.DoubleKeyFrameCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Animation { public partial class DoubleKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public int Add(DoubleKeyFrame keyFrame) { return default(int); } public void Clear() { } public System.Windows.Media.Animation.DoubleKeyFrameCollection Clone() { return default(System.Windows.Media.Animation.DoubleKeyFrameCollection); } protected override void CloneCore(System.Windows.Freezable sourceFreezable) { } protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable) { } public bool Contains(DoubleKeyFrame keyFrame) { return default(bool); } public void CopyTo(DoubleKeyFrame[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } public DoubleKeyFrameCollection() { } protected override bool FreezeCore(bool isChecking) { return default(bool); } protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable) { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public int IndexOf(DoubleKeyFrame keyFrame) { return default(int); } public void Insert(int index, DoubleKeyFrame keyFrame) { } public void Remove(DoubleKeyFrame keyFrame) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(Array array, int index) { } int System.Collections.IList.Add(Object keyFrame) { return default(int); } bool System.Collections.IList.Contains(Object keyFrame) { return default(bool); } int System.Collections.IList.IndexOf(Object keyFrame) { return default(int); } void System.Collections.IList.Insert(int index, Object keyFrame) { } void System.Collections.IList.Remove(Object keyFrame) { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public static System.Windows.Media.Animation.DoubleKeyFrameCollection Empty { get { return default(System.Windows.Media.Animation.DoubleKeyFrameCollection); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public DoubleKeyFrame this [int index] { get { return default(DoubleKeyFrame); } set { } } public Object SyncRoot { get { return default(Object); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
namespace Nancy.Bootstrapper { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Nancy.Extensions; /// <summary> /// Scans the app domain for assemblies and types /// </summary> public static class AppDomainAssemblyTypeScanner { static AppDomainAssemblyTypeScanner() { LoadAssembliesWithNancyReferences(); } /// <summary> /// Nancy core assembly /// </summary> private static Assembly nancyAssembly = typeof(NancyEngine).Assembly; /// <summary> /// App domain type cache /// </summary> private static IEnumerable<Type> types; /// <summary> /// App domain assemblies cache /// </summary> private static IEnumerable<Assembly> assemblies; /// <summary> /// Indicates whether the all Assemblies, that references a Nancy assembly, have already been loaded /// </summary> private static bool nancyReferencingAssembliesLoaded; private static IEnumerable<Func<Assembly, bool>> assembliesToScan; /// <summary> /// The default assemblies for scanning. /// Includes the nancy assembly and anything referencing a nancy assembly /// </summary> public static Func<Assembly, bool>[] DefaultAssembliesToScan = new Func<Assembly, bool>[] { x => x == nancyAssembly, x => { return !x.GetName().Name.StartsWith("Nancy.Testing",StringComparison.OrdinalIgnoreCase) && x.GetReferencedAssemblies().Any(r => r.Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)); } }; /// <summary> /// Gets or sets a set of rules for which assemblies are scanned /// Defaults to just assemblies that have references to nancy, and nancy /// itself. /// Each item in the enumerable is a delegate that takes the assembly and /// returns true if it is to be included. Returning false doesn't mean it won't /// be included as a true from another delegate will take precedence. /// </summary> public static IEnumerable<Func<Assembly, bool>> AssembliesToScan { private get { return assembliesToScan ?? (assembliesToScan = DefaultAssembliesToScan); } set { assembliesToScan = value; UpdateTypes(); } } /// <summary> /// Gets app domain types. /// </summary> public static IEnumerable<Type> Types { get { return types; } } /// <summary> /// Gets app domain types. /// </summary> public static IEnumerable<Assembly> Assemblies { get { return assemblies; } } /// <summary> /// Add assemblies to the list of assemblies to scan for Nancy types /// </summary> /// <param name="assemblyNames">One or more assembly names</param> public static void AddAssembliesToScan(params string[] assemblyNames) { var normalisedNames = GetNormalisedAssemblyNames(assemblyNames).ToArray(); foreach (var assemblyName in normalisedNames) { LoadAssemblies(assemblyName + ".dll"); LoadAssemblies(assemblyName + ".exe"); } var scanningPredicates = normalisedNames.Select(s => { return (Func<Assembly, bool>)(a => a.GetName().Name == s); }); AssembliesToScan = AssembliesToScan.Union(scanningPredicates); } /// <summary> /// Add assemblies to the list of assemblies to scan for Nancy types /// </summary> /// <param name="assemblies">One of more assemblies</param> public static void AddAssembliesToScan(params Assembly[] assemblies) { foreach (var assembly in assemblies) { LoadAssemblies(assembly.GetName() + ".dll"); LoadAssemblies(assembly.GetName() + ".exe"); } var scanningPredicates = assemblies.Select(an => (Func<Assembly, bool>)(a => a == an)); AssembliesToScan = AssembliesToScan.Union(scanningPredicates); } /// <summary> /// Add predicates for determining which assemblies to scan for Nancy types /// </summary> /// <param name="predicates">One or more predicates</param> public static void AddAssembliesToScan(params Func<Assembly, bool>[] predicates) { AssembliesToScan = AssembliesToScan.Union(predicates); } /// <summary> /// Load assemblies from a the app domain base directory matching a given wildcard. /// Assemblies will only be loaded if they aren't already in the appdomain. /// </summary> /// <param name="wildcardFilename">Wildcard to match the assemblies to load</param> public static void LoadAssemblies(string wildcardFilename) { foreach (var directory in GetAssemblyDirectories()) { LoadAssemblies(directory, wildcardFilename); } } /// <summary> /// Load assemblies from a given directory matching a given wildcard. /// Assemblies will only be loaded if they aren't already in the appdomain. /// </summary> /// <param name="containingDirectory">Directory containing the assemblies</param> /// <param name="wildcardFilename">Wildcard to match the assemblies to load</param> public static void LoadAssemblies(string containingDirectory, string wildcardFilename) { UpdateAssemblies(); var existingAssemblyPaths = assemblies.Select(a => a.Location).ToArray(); var unloadedAssemblies = Directory.GetFiles(containingDirectory, wildcardFilename).Where( f => !existingAssemblyPaths.Contains(f, StringComparer.InvariantCultureIgnoreCase)).ToArray(); foreach (var unloadedAssembly in unloadedAssemblies) { Assembly.Load(AssemblyName.GetAssemblyName(unloadedAssembly)); } UpdateTypes(); } /// <summary> /// Refreshes the type cache if additional assemblies have been loaded. /// Note: This is called automatically if assemblies are loaded using LoadAssemblies. /// </summary> public static void UpdateTypes() { UpdateAssemblies(); types = (from assembly in assemblies from type in assembly.SafeGetExportedTypes() where !type.IsAbstract select type).ToArray(); } /// <summary> /// Updates the assembly cache from the appdomain /// </summary> private static void UpdateAssemblies() { assemblies = (from assembly in AppDomain.CurrentDomain.GetAssemblies() where AssembliesToScan.Any(asm => asm(assembly)) where !assembly.IsDynamic where !assembly.ReflectionOnly select assembly).ToArray(); } /// <summary> /// Loads any assembly that references a Nancy assembly. /// </summary> public static void LoadAssembliesWithNancyReferences() { if (nancyReferencingAssembliesLoaded) { return; } UpdateAssemblies(); var existingAssemblyPaths = assemblies.Select(a => a.Location).ToArray(); foreach (var directory in GetAssemblyDirectories()) { var unloadedAssemblies = Directory .GetFiles(directory, "*.dll") .Where(f => !existingAssemblyPaths.Contains(f, StringComparer.InvariantCultureIgnoreCase)).ToArray(); foreach (var unloadedAssembly in unloadedAssemblies) { Assembly inspectedAssembly = null; try { inspectedAssembly = Assembly.ReflectionOnlyLoadFrom(unloadedAssembly); } catch (BadImageFormatException biEx) { //the assembly maybe it's not managed code } if (inspectedAssembly != null && inspectedAssembly.GetReferencedAssemblies().Any(r => r.Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase))) { try { Assembly.Load(inspectedAssembly.GetName()); } catch { } } } } UpdateTypes(); UpdateTypes(); nancyReferencingAssembliesLoaded = true; } /// <summary> /// Gets all types implementing a particular interface/base class /// </summary> /// <param name="type">Type to search for</param> /// <returns>An <see cref="IEnumerable{T}"/> of types.</returns> /// <remarks>Will scan with <see cref="ScanMode.All"/>.</remarks> public static IEnumerable<Type> TypesOf(Type type) { return TypesOf(type, ScanMode.All); } /// <summary> /// Gets all types implementing a particular interface/base class /// </summary> /// <param name="type">Type to search for</param> /// <param name="mode">A <see cref="ScanMode"/> value to determin which type set to scan in.</param> /// <returns>An <see cref="IEnumerable{T}"/> of types.</returns> public static IEnumerable<Type> TypesOf(Type type, ScanMode mode) { var returnTypes = Types.Where(type.IsAssignableFrom); if (mode == ScanMode.All) { return returnTypes; } return (mode == ScanMode.OnlyNancy) ? returnTypes.Where(t => t.Assembly == nancyAssembly) : returnTypes.Where(t => t.Assembly != nancyAssembly); } /// <summary> /// Gets all types implementing a particular interface/base class /// </summary> /// <typeparam name="TType">Type to search for</typeparam> /// <returns>An <see cref="IEnumerable{T}"/> of types.</returns> /// <remarks>Will scan with <see cref="ScanMode.All"/>.</remarks> public static IEnumerable<Type> TypesOf<TType>() { return TypesOf<TType>(ScanMode.All); } /// <summary> /// Gets all types implementing a particular interface/base class /// </summary> /// <typeparam name="TType">Type to search for</typeparam> /// <param name="mode">A <see cref="ScanMode"/> value to determin which type set to scan in.</param> /// <returns>An <see cref="IEnumerable{T}"/> of types.</returns> public static IEnumerable<Type> TypesOf<TType>(ScanMode mode) { return TypesOf(typeof(TType), mode); } /// <summary> /// Returns the directories containing dll files. It uses the default convention as stated by microsoft. /// </summary> /// <see cref="http://msdn.microsoft.com/en-us/library/system.appdomainsetup.privatebinpathprobe.aspx"/> private static IEnumerable<string> GetAssemblyDirectories() { var privateBinPathDirectories = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath == null ? new string[] { } : AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(';'); foreach (var privateBinPathDirectory in privateBinPathDirectories) { if (!string.IsNullOrWhiteSpace(privateBinPathDirectory)) { yield return privateBinPathDirectory; } } if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPathProbe == null) { yield return AppDomain.CurrentDomain.SetupInformation.ApplicationBase; } } private static IEnumerable<string> GetNormalisedAssemblyNames(string[] assemblyNames) { foreach (var assemblyName in assemblyNames) { if (assemblyName.EndsWith(".dll") || assemblyName.EndsWith(".exe")) { yield return Path.GetFileNameWithoutExtension(assemblyName); } else { yield return assemblyName; } } } } public static class AppDomainAssemblyTypeScannerExtensions { public static IEnumerable<Type> NotOfType<TType>(this IEnumerable<Type> types) { return types.Where(t => !typeof(TType).IsAssignableFrom(t)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// The implementation of the "get-alias" cmdlet. /// </summary> [Cmdlet(VerbsCommon.Get, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113306")] [OutputType(typeof(AliasInfo))] public class GetAliasCommand : PSCmdlet { #region Parameters /// <summary> /// The Name parameter for the command. /// </summary> [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty()] public string[] Name { get { return _names; } set { _names = value ?? new string[] { "*" }; } } private string[] _names = new string[] { "*" }; /// <summary> /// The Exclude parameter for the command. /// </summary> [Parameter] public string[] Exclude { get { return _excludes; } set { _excludes = value ?? new string[0]; } } private string[] _excludes = new string[0]; /// <summary> /// The scope parameter for the command determines /// which scope the aliases are retrieved from. /// </summary> [Parameter] public string Scope { get; set; } /// <summary> /// Parameter definition to retrieve aliases based on their definitions. /// </summary> [Parameter(ParameterSetName = "Definition")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Definition { get; set; } #endregion Parameters #region Command code /// <summary> /// The main processing loop of the command. /// </summary> protected override void ProcessRecord() { if (ParameterSetName.Equals("Definition")) { foreach (string defn in Definition) { WriteMatches(defn, "Definition"); } } else { foreach (string aliasName in _names) { WriteMatches(aliasName, "Default"); } } } #endregion Command code private void WriteMatches(string value, string parametersetname) { // First get the alias table (from the proper scope if necessary) IDictionary<string, AliasInfo> aliasTable = null; // get the command origin CommandOrigin origin = MyInvocation.CommandOrigin; string displayString = "name"; if (!string.IsNullOrEmpty(Scope)) { // This can throw PSArgumentException and PSArgumentOutOfRangeException // but just let them go as this is terminal for the pipeline and the // exceptions are already properly adorned with an ErrorRecord. aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope); } else { aliasTable = SessionState.Internal.GetAliasTable(); } bool matchfound = false; bool ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value); WildcardPattern wcPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); // excluding patter for Default paramset. Collection<WildcardPattern> excludePatterns = SessionStateUtilities.CreateWildcardsFromStrings( _excludes, WildcardOptions.IgnoreCase); List<AliasInfo> results = new List<AliasInfo>(); foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable) { if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase)) { displayString = "definition"; if (!wcPattern.IsMatch(tableEntry.Value.Definition)) { continue; } if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false)) { continue; } } else { if (!wcPattern.IsMatch(tableEntry.Key)) { continue; } // excludes pattern if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false)) { continue; } } if (ContainsWildcard) { // Only write the command if it is visible to the requestor if (SessionState.IsVisible(origin, tableEntry.Value)) { matchfound = true; results.Add(tableEntry.Value); } } else { // For specifically named elements, generate an error for elements that aren't visible... try { SessionState.ThrowIfNotVisible(origin, tableEntry.Value); results.Add(tableEntry.Value); matchfound = true; } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); // Even though it resulted in an error, a result was found // so we don't want to generate the nothing found error // at the end... matchfound = true; continue; } } } results.Sort( delegate (AliasInfo left, AliasInfo right) { return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name); }); foreach (AliasInfo alias in results) { this.WriteObject(alias); } if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0)) { // Need to write an error if the user tries to get an alias // tat doesn't exist and they are not globbing. ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value)); ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value); WriteError(er); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.AspNet.Razor.Editor; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Text; using Microsoft.AspNet.Razor.Tokenizer.Symbols; namespace Microsoft.AspNet.Razor.Parser { public partial class HtmlMarkupParser { private SourceLocation _lastTagStart = SourceLocation.Zero; private HtmlSymbol _bufferedOpenAngle; public override void ParseBlock() { if (Context == null) { throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set); } using (PushSpanConfig(DefaultMarkupSpan)) { using (Context.StartBlock(BlockType.Markup)) { if (!NextToken()) { return; } AcceptWhile(IsSpacingToken(includeNewLines: true)); if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle) { // "<" => Implicit Tag Block TagBlock(new Stack<Tuple<HtmlSymbol, SourceLocation>>()); } else if (CurrentSymbol.Type == HtmlSymbolType.Transition) { // "@" => Explicit Tag/Single Line Block OR Template Output(SpanKind.Markup); // Definitely have a transition span Assert(HtmlSymbolType.Transition); AcceptAndMoveNext(); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; Span.CodeGenerator = SpanCodeGenerator.Null; Output(SpanKind.Transition); if (At(HtmlSymbolType.Transition)) { Span.CodeGenerator = SpanCodeGenerator.Null; AcceptAndMoveNext(); Output(SpanKind.MetaCode); } AfterTransition(); } else { Context.OnError(CurrentSymbol.Start, RazorResources.ParseError_MarkupBlock_Must_Start_With_Tag); } Output(SpanKind.Markup); } } } private void DefaultMarkupSpan(SpanBuilder span) { span.CodeGenerator = new MarkupCodeGenerator(); span.EditHandler = new SpanEditHandler(Language.TokenizeString, AcceptedCharacters.Any); } private void AfterTransition() { // "@:" => Explicit Single Line Block if (CurrentSymbol.Type == HtmlSymbolType.Text && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == ':') { // Split the token Tuple<HtmlSymbol, HtmlSymbol> split = Language.SplitSymbol(CurrentSymbol, 1, HtmlSymbolType.Colon); // The first part (left) is added to this span and we return a MetaCode span Accept(split.Item1); Span.CodeGenerator = SpanCodeGenerator.Null; Output(SpanKind.MetaCode); if (split.Item2 != null) { Accept(split.Item2); } NextToken(); SingleLineMarkup(); } else if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle) { TagBlock(new Stack<Tuple<HtmlSymbol, SourceLocation>>()); } } private void SingleLineMarkup() { // Parse until a newline, it's that simple! // First, signal to code parser that whitespace is significant to us. bool old = Context.WhiteSpaceIsSignificantToAncestorBlock; Context.WhiteSpaceIsSignificantToAncestorBlock = true; Span.EditHandler = new SingleLineMarkupEditHandler(Language.TokenizeString); SkipToAndParseCode(HtmlSymbolType.NewLine); if (!EndOfFile && CurrentSymbol.Type == HtmlSymbolType.NewLine) { AcceptAndMoveNext(); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; } PutCurrentBack(); Context.WhiteSpaceIsSignificantToAncestorBlock = old; Output(SpanKind.Markup); } private void TagBlock(Stack<Tuple<HtmlSymbol, SourceLocation>> tags) { // Skip Whitespace and Text bool complete = false; do { SkipToAndParseCode(HtmlSymbolType.OpenAngle); if (EndOfFile) { EndTagBlock(tags, complete: true); } else { _bufferedOpenAngle = null; _lastTagStart = CurrentLocation; Assert(HtmlSymbolType.OpenAngle); _bufferedOpenAngle = CurrentSymbol; SourceLocation tagStart = CurrentLocation; if (!NextToken()) { Accept(_bufferedOpenAngle); EndTagBlock(tags, complete: false); } else { complete = AfterTagStart(tagStart, tags); } } } while (tags.Count > 0); EndTagBlock(tags, complete); } private bool AfterTagStart(SourceLocation tagStart, Stack<Tuple<HtmlSymbol, SourceLocation>> tags) { if (!EndOfFile) { switch (CurrentSymbol.Type) { case HtmlSymbolType.Solidus: // End Tag return EndTag(tagStart, tags); case HtmlSymbolType.Bang: // Comment Accept(_bufferedOpenAngle); return BangTag(); case HtmlSymbolType.QuestionMark: // XML PI Accept(_bufferedOpenAngle); return XmlPI(); default: // Start Tag return StartTag(tags); } } if (tags.Count == 0) { Context.OnError(CurrentLocation, RazorResources.ParseError_OuterTagMissingName); } return false; } private bool XmlPI() { // Accept "?" Assert(HtmlSymbolType.QuestionMark); AcceptAndMoveNext(); return AcceptUntilAll(HtmlSymbolType.QuestionMark, HtmlSymbolType.CloseAngle); } private bool BangTag() { // Accept "!" Assert(HtmlSymbolType.Bang); if (AcceptAndMoveNext()) { if (CurrentSymbol.Type == HtmlSymbolType.DoubleHyphen) { AcceptAndMoveNext(); return AcceptUntilAll(HtmlSymbolType.DoubleHyphen, HtmlSymbolType.CloseAngle); } else if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket) { if (AcceptAndMoveNext()) { return CData(); } } else { AcceptAndMoveNext(); return AcceptUntilAll(HtmlSymbolType.CloseAngle); } } return false; } private bool CData() { if (CurrentSymbol.Type == HtmlSymbolType.Text && String.Equals(CurrentSymbol.Content, "cdata", StringComparison.OrdinalIgnoreCase)) { if (AcceptAndMoveNext()) { if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket) { return AcceptUntilAll(HtmlSymbolType.RightBracket, HtmlSymbolType.RightBracket, HtmlSymbolType.CloseAngle); } } } return false; } private bool EndTag(SourceLocation tagStart, Stack<Tuple<HtmlSymbol, SourceLocation>> tags) { // Accept "/" and move next Assert(HtmlSymbolType.Solidus); HtmlSymbol solidus = CurrentSymbol; if (!NextToken()) { Accept(_bufferedOpenAngle); Accept(solidus); return false; } else { string tagName = String.Empty; if (At(HtmlSymbolType.Text)) { tagName = CurrentSymbol.Content; } bool matched = RemoveTag(tags, tagName, tagStart); if (tags.Count == 0 && String.Equals(tagName, SyntaxConstants.TextTagName, StringComparison.OrdinalIgnoreCase) && matched) { Output(SpanKind.Markup); return EndTextTag(solidus); } Accept(_bufferedOpenAngle); Accept(solidus); AcceptUntil(HtmlSymbolType.CloseAngle); // Accept the ">" return Optional(HtmlSymbolType.CloseAngle); } } private bool EndTextTag(HtmlSymbol solidus) { SourceLocation start = _bufferedOpenAngle.Start; Accept(_bufferedOpenAngle); Accept(solidus); Assert(HtmlSymbolType.Text); AcceptAndMoveNext(); bool seenCloseAngle = Optional(HtmlSymbolType.CloseAngle); if (!seenCloseAngle) { Context.OnError(start, RazorResources.ParseError_TextTagCannotContainAttributes); } else { Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; } Span.CodeGenerator = SpanCodeGenerator.Null; Output(SpanKind.Transition); return seenCloseAngle; } private bool IsTagRecoveryStopPoint(HtmlSymbol sym) { return sym.Type == HtmlSymbolType.CloseAngle || sym.Type == HtmlSymbolType.Solidus || sym.Type == HtmlSymbolType.OpenAngle || sym.Type == HtmlSymbolType.SingleQuote || sym.Type == HtmlSymbolType.DoubleQuote; } private void TagContent() { if (!At(HtmlSymbolType.WhiteSpace)) { // We should be right after the tag name, so if there's no whitespace, something is wrong RecoverToEndOfTag(); } else { // We are here ($): <tag$ foo="bar" biz="~/Baz" /> while (!EndOfFile && !IsEndOfTag()) { BeforeAttribute(); } } } private bool IsEndOfTag() { if (At(HtmlSymbolType.Solidus)) { if (NextIs(HtmlSymbolType.CloseAngle)) { return true; } else { AcceptAndMoveNext(); } } return At(HtmlSymbolType.CloseAngle) || At(HtmlSymbolType.OpenAngle); } private void BeforeAttribute() { // http://dev.w3.org/html5/spec/tokenization.html#before-attribute-name-state // Capture whitespace var whitespace = ReadWhile(sym => sym.Type == HtmlSymbolType.WhiteSpace || sym.Type == HtmlSymbolType.NewLine); if (At(HtmlSymbolType.Transition)) { // Transition outside of attribute value => Switch to recovery mode Accept(whitespace); RecoverToEndOfTag(); return; } // http://dev.w3.org/html5/spec/tokenization.html#attribute-name-state // Read the 'name' (i.e. read until the '=' or whitespace/newline) var name = Enumerable.Empty<HtmlSymbol>(); if (At(HtmlSymbolType.Text)) { name = ReadWhile(sym => sym.Type != HtmlSymbolType.WhiteSpace && sym.Type != HtmlSymbolType.NewLine && sym.Type != HtmlSymbolType.Equals && sym.Type != HtmlSymbolType.CloseAngle && sym.Type != HtmlSymbolType.OpenAngle && (sym.Type != HtmlSymbolType.Solidus || !NextIs(HtmlSymbolType.CloseAngle))); } else { // Unexpected character in tag, enter recovery Accept(whitespace); RecoverToEndOfTag(); return; } if (!At(HtmlSymbolType.Equals)) { // Saw a space or newline after the name, so just skip this attribute and continue around the loop Accept(whitespace); Accept(name); return; } Output(SpanKind.Markup); // Start a new markup block for the attribute using (Context.StartBlock(BlockType.Markup)) { AttributePrefix(whitespace, name); } } private void AttributePrefix(IEnumerable<HtmlSymbol> whitespace, IEnumerable<HtmlSymbol> nameSymbols) { // First, determine if this is a 'data-' attribute (since those can't use conditional attributes) LocationTagged<string> name = nameSymbols.GetContent(Span.Start); bool attributeCanBeConditional = !name.Value.StartsWith("data-", StringComparison.OrdinalIgnoreCase); // Accept the whitespace and name Accept(whitespace); Accept(nameSymbols); Assert(HtmlSymbolType.Equals); // We should be at "=" AcceptAndMoveNext(); HtmlSymbolType quote = HtmlSymbolType.Unknown; if (At(HtmlSymbolType.SingleQuote) || At(HtmlSymbolType.DoubleQuote)) { quote = CurrentSymbol.Type; AcceptAndMoveNext(); } // We now have the prefix: (i.e. ' foo="') LocationTagged<string> prefix = Span.GetContent(); if (attributeCanBeConditional) { Span.CodeGenerator = SpanCodeGenerator.Null; // The block code generator will render the prefix Output(SpanKind.Markup); // Read the values while (!EndOfFile && !IsEndOfAttributeValue(quote, CurrentSymbol)) { AttributeValue(quote); } // Capture the suffix LocationTagged<string> suffix = new LocationTagged<string>(String.Empty, CurrentLocation); if (quote != HtmlSymbolType.Unknown && At(quote)) { suffix = CurrentSymbol.GetContent(); AcceptAndMoveNext(); } if (Span.Symbols.Count > 0) { Span.CodeGenerator = SpanCodeGenerator.Null; // Again, block code generator will render the suffix Output(SpanKind.Markup); } // Create the block code generator Context.CurrentBlock.CodeGenerator = new AttributeBlockCodeGenerator( name, prefix, suffix); } else { // Not a "conditional" attribute, so just read the value SkipToAndParseCode(sym => IsEndOfAttributeValue(quote, sym)); if (quote != HtmlSymbolType.Unknown) { Optional(quote); } Output(SpanKind.Markup); } } private void AttributeValue(HtmlSymbolType quote) { SourceLocation prefixStart = CurrentLocation; var prefix = ReadWhile(sym => sym.Type == HtmlSymbolType.WhiteSpace || sym.Type == HtmlSymbolType.NewLine); Accept(prefix); if (At(HtmlSymbolType.Transition)) { SourceLocation valueStart = CurrentLocation; PutCurrentBack(); // Output the prefix but as a null-span. DynamicAttributeBlockCodeGenerator will render it Span.CodeGenerator = SpanCodeGenerator.Null; // Dynamic value, start a new block and set the code generator using (Context.StartBlock(BlockType.Markup)) { Context.CurrentBlock.CodeGenerator = new DynamicAttributeBlockCodeGenerator(prefix.GetContent(prefixStart), valueStart); OtherParserBlock(); } } else if (At(HtmlSymbolType.Text) && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == '~' && NextIs(HtmlSymbolType.Solidus)) { // Virtual Path value SourceLocation valueStart = CurrentLocation; VirtualPath(); Span.CodeGenerator = new LiteralAttributeCodeGenerator( prefix.GetContent(prefixStart), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), valueStart)); } else { // Literal value // 'quote' should be "Unknown" if not quoted and symbols coming from the tokenizer should never have "Unknown" type. var value = ReadWhile(sym => // These three conditions find separators which break the attribute value into portions sym.Type != HtmlSymbolType.WhiteSpace && sym.Type != HtmlSymbolType.NewLine && sym.Type != HtmlSymbolType.Transition && // This condition checks for the end of the attribute value (it repeats some of the checks above but for now that's ok) !IsEndOfAttributeValue(quote, sym)); Accept(value); Span.CodeGenerator = new LiteralAttributeCodeGenerator(prefix.GetContent(prefixStart), value.GetContent(prefixStart)); } Output(SpanKind.Markup); } private bool IsEndOfAttributeValue(HtmlSymbolType quote, HtmlSymbol sym) { return EndOfFile || sym == null || (quote != HtmlSymbolType.Unknown ? sym.Type == quote // If quoted, just wait for the quote : IsUnquotedEndOfAttributeValue(sym)); } private bool IsUnquotedEndOfAttributeValue(HtmlSymbol sym) { // If unquoted, we have a larger set of terminating characters: // http://dev.w3.org/html5/spec/tokenization.html#attribute-value-unquoted-state // Also we need to detect "/" and ">" return sym.Type == HtmlSymbolType.DoubleQuote || sym.Type == HtmlSymbolType.SingleQuote || sym.Type == HtmlSymbolType.OpenAngle || sym.Type == HtmlSymbolType.Equals || (sym.Type == HtmlSymbolType.Solidus && NextIs(HtmlSymbolType.CloseAngle)) || sym.Type == HtmlSymbolType.CloseAngle || sym.Type == HtmlSymbolType.WhiteSpace || sym.Type == HtmlSymbolType.NewLine; } private void VirtualPath() { Assert(HtmlSymbolType.Text); Debug.Assert(CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == '~'); // Parse until a transition symbol, whitespace, newline or quote. We support only a fairly minimal subset of Virtual Paths AcceptUntil(HtmlSymbolType.Transition, HtmlSymbolType.WhiteSpace, HtmlSymbolType.NewLine, HtmlSymbolType.SingleQuote, HtmlSymbolType.DoubleQuote); // Output a Virtual Path span Span.EditHandler.EditorHints = EditorHints.VirtualPath; } private void RecoverToEndOfTag() { // Accept until ">", "/" or "<", but parse code while (!EndOfFile) { SkipToAndParseCode(IsTagRecoveryStopPoint); if (!EndOfFile) { EnsureCurrent(); switch (CurrentSymbol.Type) { case HtmlSymbolType.SingleQuote: case HtmlSymbolType.DoubleQuote: ParseQuoted(); break; case HtmlSymbolType.OpenAngle: // Another "<" means this tag is invalid. case HtmlSymbolType.Solidus: // Empty tag case HtmlSymbolType.CloseAngle: // End of tag return; default: AcceptAndMoveNext(); break; } } } } private void ParseQuoted() { HtmlSymbolType type = CurrentSymbol.Type; AcceptAndMoveNext(); ParseQuoted(type); } private void ParseQuoted(HtmlSymbolType type) { SkipToAndParseCode(type); if (!EndOfFile) { Assert(type); AcceptAndMoveNext(); } } private bool StartTag(Stack<Tuple<HtmlSymbol, SourceLocation>> tags) { // If we're at text, it's the name, otherwise the name is "" HtmlSymbol tagName; if (At(HtmlSymbolType.Text)) { tagName = CurrentSymbol; } else { tagName = new HtmlSymbol(CurrentLocation, String.Empty, HtmlSymbolType.Unknown); } Tuple<HtmlSymbol, SourceLocation> tag = Tuple.Create(tagName, _lastTagStart); if (tags.Count == 0 && String.Equals(tag.Item1.Content, SyntaxConstants.TextTagName, StringComparison.OrdinalIgnoreCase)) { Output(SpanKind.Markup); Span.CodeGenerator = SpanCodeGenerator.Null; Accept(_bufferedOpenAngle); Assert(HtmlSymbolType.Text); AcceptAndMoveNext(); int bookmark = CurrentLocation.AbsoluteIndex; IEnumerable<HtmlSymbol> tokens = ReadWhile(IsSpacingToken(includeNewLines: true)); bool empty = At(HtmlSymbolType.Solidus); if (empty) { Accept(tokens); Assert(HtmlSymbolType.Solidus); AcceptAndMoveNext(); bookmark = CurrentLocation.AbsoluteIndex; tokens = ReadWhile(IsSpacingToken(includeNewLines: true)); } if (!Optional(HtmlSymbolType.CloseAngle)) { Context.Source.Position = bookmark; NextToken(); Context.OnError(tag.Item2, RazorResources.ParseError_TextTagCannotContainAttributes); } else { Accept(tokens); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; } if (!empty) { tags.Push(tag); } Output(SpanKind.Transition); return true; } Accept(_bufferedOpenAngle); Optional(HtmlSymbolType.Text); return RestOfTag(tag, tags); } private bool RestOfTag(Tuple<HtmlSymbol, SourceLocation> tag, Stack<Tuple<HtmlSymbol, SourceLocation>> tags) { TagContent(); // We are now at a possible end of the tag // Found '<', so we just abort this tag. if (At(HtmlSymbolType.OpenAngle)) { return false; } bool isEmpty = At(HtmlSymbolType.Solidus); // Found a solidus, so don't accept it but DON'T push the tag to the stack if (isEmpty) { AcceptAndMoveNext(); } // Check for the '>' to determine if the tag is finished bool seenClose = Optional(HtmlSymbolType.CloseAngle); if (!seenClose) { Context.OnError(tag.Item2, string.Format(RazorResources.ParseError_UnfinishedTag,tag.Item1.Content)); } else { if (!isEmpty) { // Is this a void element? string tagName = tag.Item1.Content.Trim(); if (VoidElements.Contains(tagName)) { // Technically, void elements like "meta" are not allowed to have end tags. Just in case they do, // we need to look ahead at the next set of tokens. If we see "<", "/", tag name, accept it and the ">" following it // Place a bookmark int bookmark = CurrentLocation.AbsoluteIndex; // Skip whitespace IEnumerable<HtmlSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true)); // Open Angle if (At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus)) { HtmlSymbol openAngle = CurrentSymbol; NextToken(); Assert(HtmlSymbolType.Solidus); HtmlSymbol solidus = CurrentSymbol; NextToken(); if (At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase)) { // Accept up to here Accept(ws); Accept(openAngle); Accept(solidus); AcceptAndMoveNext(); // Accept to '>', '<' or EOF AcceptUntil(HtmlSymbolType.CloseAngle, HtmlSymbolType.OpenAngle); // Accept the '>' if we saw it. And if we do see it, we're complete return Optional(HtmlSymbolType.CloseAngle); } // At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase) } // At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus) // Go back to the bookmark and just finish this tag at the close angle Context.Source.Position = bookmark; NextToken(); } else if (String.Equals(tagName, "script", StringComparison.OrdinalIgnoreCase)) { SkipToEndScriptAndParseCode(); } else { // Push the tag on to the stack tags.Push(tag); } } } return seenClose; } private void SkipToEndScriptAndParseCode() { // Special case for <script>: Skip to end of script tag and parse code bool seenEndScript = false; while (!seenEndScript && !EndOfFile) { SkipToAndParseCode(HtmlSymbolType.OpenAngle); SourceLocation tagStart = CurrentLocation; AcceptAndMoveNext(); AcceptWhile(HtmlSymbolType.WhiteSpace); if (Optional(HtmlSymbolType.Solidus)) { AcceptWhile(HtmlSymbolType.WhiteSpace); if (At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, "script", StringComparison.OrdinalIgnoreCase)) { // </script! SkipToAndParseCode(HtmlSymbolType.CloseAngle); if (!Optional(HtmlSymbolType.CloseAngle)) { Context.OnError(tagStart, string.Format(RazorResources.ParseError_UnfinishedTag, "script")); } seenEndScript = true; } } } } private bool AcceptUntilAll(params HtmlSymbolType[] endSequence) { while (!EndOfFile) { SkipToAndParseCode(endSequence[0]); if (AcceptAll(endSequence)) { return true; } } Debug.Assert(EndOfFile); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; return false; } private bool RemoveTag(Stack<Tuple<HtmlSymbol, SourceLocation>> tags, string tagName, SourceLocation tagStart) { Tuple<HtmlSymbol, SourceLocation> currentTag = null; while (tags.Count > 0) { currentTag = tags.Pop(); if (String.Equals(tagName, currentTag.Item1.Content, StringComparison.OrdinalIgnoreCase)) { // Matched the tag return true; } } if (currentTag != null) { Context.OnError(currentTag.Item2, string.Format(RazorResources.ParseError_MissingEndTag, currentTag.Item1.Content)); } else { Context.OnError(tagStart, string.Format(RazorResources.ParseError_UnexpectedEndTag,tagName)); } return false; } private void EndTagBlock(Stack<Tuple<HtmlSymbol, SourceLocation>> tags, bool complete) { if (tags.Count > 0) { // Ended because of EOF, not matching close tag. Throw error for last tag while (tags.Count > 1) { tags.Pop(); } Tuple<HtmlSymbol, SourceLocation> tag = tags.Pop(); Context.OnError(tag.Item2, string.Format(RazorResources.ParseError_MissingEndTag, tag.Item1.Content)); } else if (complete) { Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; } tags.Clear(); if (!Context.DesignTimeMode) { AcceptWhile(HtmlSymbolType.WhiteSpace); if (!EndOfFile && CurrentSymbol.Type == HtmlSymbolType.NewLine) { AcceptAndMoveNext(); } } else if (Span.EditHandler.AcceptedCharacters == AcceptedCharacters.Any) { AcceptWhile(HtmlSymbolType.WhiteSpace); Optional(HtmlSymbolType.NewLine); } PutCurrentBack(); if (!complete) { AddMarkerSymbolIfNecessary(); } Output(SpanKind.Markup); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Tests.Common { /// <summary> /// Utility functions for carrying out user inventory tests. /// </summary> public static class UserInventoryHelpers { public static readonly string PATH_DELIMITER = "/"; /// <summary> /// Add an existing scene object as an item in the user's inventory. /// </summary> /// <remarks> /// Will be added to the system Objects folder. /// </remarks> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID); } /// <summary> /// Add an existing scene object as an item in the user's inventory at the given path. /// </summary> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail, string path) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID, path); } /// <summary> /// Adds the given item to the existing system folder for its type (e.g. an object will go in the "Objects" /// folder). /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId) { return AddInventoryItem( scene, itemName, itemId, itemType, asset, userId, scene.InventoryService.GetFolderForType(userId, (AssetType)asset.Type).Name); } /// <summary> /// Adds the given item to an inventory folder /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <param name="path">Existing inventory path at which to add.</param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId, string path) { scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); item.Name = itemName; item.AssetID = asset.FullID; item.ID = itemId; item.Owner = userId; item.AssetType = asset.Type; item.InvType = (int)itemType; InventoryFolderBase folder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, path)[0]; item.Folder = folder.ID; scene.AddInventoryItem(item); return item; } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem(Scene scene, string itemName, UUID userId) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, InventoryType.Notecard); } /// <summary> /// Creates an item of the given type with an accompanying asset. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID userId, InventoryType type) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, type); } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="assetId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID itemId, UUID assetId, UUID userId, InventoryType itemType) { AssetBase asset = null; if (itemType == InventoryType.Notecard) { asset = AssetHelpers.CreateNotecardAsset(); asset.CreatorID = userId.ToString(); } else if (itemType == InventoryType.Object) { asset = AssetHelpers.CreateAsset(assetId, SceneHelpers.CreateSceneObject(1, userId)); } else { throw new Exception(string.Format("Inventory type {0} not supported", itemType)); } return AddInventoryItem(scene, itemName, itemId, itemType, asset, userId); } /// <summary> /// Create inventory folders starting from the user's root folder. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"> /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID userId, string path, bool useExistingFolders) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; return CreateInventoryFolder(inventoryService, rootFolder, path, useExistingFolders); } /// <summary> /// Create inventory folders starting from a given parent folder /// </summary> /// <remarks> /// If any stem of the path names folders that already exist then these are not recreated. This includes the /// final folder. /// TODO: May need to make it an option to create duplicate folders. /// </remarks> /// <param name="inventoryService"></param> /// <param name="parentFolder"></param> /// <param name="path"> /// The folder to create. /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, InventoryFolderBase parentFolder, string path, bool useExistingFolders) { string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); InventoryFolderBase folder = null; if (useExistingFolders) folder = InventoryArchiveUtils.FindFolderByPath(inventoryService, parentFolder, components[0]); if (folder == null) { // Console.WriteLine("Creating folder {0} at {1}", components[0], parentFolder.Name); folder = new InventoryFolderBase( UUID.Random(), components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0); inventoryService.AddFolder(folder); } // else // { // Console.WriteLine("Found existing folder {0}", folder.Name); // } if (components.Length > 1) return CreateInventoryFolder(inventoryService, folder, components[1], useExistingFolders); else return folder; } /// <summary> /// Get the inventory folder that matches the path name. If there are multiple folders then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no folder matching the path was found</returns> public static InventoryFolderBase GetInventoryFolder(IInventoryService inventoryService, UUID userId, string path) { List<InventoryFolderBase> folders = GetInventoryFolders(inventoryService, userId, path); if (folders.Count != 0) return folders[0]; else return null; } /// <summary> /// Get the inventory folders that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching folders were found</returns> public static List<InventoryFolderBase> GetInventoryFolders(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindFoldersByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory item that matches the path name. If there are multiple items then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no item matching the path was found</returns> public static InventoryItemBase GetInventoryItem(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory items that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching items were found.</returns> public static List<InventoryItemBase> GetInventoryItems(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemsByPath(inventoryService, userId, path); } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using OpenHome.Net.Core; namespace OpenHome.Net.Device.Providers { public interface IDvProviderLinnCoUkLipSync1 : IDisposable { /// <summary> /// Set the value of the Delay property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyDelay(uint aValue); /// <summary> /// Get a copy of the value of the Delay property /// </summary> /// <returns>Value of the Delay property.</param> uint PropertyDelay(); /// <summary> /// Set the value of the DelayMinimum property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyDelayMinimum(uint aValue); /// <summary> /// Get a copy of the value of the DelayMinimum property /// </summary> /// <returns>Value of the DelayMinimum property.</param> uint PropertyDelayMinimum(); /// <summary> /// Set the value of the DelayMaximum property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyDelayMaximum(uint aValue); /// <summary> /// Get a copy of the value of the DelayMaximum property /// </summary> /// <returns>Value of the DelayMaximum property.</param> uint PropertyDelayMaximum(); } /// <summary> /// Provider for the linn.co.uk:LipSync:1 UPnP service /// </summary> public class DvProviderLinnCoUkLipSync1 : DvProvider, IDisposable, IDvProviderLinnCoUkLipSync1 { private GCHandle iGch; private ActionDelegate iDelegateSetDelay; private ActionDelegate iDelegateDelay; private ActionDelegate iDelegateDelayMinimum; private ActionDelegate iDelegateDelayMaximum; private PropertyUint iPropertyDelay; private PropertyUint iPropertyDelayMinimum; private PropertyUint iPropertyDelayMaximum; /// <summary> /// Constructor /// </summary> /// <param name="aDevice">Device which owns this provider</param> protected DvProviderLinnCoUkLipSync1(DvDevice aDevice) : base(aDevice, "linn.co.uk", "LipSync", 1) { iGch = GCHandle.Alloc(this); } /// <summary> /// Enable the Delay property. /// </summary> public void EnablePropertyDelay() { iPropertyDelay = new PropertyUint(new ParameterUint("Delay")); AddProperty(iPropertyDelay); } /// <summary> /// Enable the DelayMinimum property. /// </summary> public void EnablePropertyDelayMinimum() { iPropertyDelayMinimum = new PropertyUint(new ParameterUint("DelayMinimum")); AddProperty(iPropertyDelayMinimum); } /// <summary> /// Enable the DelayMaximum property. /// </summary> public void EnablePropertyDelayMaximum() { iPropertyDelayMaximum = new PropertyUint(new ParameterUint("DelayMaximum")); AddProperty(iPropertyDelayMaximum); } /// <summary> /// Set the value of the Delay property /// </summary> /// <remarks>Can only be called if EnablePropertyDelay has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyDelay(uint aValue) { if (iPropertyDelay == null) throw new PropertyDisabledError(); return SetPropertyUint(iPropertyDelay, aValue); } /// <summary> /// Get a copy of the value of the Delay property /// </summary> /// <remarks>Can only be called if EnablePropertyDelay has previously been called.</remarks> /// <returns>Value of the Delay property.</returns> public uint PropertyDelay() { if (iPropertyDelay == null) throw new PropertyDisabledError(); return iPropertyDelay.Value(); } /// <summary> /// Set the value of the DelayMinimum property /// </summary> /// <remarks>Can only be called if EnablePropertyDelayMinimum has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyDelayMinimum(uint aValue) { if (iPropertyDelayMinimum == null) throw new PropertyDisabledError(); return SetPropertyUint(iPropertyDelayMinimum, aValue); } /// <summary> /// Get a copy of the value of the DelayMinimum property /// </summary> /// <remarks>Can only be called if EnablePropertyDelayMinimum has previously been called.</remarks> /// <returns>Value of the DelayMinimum property.</returns> public uint PropertyDelayMinimum() { if (iPropertyDelayMinimum == null) throw new PropertyDisabledError(); return iPropertyDelayMinimum.Value(); } /// <summary> /// Set the value of the DelayMaximum property /// </summary> /// <remarks>Can only be called if EnablePropertyDelayMaximum has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyDelayMaximum(uint aValue) { if (iPropertyDelayMaximum == null) throw new PropertyDisabledError(); return SetPropertyUint(iPropertyDelayMaximum, aValue); } /// <summary> /// Get a copy of the value of the DelayMaximum property /// </summary> /// <remarks>Can only be called if EnablePropertyDelayMaximum has previously been called.</remarks> /// <returns>Value of the DelayMaximum property.</returns> public uint PropertyDelayMaximum() { if (iPropertyDelayMaximum == null) throw new PropertyDisabledError(); return iPropertyDelayMaximum.Value(); } /// <summary> /// Signal that the action SetDelay is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SetDelay must be overridden if this is called.</remarks> protected void EnableActionSetDelay() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetDelay"); action.AddInputParameter(new ParameterRelated("Delay", iPropertyDelay)); iDelegateSetDelay = new ActionDelegate(DoSetDelay); EnableAction(action, iDelegateSetDelay, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action Delay is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// Delay must be overridden if this is called.</remarks> protected void EnableActionDelay() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Delay"); action.AddOutputParameter(new ParameterRelated("Delay", iPropertyDelay)); iDelegateDelay = new ActionDelegate(DoDelay); EnableAction(action, iDelegateDelay, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action DelayMinimum is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// DelayMinimum must be overridden if this is called.</remarks> protected void EnableActionDelayMinimum() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DelayMinimum"); action.AddOutputParameter(new ParameterRelated("Min", iPropertyDelayMinimum)); iDelegateDelayMinimum = new ActionDelegate(DoDelayMinimum); EnableAction(action, iDelegateDelayMinimum, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action DelayMaximum is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// DelayMaximum must be overridden if this is called.</remarks> protected void EnableActionDelayMaximum() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DelayMaximum"); action.AddOutputParameter(new ParameterRelated("Max", iPropertyDelayMaximum)); iDelegateDelayMaximum = new ActionDelegate(DoDelayMaximum); EnableAction(action, iDelegateDelayMaximum, GCHandle.ToIntPtr(iGch)); } /// <summary> /// SetDelay action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SetDelay action for the owning device. /// /// Must be implemented iff EnableActionSetDelay was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDelay"></param> protected virtual void SetDelay(IDvInvocation aInvocation, uint aDelay) { throw (new ActionDisabledError()); } /// <summary> /// Delay action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// Delay action for the owning device. /// /// Must be implemented iff EnableActionDelay was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDelay"></param> protected virtual void Delay(IDvInvocation aInvocation, out uint aDelay) { throw (new ActionDisabledError()); } /// <summary> /// DelayMinimum action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// DelayMinimum action for the owning device. /// /// Must be implemented iff EnableActionDelayMinimum was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aMin"></param> protected virtual void DelayMinimum(IDvInvocation aInvocation, out uint aMin) { throw (new ActionDisabledError()); } /// <summary> /// DelayMaximum action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// DelayMaximum action for the owning device. /// /// Must be implemented iff EnableActionDelayMaximum was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aMax"></param> protected virtual void DelayMaximum(IDvInvocation aInvocation, out uint aMax) { throw (new ActionDisabledError()); } private static int DoSetDelay(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkLipSync1 self = (DvProviderLinnCoUkLipSync1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint delay; try { invocation.ReadStart(); delay = invocation.ReadUint("Delay"); invocation.ReadEnd(); self.SetDelay(invocation, delay); } catch (ActionError e) { invocation.ReportActionError(e, "SetDelay"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetDelay" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetDelay" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetDelay" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoDelay(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkLipSync1 self = (DvProviderLinnCoUkLipSync1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint delay; try { invocation.ReadStart(); invocation.ReadEnd(); self.Delay(invocation, out delay); } catch (ActionError e) { invocation.ReportActionError(e, "Delay"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Delay" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Delay" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteUint("Delay", delay); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Delay" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoDelayMinimum(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkLipSync1 self = (DvProviderLinnCoUkLipSync1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint min; try { invocation.ReadStart(); invocation.ReadEnd(); self.DelayMinimum(invocation, out min); } catch (ActionError e) { invocation.ReportActionError(e, "DelayMinimum"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DelayMinimum" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DelayMinimum" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteUint("Min", min); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DelayMinimum" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoDelayMaximum(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderLinnCoUkLipSync1 self = (DvProviderLinnCoUkLipSync1)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); uint max; try { invocation.ReadStart(); invocation.ReadEnd(); self.DelayMaximum(invocation, out max); } catch (ActionError e) { invocation.ReportActionError(e, "DelayMaximum"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DelayMaximum" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DelayMaximum" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteUint("Max", max); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DelayMaximum" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public virtual void Dispose() { if (DisposeProvider()) iGch.Free(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime.Configuration; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.Messaging; using Orleans.Runtime.Placement; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Versions.Compatibility; using Orleans.Serialization; using Orleans.Versions.Compatibility; namespace Orleans.Runtime { internal class Dispatcher { internal ISiloMessageCenter Transport { get; } private readonly OrleansTaskScheduler scheduler; private readonly Catalog catalog; private readonly Logger logger; private readonly ClusterConfiguration config; private readonly PlacementDirectorsManager placementDirectorsManager; private readonly ILocalGrainDirectory localGrainDirectory; private readonly MessageFactory messagefactory; private readonly SerializationManager serializationManager; private readonly CompatibilityDirectorManager compatibilityDirectorManager; private readonly double rejectionInjectionRate; private readonly bool errorInjection; private readonly double errorInjectionRate; private readonly SafeRandom random; internal Dispatcher( OrleansTaskScheduler scheduler, ISiloMessageCenter transport, Catalog catalog, ClusterConfiguration config, PlacementDirectorsManager placementDirectorsManager, ILocalGrainDirectory localGrainDirectory, MessageFactory messagefactory, SerializationManager serializationManager, CompatibilityDirectorManager compatibilityDirectorManager) { this.scheduler = scheduler; this.catalog = catalog; Transport = transport; this.config = config; this.placementDirectorsManager = placementDirectorsManager; this.localGrainDirectory = localGrainDirectory; this.messagefactory = messagefactory; this.serializationManager = serializationManager; this.compatibilityDirectorManager = compatibilityDirectorManager; logger = LogManager.GetLogger("Dispatcher", LoggerType.Runtime); rejectionInjectionRate = config.Globals.RejectionInjectionRate; double messageLossInjectionRate = config.Globals.MessageLossInjectionRate; errorInjection = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d; errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate; random = new SafeRandom(); } #region Receive path /// <summary> /// Receive a new message: /// - validate order constraints, queue (or possibly redirect) if out of order /// - validate transactions constraints /// - invoke handler if ready, otherwise enqueue for later invocation /// </summary> /// <param name="message"></param> public void ReceiveMessage(Message message) { MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message); // Don't process messages that have already timed out if (message.IsExpired) { logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired"); message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch); return; } // check if its targeted at a new activation if (message.TargetGrain.IsSystemTarget) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target."); throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message); } if (errorInjection && ShouldInjectError(message)) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingRejection, "Injecting a rejection"); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ErrorInjection"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, null, "Injected rejection"); return; } try { Task ignore; ActivationData target = catalog.GetOrCreateActivation( message.TargetAddress, message.IsNewPlacement, message.NewGrainType, String.IsNullOrEmpty(message.GenericGrainType) ? null : message.GenericGrainType, message.RequestContextData, out ignore); if (ignore != null) { ignore.Ignore(); } if (message.Direction == Message.Directions.Response) { ReceiveResponse(message, target); } else // Request or OneWay { if (target.State == ActivationState.Valid) { catalog.ActivationCollector.TryRescheduleCollection(target); } // Silo is always capable to accept a new request. It's up to the activation to handle its internal state. // If activation is shutting down, it will queue and later forward this request. ReceiveRequest(message, target); } } catch (Exception ex) { try { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation"); var nea = ex as Catalog.NonExistentActivationException; if (nea == null) { var str = String.Format("Error creating activation for {0}. Message {1}", message.NewGrainType, message); logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex); throw new OrleansException(str, ex); } if (nea.IsStatelessWorker) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate StatelessWorker NonExistentActivation for message {0}", message), ex); } else { logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate NonExistentActivation for message {0}", message), ex); } ActivationAddress nonExistentActivation = nea.NonExistentActivation; if (message.Direction != Message.Directions.Response) { // Un-register the target activation so we don't keep getting spurious messages. // The time delay (one minute, as of this writing) is to handle the unlikely but possible race where // this request snuck ahead of another request, with new placement requested, for the same activation. // If the activation registration request from the new placement somehow sneaks ahead of this un-registration, // we want to make sure that we don't un-register the activation we just created. // We would add a counter here, except that there's already a counter for this in the Catalog. // Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context var origin = message.SendingSilo; scheduler.QueueWorkItem(new ClosureWorkItem( // don't use message.TargetAddress, cause it may have been removed from the headers by this time! async () => { try { await this.localGrainDirectory.UnregisterAfterNonexistingActivation( nonExistentActivation, origin); } catch (Exception exc) { logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct, String.Format("Failed to un-register NonExistentActivation {0}", nonExistentActivation), exc); } }, () => "LocalGrainDirectory.UnregisterAfterNonexistingActivation"), catalog.SchedulingContext); ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation"); } else { logger.Warn( ErrorCode.Dispatcher_NoTargetActivation, nonExistentActivation.Silo.IsClient ? "No target client {0} for response message: {1}. It's likely that the client recently disconnected." : "No target activation {0} for response message: {1}", nonExistentActivation, message); this.localGrainDirectory.InvalidateCacheEntry(nonExistentActivation); } } catch (Exception exc) { // Unable to create activation for this request - reject message RejectMessage(message, Message.RejectionTypes.Transient, exc); } } } public void RejectMessage( Message message, Message.RejectionTypes rejectType, Exception exc, string rejectInfo = null) { if (message.Direction == Message.Directions.Request) { var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString()); MessagingStatisticsGroup.OnRejectedMessage(message); Message rejection = this.messagefactory.CreateRejectionResponse(message, rejectType, str, exc as OrleansException); SendRejectionMessage(rejection); } else { logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection, "Discarding {0} rejection for message {1}. Exc = {2}", Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message); } } internal void SendRejectionMessage(Message rejection) { if (rejection.Result == Message.ResponseTypes.Rejection) { Transport.SendMessage(rejection); rejection.ReleaseBodyAndHeaderBuffers(); } else { throw new InvalidOperationException( "Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection."); } } private void ReceiveResponse(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation, "Response received for invalid activation {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid"); return; } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); if (Transport.TryDeliverToProxy(message)) return; this.catalog.RuntimeClient.ReceiveResponse(message); } } /// <summary> /// Check if we can locally accept this message. /// Redirects if it can't be accepted. /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void ReceiveRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "ReceiveRequest"); } else if (!ActivationMayAcceptRequest(targetActivation, message)) { // Check for deadlock before Enqueueing. if (config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget) { try { CheckDeadlock(message); } catch (DeadlockException exc) { // Record that this message is no longer flowing through the system MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock"); logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock, "Detected Application Deadlock: {0}", exc.Message); // We want to send DeadlockException back as an application exception, rather than as a system rejection. SendResponse(message, Response.ExceptionResponse(exc)); return; } } EnqueueRequest(message, targetActivation); } else { HandleIncomingRequest(message, targetActivation); } } } /// <summary> /// Determine if the activation is able to currently accept the given message /// - always accept responses /// For other messages, require that: /// - activation is properly initialized /// - the message would not cause a reentrancy conflict /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming) { if (targetActivation.State != ActivationState.Valid) return false; if (!targetActivation.IsCurrentlyExecuting) return true; return CanInterleave(targetActivation, incoming); } /// <summary> /// Whether an incoming message can interleave /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> public bool CanInterleave(ActivationData targetActivation, Message incoming) { bool canInterleave = catalog.CanInterleave(targetActivation.ActivationId, incoming) || incoming.IsAlwaysInterleave || targetActivation.Running == null || (targetActivation.Running.IsReadOnly && incoming.IsReadOnly); return canInterleave; } /// <summary> /// Check if the current message will cause deadlock. /// Throw DeadlockException if yes. /// </summary> /// <param name="message">Message to analyze</param> private void CheckDeadlock(Message message) { var requestContext = message.RequestContextData; object obj; if (requestContext == null || !requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) || obj == null) return; // first call in a chain var prevChain = ((IList)obj); ActivationId nextActivationId = message.TargetActivation; // check if the target activation already appears in the call chain. foreach (object invocationObj in prevChain) { var prevId = ((RequestInvocationHistory)invocationObj).ActivationId; if (!prevId.Equals(nextActivationId) || catalog.CanInterleave(nextActivationId, message)) continue; var newChain = new List<RequestInvocationHistory>(); newChain.AddRange(prevChain.Cast<RequestInvocationHistory>()); newChain.Add(new RequestInvocationHistory(message)); throw new DeadlockException(newChain); } } /// <summary> /// Handle an incoming message and queue/invoke appropriate handler /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> public void HandleIncomingRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.Grain.IsGrain && message.IsUsingInterfaceVersions) { var request = ((InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager)); var compatibilityDirector = compatibilityDirectorManager.GetDirector(request.InterfaceId); var currentVersion = catalog.GrainTypeManager.GetLocalSupportedVersion(request.InterfaceId); if (!compatibilityDirector.IsCompatible(request.InterfaceVersion, currentVersion)) catalog.DeactivateActivationOnIdle(targetActivation); } if (targetActivation.State == ActivationState.Invalid || targetActivation.State == ActivationState.Deactivating) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest"); return; } // Now we can actually scheduler processing of this request targetActivation.RecordRunning(message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, this), targetActivation.SchedulingContext); } } /// <summary> /// Enqueue message for local handling after transaction completes /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void EnqueueRequest(Message message, ActivationData targetActivation) { var overloadException = targetActivation.CheckOverloaded(logger); if (overloadException != null) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2"); RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation); return; } switch (targetActivation.EnqueueMessage(message)) { case ActivationData.EnqueueMessageResult.Success: // Great, nothing to do break; case ActivationData.EnqueueMessageResult.ErrorInvalidActivation: ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest"); break; case ActivationData.EnqueueMessageResult.ErrorStuckActivation: // Avoid any new call to this activation catalog.DeactivateStuckActivation(targetActivation); ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest - blocked grain"); break; default: throw new ArgumentOutOfRangeException(); } // Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest. #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_EnqueueMessage, "EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus()); #endif } internal void ProcessRequestToInvalidActivation( Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { this.localGrainDirectory.InvalidateCacheEntry(oldAddress); } // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. scheduler.QueueWorkItem(new ClosureWorkItem( () => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)), catalog.SchedulingContext); } internal void ProcessRequestsToInvalidActivation( List<Message> messages, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { this.localGrainDirectory.InvalidateCacheEntry(oldAddress); } logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests, String.Format("Forwarding {0} requests to old address {1} after {2}.", messages.Count, oldAddress, failedOperation)); // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. scheduler.QueueWorkItem(new ClosureWorkItem( () => { foreach (var message in messages) { TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc); } } ), catalog.SchedulingContext); } internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { bool forwardingSucceded = true; try { logger.Info(ErrorCode.Messaging_Dispatcher_TryForward, String.Format("Trying to forward after {0}, ForwardCount = {1}. Message {2}.", failedOperation, message.ForwardCount, message)); // if this message is from a different cluster and hit a non-existing activation // in this cluster (which can happen due to stale cache or directory states) // we forward it back to the original silo it came from in the original cluster, // and target it to a fictional activation that is guaranteed to not exist. // This ensures that the GSI protocol creates a new instance there instead of here. if (forwardingAddress == null && message.TargetSilo != message.SendingSilo && !this.localGrainDirectory.IsSiloInCluster(message.SendingSilo)) { message.IsReturnedFromRemoteCluster = true; // marks message to force invalidation of stale directory entry forwardingAddress = ActivationAddress.NewActivationAddress(message.SendingSilo, message.TargetGrain); logger.Info(ErrorCode.Messaging_Dispatcher_ReturnToOriginCluster, String.Format("Forwarding back to origin cluster, to fictional activation {0}", message)); } MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message); if (oldAddress != null) { message.AddToCacheInvalidationHeader(oldAddress); } forwardingSucceded = this.TryForwardMessage(message, forwardingAddress); } catch (Exception exc2) { forwardingSucceded = false; exc = exc2; } finally { if (!forwardingSucceded) { var str = String.Format("Forwarding failed: tried to forward message {0} for {1} times after {2} to invalid activation. Rejecting now.", message, message.ForwardCount, failedOperation); logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc); RejectMessage(message, Message.RejectionTypes.Transient, exc, str); } } } /// <summary> /// Reroute a message coming in through a gateway /// </summary> /// <param name="message"></param> internal void RerouteMessage(Message message) { ResendMessageImpl(message); } internal bool TryResendMessage(Message message) { if (!message.MayResend(this.config.Globals)) return false; message.ResendCount = message.ResendCount + 1; MessagingProcessingStatisticsGroup.OnIgcMessageResend(message); ResendMessageImpl(message); return true; } internal bool TryForwardMessage(Message message, ActivationAddress forwardingAddress) { if (!message.MayForward(this.config.Globals)) return false; message.ForwardCount = message.ForwardCount + 1; MessagingProcessingStatisticsGroup.OnIgcMessageForwared(message); ResendMessageImpl(message, forwardingAddress); return true; } private void ResendMessageImpl(Message message, ActivationAddress forwardingAddress = null) { if (logger.IsVerbose) logger.Verbose("Resend {0}", message); message.TargetHistory = message.GetTargetHistory(); if (message.TargetGrain.IsSystemTarget) { this.SendSystemTargetMessage(message); } else if (forwardingAddress != null) { message.TargetAddress = forwardingAddress; message.IsNewPlacement = false; this.Transport.SendMessage(message); } else { message.TargetActivation = null; message.TargetSilo = null; message.ClearTargetAddress(); this.SendMessage(message); } } #endregion #region Send path /// <summary> /// Send an outgoing message /// - may buffer for transaction completion / commit if it ends a transaction /// - choose target placement address, maintaining send order /// - add ordering info and maintain send order /// /// </summary> /// <param name="message"></param> /// <param name="sendingActivation"></param> public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null) { try { await AddressMessage(message); TransportMessage(message); } catch (Exception ex) { if (ShouldLogError(ex)) { logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed, String.Format("SelectTarget failed with {0}", ex.Message), ex); } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex); } } private bool ShouldLogError(Exception ex) { return !(ex.GetBaseException() is KeyNotFoundException) && !(ex.GetBaseException() is ClientNotAvailableException); } // this is a compatibility method for portions of the code base that don't use // async/await yet, which is almost everything. there's no liability to discarding the // Task returned by AsyncSendMessage() internal void SendMessage(Message message, ActivationData sendingActivation = null) { AsyncSendMessage(message, sendingActivation).Ignore(); } /// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private async Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) return; // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var request = message.IsUsingInterfaceVersions ? message.GetDeserializedBody(this.serializationManager) as InvokeMethodRequest : null; var target = new PlacementTarget(message.TargetGrain, request?.InterfaceId ?? 0, request?.InterfaceVersion ?? 0); var placementResult = await this.placementDirectorsManager.SelectOrAddActivation( message.SendingAddress, target, this.catalog, strategy); if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient) { logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message)); throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain)); } message.SetTargetPlacement(placementResult); if (placementResult.IsNewPlacement) { CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment(); } if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message); } internal void SendResponse(Message request, Response response) { // create the response var message = this.messagefactory.CreateResponseMessage(request); message.BodyObject = response; if (message.TargetGrain.IsSystemTarget) { SendSystemTargetMessage(message); } else { TransportMessage(message); } } internal void SendSystemTargetMessage(Message message) { message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; if (message.TargetSilo == null) { message.TargetSilo = Transport.MyAddress; } if (message.TargetActivation == null) { message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo); } TransportMessage(message); } /// <summary> /// Directly send a message to the transport without processing /// </summary> /// <param name="message"></param> public void TransportMessage(Message message) { if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message); Transport.SendMessage(message); } #endregion #region Execution /// <summary> /// Invoked when an activation has finished a transaction and may be ready for additional transactions /// </summary> /// <param name="activation">The activation that has just completed processing this message</param> /// <param name="message">The message that has just completed processing. /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param> internal void OnActivationCompletedRequest(ActivationData activation, Message message) { lock (activation) { #if DEBUG // This is a hot code path, so using #if to remove diags from Release version if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting, "OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif activation.ResetRunning(message); // ensure inactive callbacks get run even with transactions disabled if (!activation.IsCurrentlyExecuting) activation.RunOnInactive(); // Run message pump to see if there is a new request arrived to be processed RunMessagePump(activation); } } internal void RunMessagePump(ActivationData activation) { // Note: this method must be called while holding lock (activation) #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting, "RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif // don't run any messages if activation is not ready or deactivating if (activation.State != ActivationState.Valid) return; bool runLoop; do { runLoop = false; var nextMessage = activation.PeekNextWaitingMessage(); if (nextMessage == null) continue; if (!ActivationMayAcceptRequest(activation, nextMessage)) continue; activation.DequeueNextWaitingMessage(); // we might be over-writing an already running read only request. HandleIncomingRequest(nextMessage, activation); runLoop = true; } while (runLoop); } private bool ShouldInjectError(Message message) { if (!errorInjection || message.Direction != Message.Directions.Request) return false; double r = random.NextDouble() * 100; if (!(r < errorInjectionRate)) return false; if (r < rejectionInjectionRate) { return true; } if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingMessageLoss, "Injecting a message loss"); // else do nothing and intentionally drop message on the floor to inject a message loss return true; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Versions; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { internal abstract partial class AbstractDesignerAttributeIncrementalAnalyzer : ForegroundThreadAffinitizedObject { private readonly IForegroundNotificationService _notificationService; private readonly IServiceProvider _serviceProvider; private readonly DesignerAttributeState _state; private readonly IAsynchronousOperationListener _listener; /// <summary> /// cache designer from UI thread /// /// access this field through <see cref="GetDesignerFromForegroundThread"/> /// </summary> private IVSMDDesignerService _dotNotAccessDirectlyDesigner; public AbstractDesignerAttributeIncrementalAnalyzer( IServiceProvider serviceProvider, IForegroundNotificationService notificationService, IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _serviceProvider = serviceProvider; Contract.ThrowIfNull(_serviceProvider); _notificationService = notificationService; _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.DesignerAttribute); _state = new DesignerAttributeState(); } protected abstract bool ProcessOnlyFirstTypeDefined(); protected abstract IEnumerable<SyntaxNode> GetAllTopLevelTypeDefined(SyntaxNode root); protected abstract bool HasAttributesOrBaseTypeOrIsPartial(SyntaxNode typeNode); public System.Threading.Tasks.Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { _state.Remove(document.Id); return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, designerAttributeArgument: null), cancellationToken); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } public async System.Threading.Tasks.Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.IsFromPrimaryBranch()); cancellationToken.ThrowIfCancellationRequested(); if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.DesignerAttributes)) { return; } // use tree version so that things like compiler option changes are considered var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData != null) { // check whether we can use the data as it is (can happen when re-using persisted data from previous VS session) if (CheckVersions(document, textVersion, projectVersion, semanticVersion, existingData)) { RegisterDesignerAttribute(document, existingData.DesignerAttributeArgument); return; } } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); // Delay getting any of these until we need them, but hold on to them once we have them. string designerAttributeArgument = null; Compilation compilation = null; INamedTypeSymbol designerAttribute = null; SemanticModel model = null; var documentHasError = false; // get type defined in current tree foreach (var typeNode in GetAllTopLevelTypeDefined(root)) { cancellationToken.ThrowIfCancellationRequested(); if (HasAttributesOrBaseTypeOrIsPartial(typeNode)) { if (designerAttribute == null) { if (compilation == null) { compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); } designerAttribute = compilation.DesignerCategoryAttributeType(); if (designerAttribute == null) { // The DesignerCategoryAttribute doesn't exist. // no idea on design attribute status, just leave things as it is. _state.Remove(document.Id); return; } } if (model == null) { model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } var definedType = model.GetDeclaredSymbol(typeNode, cancellationToken) as INamedTypeSymbol; if (definedType == null) { continue; } // walk up type chain foreach (var type in definedType.GetBaseTypesAndThis()) { if (type.IsErrorType()) { documentHasError = true; continue; } cancellationToken.ThrowIfCancellationRequested(); // if it has designer attribute, set it var attribute = type.GetAttributes().Where(d => designerAttribute.Equals(d.AttributeClass)).FirstOrDefault(); if (attribute != null && attribute.ConstructorArguments.Length == 1) { designerAttributeArgument = GetArgumentString(attribute.ConstructorArguments[0]); await RegisterDesignerAttributeAndSaveStateAsync(document, textVersion, semanticVersion, designerAttributeArgument, cancellationToken).ConfigureAwait(false); return; } } } // check only first type if (ProcessOnlyFirstTypeDefined()) { break; } } // we checked all types in the document, but couldn't find designer attribute, but we can't say this document doesn't have designer attribute // if the document also contains some errors. var designerAttributeArgumentOpt = documentHasError ? new Optional<string>() : new Optional<string>(designerAttributeArgument); await RegisterDesignerAttributeAndSaveStateAsync(document, textVersion, semanticVersion, designerAttributeArgumentOpt, cancellationToken).ConfigureAwait(false); } private bool CheckVersions( Document document, VersionStamp textVersion, VersionStamp dependentProjectVersion, VersionStamp dependentSemanticVersion, Data existingData) { // first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether // we can use it cross-session. return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(dependentProjectVersion, dependentSemanticVersion, existingData.SemanticVersion); } private static string GetArgumentString(TypedConstant argument) { if (argument.Type == null || argument.Type.SpecialType != SpecialType.System_String || argument.IsNull) { return null; } return ((string)argument.Value).Trim(); } private async System.Threading.Tasks.Task RegisterDesignerAttributeAndSaveStateAsync( Document document, VersionStamp textVersion, VersionStamp semanticVersion, Optional<string> designerAttributeArgumentOpt, CancellationToken cancellationToken) { if (!designerAttributeArgumentOpt.HasValue) { // no value means it couldn't determine whether this document has designer attribute or not. // one of such case is when base type is error type. return; } var data = new Data(textVersion, semanticVersion, designerAttributeArgumentOpt.Value); await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false); RegisterDesignerAttribute(document, designerAttributeArgumentOpt.Value); } private void RegisterDesignerAttribute(Document document, string designerAttributeArgument) { var workspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (workspace == null) { return; } var documentId = document.Id; _notificationService.RegisterNotification(() => { var vsDocument = workspace.GetHostDocument(documentId); if (vsDocument == null) { return; } uint itemId = vsDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } object currentValue; if (ErrorHandler.Succeeded(vsDocument.Project.Hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ItemSubType, out currentValue))) { var currentStringValue = string.IsNullOrEmpty(currentValue as string) ? null : (string)currentValue; if (string.Equals(currentStringValue, designerAttributeArgument, StringComparison.OrdinalIgnoreCase)) { // PERF: Avoid sending the message if the project system already has the current value. return; } } try { var designer = GetDesignerFromForegroundThread(); if (designer != null) { designer.RegisterDesignViewAttribute(vsDocument.Project.Hierarchy, (int)itemId, dwClass: 0, pwszAttributeValue: designerAttributeArgument); } } catch { // DevDiv # 933717 // turns out RegisterDesignViewAttribute can throw in certain cases such as a file failed to be checked out by source control // or IVSHierarchy failed to set a property for this project // // just swallow it. don't crash VS. } }, _listener.BeginAsyncOperation("RegisterDesignerAttribute")); } private IVSMDDesignerService GetDesignerFromForegroundThread() { if (_dotNotAccessDirectlyDesigner != null) { return _dotNotAccessDirectlyDesigner; } AssertIsForeground(); _dotNotAccessDirectlyDesigner = _serviceProvider.GetService(typeof(SVSMDDesignerService)) as IVSMDDesignerService; return _dotNotAccessDirectlyDesigner; } public void RemoveDocument(DocumentId documentId) { _state.Remove(documentId); } private class Data { public readonly VersionStamp TextVersion; public readonly VersionStamp SemanticVersion; public readonly string DesignerAttributeArgument; public Data(VersionStamp textVersion, VersionStamp semanticVersion, string designerAttributeArgument) { this.TextVersion = textVersion; this.SemanticVersion = semanticVersion; this.DesignerAttributeArgument = designerAttributeArgument; } } #region unused public System.Threading.Tasks.Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public System.Threading.Tasks.Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public System.Threading.Tasks.Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public System.Threading.Tasks.Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public System.Threading.Tasks.Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public void RemoveProject(ProjectId projectId) { } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DomainDnsRecordRequest. /// </summary> public partial class DomainDnsRecordRequest : BaseRequest, IDomainDnsRecordRequest { /// <summary> /// Constructs a new DomainDnsRecordRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DomainDnsRecordRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DomainDnsRecord using POST. /// </summary> /// <param name="domainDnsRecordToCreate">The DomainDnsRecord to create.</param> /// <returns>The created DomainDnsRecord.</returns> public System.Threading.Tasks.Task<DomainDnsRecord> CreateAsync(DomainDnsRecord domainDnsRecordToCreate) { return this.CreateAsync(domainDnsRecordToCreate, CancellationToken.None); } /// <summary> /// Creates the specified DomainDnsRecord using POST. /// </summary> /// <param name="domainDnsRecordToCreate">The DomainDnsRecord to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DomainDnsRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsRecord> CreateAsync(DomainDnsRecord domainDnsRecordToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<DomainDnsRecord>(domainDnsRecordToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified DomainDnsRecord. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified DomainDnsRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<DomainDnsRecord>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified DomainDnsRecord. /// </summary> /// <returns>The DomainDnsRecord.</returns> public System.Threading.Tasks.Task<DomainDnsRecord> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified DomainDnsRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DomainDnsRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsRecord> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<DomainDnsRecord>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified DomainDnsRecord using PATCH. /// </summary> /// <param name="domainDnsRecordToUpdate">The DomainDnsRecord to update.</param> /// <returns>The updated DomainDnsRecord.</returns> public System.Threading.Tasks.Task<DomainDnsRecord> UpdateAsync(DomainDnsRecord domainDnsRecordToUpdate) { return this.UpdateAsync(domainDnsRecordToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified DomainDnsRecord using PATCH. /// </summary> /// <param name="domainDnsRecordToUpdate">The DomainDnsRecord to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DomainDnsRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsRecord> UpdateAsync(DomainDnsRecord domainDnsRecordToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<DomainDnsRecord>(domainDnsRecordToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDomainDnsRecordRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDomainDnsRecordRequest Expand(Expression<Func<DomainDnsRecord, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDomainDnsRecordRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDomainDnsRecordRequest Select(Expression<Func<DomainDnsRecord, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="domainDnsRecordToInitialize">The <see cref="DomainDnsRecord"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DomainDnsRecord domainDnsRecordToInitialize) { } } }
using System; using System.Collections.Generic; using System.Text; namespace Codehaus.Parsec { public delegate bool FromToken<T>(Tok tok, ref T result); public delegate TTo Map<TFrom, TTo>(TFrom from); public delegate TTo Map<TA, TB, TTo>(TA a, TB b); public delegate TTo Map<TA, TB, TC, TTo>(TA a, TB b, TC c); public delegate TTo Map<TA, TB, TC, TD, TTo>(TA a, TB b, TC c, TD d); public delegate TTo Map<TA, TB, TC, TD, TE, TTo>(TA a, TB b, TC c, TD d, TE e); public delegate TTo Map<TTo>(params object[] args); public delegate TTo Mapn<TFrom, TTo>(params TFrom[] args); public delegate bool Predicate<T>(T t); public delegate T[] ArrayFactory<T>(int len); public delegate TR FromRange<T, TR>(int from, int len, T data); public delegate TR FromRange<TA, TB, TR>(int from, int len, TA a, TB b); public delegate TR FromRange<TA, TB, TC, TR>(int from, int len, TA a, TB b, TC c); /// <summary> /// Used to trace a parser. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ok">whether the parser succeeded.</param> /// <param name="result">the parser result if succeeded.</param> /// <param name="except">pseudo exception.</param> /// <param name="src">the text being parsed.</param> /// <param name="index">the index where the parser terminates.</param> /// <param name="steps">logical steps consumed by the parser.</param> /// <param name="offset">physical offset consumed by the parser.</param> internal delegate void Tracer<T>(bool ok, T result, object except, string src, int index, int steps, int offset); /// <summary> /// Used to trace a parser when it fails. /// </summary> /// <param name="except">the pseudo exception.</param> /// <param name="src">the text being parsed.</param> /// <param name="index">the index where the error happens.</param> /// <param name="steps">the logical steps consumed.</param> /// <param name="offset">the physical offset consumed.</param> public delegate void ErrorTrace(object except, string src, int index, int steps, int offset); /// <summary> /// Used to trace a parser when it succeeds. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="result">the parser result.</param> /// <param name="src">the text being parsed.</param> /// <param name="index">the index where the parser succeeds.</param> /// <param name="steps">the logical steps consumed.</param> /// <param name="offset">the physical offset consumed.</param> public delegate void GoodTrace<T>(T result, string src, int index, int steps, int offset); public delegate Parser<To> Binder<From, To>(From from); public delegate void Proc(); public delegate void Proc<T>(T t); public delegate void Proc<TA, TB>(TA a, TB b); public delegate void Proc<TA, TB, TC>(TA a, TB b, TC c); public delegate void Proc<TA, TB, TC, TD>(TA a, TB b, TC c, TD d); public delegate void Proc<TA, TB, TC, TD, TE>(TA a, TB b, TC c, TD d, TE e); public delegate Parser<T> Catch<T>(T val, object e); public delegate T Generator<T>(); public static class Tuple { public static T Create<T>(T v) { return v; } public static Pair<A, B> Create<A, B>(A a, B b) { return new Pair<A, B>(a, b); } public static Tuple<A, B, C> Create<A, B, C>(A a, B b, C c) { return new Tuple<A, B, C>(a, b, c); } public static Tuple<A, B, C, D> Create<A, B, C, D>(A a, B b, C c, D d) { return new Tuple<A, B, C, D>(a, b, c, d); } public static Tuple<A, B, C, D, E> Create<A, B, C, D, E>(A a, B b, C c, D d, E e) { return new Tuple<A, B, C, D, E>(a, b, c, d, e); } } public struct Pair<A, B> : IEquatable<Pair<A, B>> { public A V1 { get; set; } public B V2 { get; set; } public Pair(A a, B b) { this.V1 = a; this.V2 = b; } public override bool Equals(object obj) { return Equals((Pair<A, B>)obj); } public bool Equals(Pair<A, B> other) { return V1.Equals(other.V1) && V2.Equals(other.V2); } public static bool operator ==(Pair<A, B> x, Pair<A, B> y) { return x.Equals(y); } public static bool operator !=(Pair<A, B> x, Pair<A, B> y) { return !(x == y); } public override int GetHashCode() { return V1.GetHashCode() ^ V2.GetHashCode(); } } public struct Tuple<A, B, C> : IEquatable<Tuple<A, B, C>> { public A V1 { get; set; } public B V2 { get; set; } public C V3 { get; set; } public Tuple(A a, B b, C c) { this.V1 = a; this.V2 = b; this.V3 = c; } public override bool Equals(object obj) { return Equals((Tuple<A, B, C>)obj); } public bool Equals(Tuple<A, B, C> other) { return V1.Equals(other.V1) && V2.Equals(other.V2) && V3.Equals(other.V3); } public static bool operator ==(Tuple<A, B, C> x, Tuple<A, B, C> y) { return x.Equals(y); } public static bool operator !=(Tuple<A, B, C> x, Tuple<A, B, C> y) { return !(x == y); } public override int GetHashCode() { return V1.GetHashCode() ^ V2.GetHashCode() ^ V3.GetHashCode(); } } public struct Tuple<A, B, C, D> : IEquatable<Tuple<A, B, C, D>> { public A V1 { get; set; } public B V2 { get; set; } public C V3 { get; set; } public D V4 { get; set; } public Tuple(A a, B b, C c, D d) { this.V1 = a; this.V2 = b; this.V3 = c; this.V4 = d; } public override bool Equals(object obj) { return Equals((Tuple<A, B, C, D>)obj); } public bool Equals(Tuple<A, B, C, D> other) { return V1.Equals(other.V1) && V2.Equals(other.V2) && V3.Equals(other.V3) && V4.Equals(other.V4); } public static bool operator ==(Tuple<A, B, C, D> x, Tuple<A, B, C, D> y) { return x.Equals(y); } public static bool operator !=(Tuple<A, B, C, D> x, Tuple<A, B, C, D> y) { return !(x == y); } public override int GetHashCode() { return V1.GetHashCode() ^ V2.GetHashCode() ^ V3.GetHashCode() ^ V4.GetHashCode(); } } public struct Tuple<A, B, C, D, E> : IEquatable<Tuple<A, B, C, D, E>> { public A V1 { get; set; } public B V2 { get; set; } public C V3 { get; set; } public D V4 { get; set; } public E V5 { get; set; } public Tuple(A a, B b, C c, D d, E e) { this.V1 = a; this.V2 = b; this.V3 = c; this.V4 = d; this.V5 = e; } public override bool Equals(object obj) { return Equals((Tuple<A, B, C, D, E>)obj); } public bool Equals(Tuple<A, B, C, D, E> other) { return V1.Equals(other.V1) && V2.Equals(other.V2) && V3.Equals(other.V3) && V4.Equals(other.V4) && V5.Equals(other.V5); } public static bool operator ==(Tuple<A, B, C, D, E> x, Tuple<A, B, C, D, E> y) { return x.Equals(y); } public static bool operator !=(Tuple<A, B, C, D, E> x, Tuple<A, B, C, D, E> y) { return !(x == y); } public override int GetHashCode() { return V1.GetHashCode() ^ V2.GetHashCode() ^ V3.GetHashCode() ^ V4.GetHashCode() ^ V5.GetHashCode(); } } public static class Traces { const int LDEADING = 32; static string getLeadingChars(string src, int ind, int n) { int len = src.Length; if (ind >= len) { return "<EOF>"; } if (n + ind >= len) { n = len - ind; return src.Substring(ind, n); } return src.Substring(ind, n) + "..."; } /// <summary> /// Create an ErrorTrace object that prints error message to output. /// </summary> /// <param name="name">the name in the trace message.</param> /// <param name="writer">the writer for the output.</param> /// <param name="min_steps">the minimal logical steps to trigger the trace message.</param> /// <returns>the ErrorTrace object.</returns> public static ErrorTrace PrintError(string name, System.IO.TextWriter writer, int min_steps) { return delegate(object exception, string src, int ind, int steps, int offset) { if (steps < min_steps) return; writer.Write("{0}: ", name); if (exception != null) { writer.WriteLine("exception raised."); } writer.WriteLine("[{0}]", getLeadingChars(src, ind, LDEADING)); writer.WriteLine("steps={0}, offset={1}", steps, offset); }; } /// <summary> /// Create a GoodTrace object that prints parse result to output. /// </summary> /// <param name="name">the name in the trace message.</param> /// <param name="writer">the writer for the output.</param> /// <returns>the GoodTrace object.</returns> public static GoodTrace<T> PrintResult<T>(string name, System.IO.TextWriter writer) { return delegate(T result, string src, int ind, int steps, int offset) { writer.WriteLine("{0} => {1}", name, result); writer.WriteLine("[{0}]", getLeadingChars(src, ind, LDEADING)); writer.WriteLine("steps={0}, offset={1}", steps, offset); }; } } public static class Functors { public static ArrayFactory<T> getSimpleArrayFactory<T>() { return delegate(int n) { return new T[n]; }; } public static Generator<Accumulator<T, T[]>> ToArrayAccumulatable<T>(ArrayFactory<T> factory) { return delegate() { return new ArrayAccumulator<T>(factory, new System.Collections.Generic.List<T>()); }; } public static Generator<Accumulator<T, T[]>> ToArrayAccumulatable<T>( T initial_value, ArrayFactory<T> factory) { return delegate() { List<T> list = new System.Collections.Generic.List<T>(); list.Add(initial_value); return new ArrayAccumulator<T>(factory, list); }; } static readonly FromToken<object> any_token = delegate(Tok tok, ref object result) { result = tok.Token; return true; }; public static FromToken<object> AnyToken { get { return any_token; } } public static Map<From, To> AsMap<From, To>(System.Collections.IDictionary dict) where To : class { return delegate(From key) { return dict[key] as To; }; } } public static class Maps { public static string ToString(object v) { return v == null ? "<null>" : v.ToString(); } public static readonly Map<object, string> ToStringMap = new Map<object, string>(ToString); static readonly Map<object, object> object_id = delegate(object v) { return v; }; public static Map<object, object> Identity { get { return object_id; } } public static Map<T, T> Id<T>() { return delegate(T v) { return v; }; } public static Map<A, B, Pair<A, B>> ToPair<A, B>() { return delegate(A a, B b) { return Tuple.Create(a, b); }; } public static Map<A, B, C, Tuple<A, B, C>> ToTuple<A, B, C>() { return delegate(A a, B b, C c) { return Tuple.Create(a, b, c); }; } public static Map<A, B, C, D, Tuple<A, B, C, D>> ToTuple<A, B, C, D>() { return delegate(A a, B b, C c, D d) { return Tuple.Create(a, b, c, d); }; } public static Map<A, B, C, D, E, Tuple<A, B, C, D, E>> ToTuple<A, B, C, D, E>() { return delegate(A a, B b, C c, D d, E e) { return Tuple.Create(a, b, c, d, e); }; } } class IntOrders { public static Map<int, int, bool> Less() { return delegate(int a, int b) { return a < b; }; } public static Map<int, int, bool> Greater() { return delegate(int a, int b) { return a > b; }; } public static Map<int, int, bool> LessEqual() { return delegate(int a, int b) { return a <= b; }; } public static Map<int, int, bool> GreaterEqual() { return delegate(int a, int b) { return a >= b; }; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Drawing; using System.ComponentModel; //Original: http://blogs.msdn.com/jfoscoding/articles/491523.aspx //Wyatt's fixes: http://wyday.com/blog/csharp-splitbutton namespace InstantUpdate.Controls { public class SplitButton : Button { private PushButtonState _state; private const int SplitSectionWidth = 14; private static int BorderSize = SystemInformation.Border3DSize.Width * 2; private Rectangle dropDownRectangle = new Rectangle(); private bool showSplit = false; private bool isSplitMenuVisible = false; private bool isMouseOutside = false; private ContextMenuStrip m_SplitMenuStrip = null; private ContextMenu m_SplitMenu = null; TextFormatFlags textFormatFlags = TextFormatFlags.Default; public SplitButton() { this.AutoSize = true; State = PushButtonState.Normal; } #region Properties [Browsable(false)] public override ContextMenuStrip ContextMenuStrip { get { return m_SplitMenuStrip; } set { m_SplitMenuStrip = value; } } [DefaultValue(null)] public ContextMenu SplitMenu { get { return m_SplitMenu; } set { //remove the event handlers for the old SplitMenu if (m_SplitMenu != null) { m_SplitMenu.Popup -= new EventHandler(SplitMenu_Popup); } //add the event handlers for the new SplitMenu if (value != null) { ShowSplit = true; value.Popup += new EventHandler(SplitMenu_Popup); } else ShowSplit = false; m_SplitMenu = value; } } [DefaultValue(null)] public ContextMenuStrip SplitMenuStrip { get { return m_SplitMenuStrip; } set { //remove the event handlers for the old SplitMenuStrip if (m_SplitMenuStrip != null) { m_SplitMenuStrip.Closing -= new ToolStripDropDownClosingEventHandler(SplitMenuStrip_Closing); m_SplitMenuStrip.Opening -= new CancelEventHandler(SplitMenuStrip_Opening); } //add the event handlers for the new SplitMenuStrip if (value != null) { ShowSplit = true; value.Closing += new ToolStripDropDownClosingEventHandler(SplitMenuStrip_Closing); value.Opening += new CancelEventHandler(SplitMenuStrip_Opening); } else ShowSplit = false; m_SplitMenuStrip = value; } } [DefaultValue(false)] public bool ShowSplit { set { if (value != showSplit) { showSplit = value; Invalidate(); if (this.Parent != null) { this.Parent.PerformLayout(); } } } } private PushButtonState State { get { return _state; } set { if (!_state.Equals(value)) { _state = value; Invalidate(); } } } #endregion Properties protected override bool IsInputKey(Keys keyData) { if (keyData.Equals(Keys.Down) && showSplit) { return true; } else { return base.IsInputKey(keyData); } } protected override void OnGotFocus(EventArgs e) { if (!showSplit) { base.OnGotFocus(e); return; } if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Default; } } protected override void OnKeyDown(KeyEventArgs kevent) { if (showSplit) { if (kevent.KeyCode.Equals(Keys.Down) && !isSplitMenuVisible) { ShowContextMenuStrip(); } else if (kevent.KeyCode.Equals(Keys.Space) && kevent.Modifiers == Keys.None) { State = PushButtonState.Pressed; } } base.OnKeyDown(kevent); } protected override void OnKeyUp(KeyEventArgs kevent) { if (kevent.KeyCode.Equals(Keys.Space)) { if (Control.MouseButtons == MouseButtons.None) { State = PushButtonState.Normal; } } else if (kevent.KeyCode.Equals(Keys.Apps)) { if (Control.MouseButtons == MouseButtons.None && !isSplitMenuVisible) { ShowContextMenuStrip(); } } base.OnKeyUp(kevent); } protected override void OnEnabledChanged(EventArgs e) { if (Enabled) State = PushButtonState.Normal; else State = PushButtonState.Disabled; base.OnEnabledChanged(e); } protected override void OnLostFocus(EventArgs e) { if (!showSplit) { base.OnLostFocus(e); return; } if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Normal; } } protected override void OnMouseEnter(EventArgs e) { if (!showSplit) { base.OnMouseEnter(e); return; } if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { isMouseOutside = false; State = PushButtonState.Hot; } } protected override void OnMouseLeave(EventArgs e) { if (!showSplit) { base.OnMouseLeave(e); return; } //!(State.Equals(PushButtonState.Pressed) && isSplitMenuVisible && ClientRectangle.Contains(PointToClient(Cursor.Position)) ) if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { if (Focused) { State = PushButtonState.Default; } else { State = PushButtonState.Normal; } } } protected override void OnMouseMove(MouseEventArgs mevent) { if (!ClientRectangle.Contains(mevent.Location)) { if (State.Equals(PushButtonState.Pressed) && !isSplitMenuVisible) { isMouseOutside = true; State = PushButtonState.Hot; } } else if (isMouseOutside) //mouse is now inside the button, but was previously outside { isMouseOutside = false; State = PushButtonState.Pressed; } base.OnMouseMove(mevent); } protected override void OnMouseDown(MouseEventArgs e) { if (!showSplit) { base.OnMouseDown(e); return; } if (/*dropDownRectangle.Contains(e.Location) &&*/ !isSplitMenuVisible && e.Button == MouseButtons.Left) { if (State != PushButtonState.Pressed) ShowContextMenuStrip(); else State = PushButtonState.Hot; } else { State = PushButtonState.Pressed; } } protected override void OnMouseUp(MouseEventArgs mevent) { if (!showSplit) { base.OnMouseUp(mevent); return; } // if the right button was released inside the button if (mevent.Button == MouseButtons.Right && ClientRectangle.Contains(mevent.Location) && !isSplitMenuVisible) { ShowContextMenuStrip(); } else if (m_SplitMenuStrip == null && m_SplitMenu == null || !isSplitMenuVisible) { SetButtonDrawState(); if (ClientRectangle.Contains(mevent.Location) && !dropDownRectangle.Contains(mevent.Location)) { OnClick(new EventArgs()); } } } protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); if (!showSplit) { return; } Graphics g = pevent.Graphics; Rectangle bounds = this.ClientRectangle; switch (State) { case PushButtonState.Default: case PushButtonState.Disabled: case PushButtonState.Hot: case PushButtonState.Normal: g.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle); //TODO: insert painting code break; case PushButtonState.Pressed: g.FillRectangle(Brushes.White, this.ClientRectangle); break; } //// draw the button background as according to the current state. //if (State != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles) //{ // Rectangle backgroundBounds = bounds; // backgroundBounds.Inflate(-1, -1); // ButtonRenderer.DrawButton(g, backgroundBounds, State); // // button renderer doesnt draw the black frame when themes are off =( // g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1); //} //else //{ // ButtonRenderer.DrawButton(g, bounds, State); //} // calculate the current dropdown rectangle. dropDownRectangle = new Rectangle(bounds.Right - SplitSectionWidth, 0, SplitSectionWidth, bounds.Height); int internalBorder = BorderSize; Rectangle focusRect = new Rectangle(internalBorder - 1, internalBorder - 1, bounds.Width - dropDownRectangle.Width - internalBorder, bounds.Height - (internalBorder * 2) + 2); bool drawSplitLine = (State == PushButtonState.Hot || State == PushButtonState.Pressed || !Application.RenderWithVisualStyles); if (RightToLeft == RightToLeft.Yes) { dropDownRectangle.X = bounds.Left + 1; focusRect.X = dropDownRectangle.Right; if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Left + SplitSectionWidth, BorderSize, bounds.Left + SplitSectionWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Left + SplitSectionWidth + 1, BorderSize, bounds.Left + SplitSectionWidth + 1, bounds.Bottom - BorderSize); } } else { if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Right - SplitSectionWidth, BorderSize, bounds.Right - SplitSectionWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Right - SplitSectionWidth - 1, BorderSize, bounds.Right - SplitSectionWidth - 1, bounds.Bottom - BorderSize); } } // Draw an arrow in the correct location PaintArrow(g, dropDownRectangle); //paint the image and text in the "button" part of the splitButton PaintTextandImage(g, new Rectangle(0, 0, ClientRectangle.Width - SplitSectionWidth, ClientRectangle.Height)); // draw the focus rectangle. if (State != PushButtonState.Pressed && Focused && ShowFocusCues) { ControlPaint.DrawFocusRectangle(g, focusRect); } ControlPaint.DrawBorder(g, this.ClientRectangle, Color.DimGray, ButtonBorderStyle.Solid); if (State == PushButtonState.Hot) { g.DrawLine(Pens.White, ClientRectangle.Location, new Point(ClientRectangle.Right, ClientRectangle.Top)); g.DrawLine(Pens.White, ClientRectangle.Location, new Point(ClientRectangle.Left, ClientRectangle.Bottom)); } } private void PaintTextandImage(Graphics g, Rectangle bounds) { // Figure out where our text and image should go Rectangle text_rectangle; Rectangle image_rectangle; CalculateButtonTextAndImageLayout(ref bounds, out text_rectangle, out image_rectangle); //draw the image if (Image != null) { if (Enabled) g.DrawImage(Image, image_rectangle.X, image_rectangle.Y, Image.Width, Image.Height); else ControlPaint.DrawImageDisabled(g, Image, image_rectangle.X, image_rectangle.Y, BackColor); } // If we dont' use mnemonic, set formatFlag to NoPrefix as this will show ampersand. if (!UseMnemonic) textFormatFlags = textFormatFlags | TextFormatFlags.NoPrefix; else if (!ShowKeyboardCues) textFormatFlags = textFormatFlags | TextFormatFlags.HidePrefix; //draw the text if (!string.IsNullOrEmpty(this.Text)) { if (Enabled) TextRenderer.DrawText(g, Text, Font, text_rectangle, SystemColors.ControlText, textFormatFlags); else ControlPaint.DrawStringDisabled(g, Text, Font, BackColor, text_rectangle, textFormatFlags); } } private void PaintArrow(Graphics g, Rectangle dropDownRect) { Point middle = new Point(Convert.ToInt32(dropDownRect.Left + dropDownRect.Width / 2), Convert.ToInt32(dropDownRect.Top + dropDownRect.Height / 2)); //if the width is odd - favor pushing it over one pixel right. middle.X += (dropDownRect.Width % 2); Point[] arrow = new Point[] { new Point(middle.X - 2, middle.Y - 1), new Point(middle.X + 3, middle.Y - 1), new Point(middle.X, middle.Y + 2) }; if (Enabled) g.FillPolygon(SystemBrushes.ControlText, arrow); else g.FillPolygon(SystemBrushes.ButtonShadow, arrow); } public override Size GetPreferredSize(Size proposedSize) { Size preferredSize = base.GetPreferredSize(proposedSize); //autosize correctly for splitbuttons if (showSplit) { if (AutoSize) return CalculateButtonAutoSize(); else if (!string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + SplitSectionWidth > preferredSize.Width) return preferredSize + new Size(SplitSectionWidth + BorderSize * 2, 0); } return preferredSize; } private Size CalculateButtonAutoSize() { Size ret_size = Size.Empty; Size text_size = TextRenderer.MeasureText(Text, Font); Size image_size = Image == null ? Size.Empty : Image.Size; // Pad the text size if (Text.Length != 0) { text_size.Height += 4; text_size.Width += 4; } switch (TextImageRelation) { case TextImageRelation.Overlay: ret_size.Height = Math.Max(Text.Length == 0 ? 0 : text_size.Height, image_size.Height); ret_size.Width = Math.Max(text_size.Width, image_size.Width); break; case TextImageRelation.ImageAboveText: case TextImageRelation.TextAboveImage: ret_size.Height = text_size.Height + image_size.Height; ret_size.Width = Math.Max(text_size.Width, image_size.Width); break; case TextImageRelation.ImageBeforeText: case TextImageRelation.TextBeforeImage: ret_size.Height = Math.Max(text_size.Height, image_size.Height); ret_size.Width = text_size.Width + image_size.Width; break; } // Pad the result ret_size.Height += (Padding.Vertical + 6); ret_size.Width += (Padding.Horizontal + 6); //pad the splitButton arrow region if (showSplit) ret_size.Width += SplitSectionWidth; return ret_size; } #region Button Layout Calculations //The following layout functions were taken from Mono's Windows.Forms //implementation, specifically "ThemeWin32Classic.cs", //then modified to fit the context of this splitButton private void CalculateButtonTextAndImageLayout(ref Rectangle content_rect, out Rectangle textRectangle, out Rectangle imageRectangle) { Size text_size = TextRenderer.MeasureText(Text, Font, content_rect.Size, textFormatFlags); Size image_size = Image == null ? Size.Empty : Image.Size; textRectangle = Rectangle.Empty; imageRectangle = Rectangle.Empty; switch (TextImageRelation) { case TextImageRelation.Overlay: // Overlay is easy, text always goes here textRectangle = OverlayObjectRect(ref content_rect, ref text_size, TextAlign); // Rectangle.Inflate(content_rect, -4, -4); //Offset on Windows 98 style when button is pressed if (_state == PushButtonState.Pressed && !Application.RenderWithVisualStyles) textRectangle.Offset(1, 1); // Image is dependent on ImageAlign if (Image != null) imageRectangle = OverlayObjectRect(ref content_rect, ref image_size, ImageAlign); break; case TextImageRelation.ImageAboveText: content_rect.Inflate(-4, -4); LayoutTextAboveOrBelowImage(content_rect, false, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.TextAboveImage: content_rect.Inflate(-4, -4); LayoutTextAboveOrBelowImage(content_rect, true, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.ImageBeforeText: content_rect.Inflate(-4, -4); LayoutTextBeforeOrAfterImage(content_rect, false, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.TextBeforeImage: content_rect.Inflate(-4, -4); LayoutTextBeforeOrAfterImage(content_rect, true, text_size, image_size, out textRectangle, out imageRectangle); break; } } private Rectangle OverlayObjectRect(ref Rectangle container, ref Size sizeOfObject, System.Drawing.ContentAlignment alignment) { int x, y; switch (alignment) { case System.Drawing.ContentAlignment.TopLeft: x = 4; y = 4; break; case System.Drawing.ContentAlignment.TopCenter: x = (container.Width - sizeOfObject.Width) / 2; y = 4; break; case System.Drawing.ContentAlignment.TopRight: x = container.Width - sizeOfObject.Width - 4; y = 4; break; case System.Drawing.ContentAlignment.MiddleLeft: x = 4; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.MiddleCenter: x = (container.Width - sizeOfObject.Width) / 2; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.MiddleRight: x = container.Width - sizeOfObject.Width - 4; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.BottomLeft: x = 4; y = container.Height - sizeOfObject.Height - 4; break; case System.Drawing.ContentAlignment.BottomCenter: x = (container.Width - sizeOfObject.Width) / 2; y = container.Height - sizeOfObject.Height - 4; break; case System.Drawing.ContentAlignment.BottomRight: x = container.Width - sizeOfObject.Width - 4; y = container.Height - sizeOfObject.Height - 4; break; default: x = 4; y = 4; break; } return new Rectangle(x, y, sizeOfObject.Width, sizeOfObject.Height); } private void LayoutTextBeforeOrAfterImage(Rectangle totalArea, bool textFirst, Size textSize, Size imageSize, out Rectangle textRect, out Rectangle imageRect) { int element_spacing = 0; // Spacing between the Text and the Image int total_width = textSize.Width + element_spacing + imageSize.Width; if (!textFirst) element_spacing += 2; // If the text is too big, chop it down to the size we have available to it if (total_width > totalArea.Width) { textSize.Width = totalArea.Width - element_spacing - imageSize.Width; total_width = totalArea.Width; } int excess_width = totalArea.Width - total_width; int offset = 0; Rectangle final_text_rect; Rectangle final_image_rect; HorizontalAlignment h_text = GetHorizontalAlignment(TextAlign); HorizontalAlignment h_image = GetHorizontalAlignment(ImageAlign); if (h_image == HorizontalAlignment.Left) offset = 0; else if (h_image == HorizontalAlignment.Right && h_text == HorizontalAlignment.Right) offset = excess_width; else if (h_image == HorizontalAlignment.Center && (h_text == HorizontalAlignment.Left || h_text == HorizontalAlignment.Center)) offset += (int)(excess_width / 3); else offset += (int)(2 * (excess_width / 3)); if (textFirst) { final_text_rect = new Rectangle(totalArea.Left + offset, AlignInRectangle(totalArea, textSize, TextAlign).Top, textSize.Width, textSize.Height); final_image_rect = new Rectangle(final_text_rect.Right + element_spacing, AlignInRectangle(totalArea, imageSize, ImageAlign).Top, imageSize.Width, imageSize.Height); } else { final_image_rect = new Rectangle(totalArea.Left + offset, AlignInRectangle(totalArea, imageSize, ImageAlign).Top, imageSize.Width, imageSize.Height); final_text_rect = new Rectangle(final_image_rect.Right + element_spacing, AlignInRectangle(totalArea, textSize, TextAlign).Top, textSize.Width, textSize.Height); } textRect = final_text_rect; imageRect = final_image_rect; } private void LayoutTextAboveOrBelowImage(Rectangle totalArea, bool textFirst, Size textSize, Size imageSize, out Rectangle textRect, out Rectangle imageRect) { int element_spacing = 0; // Spacing between the Text and the Image int total_height = textSize.Height + element_spacing + imageSize.Height; if (textFirst) element_spacing += 2; if (textSize.Width > totalArea.Width) textSize.Width = totalArea.Width; // If the there isn't enough room and we're text first, cut out the image if (total_height > totalArea.Height && textFirst) { imageSize = Size.Empty; total_height = totalArea.Height; } int excess_height = totalArea.Height - total_height; int offset = 0; Rectangle final_text_rect; Rectangle final_image_rect; VerticalAlignment v_text = GetVerticalAlignment(TextAlign); VerticalAlignment v_image = GetVerticalAlignment(ImageAlign); if (v_image == VerticalAlignment.Top) offset = 0; else if (v_image == VerticalAlignment.Bottom && v_text == VerticalAlignment.Bottom) offset = excess_height; else if (v_image == VerticalAlignment.Center && (v_text == VerticalAlignment.Top || v_text == VerticalAlignment.Center)) offset += (int)(excess_height / 3); else offset += (int)(2 * (excess_height / 3)); if (textFirst) { final_text_rect = new Rectangle(AlignInRectangle(totalArea, textSize, TextAlign).Left, totalArea.Top + offset, textSize.Width, textSize.Height); final_image_rect = new Rectangle(AlignInRectangle(totalArea, imageSize, ImageAlign).Left, final_text_rect.Bottom + element_spacing, imageSize.Width, imageSize.Height); } else { final_image_rect = new Rectangle(AlignInRectangle(totalArea, imageSize, ImageAlign).Left, totalArea.Top + offset, imageSize.Width, imageSize.Height); final_text_rect = new Rectangle(AlignInRectangle(totalArea, textSize, TextAlign).Left, final_image_rect.Bottom + element_spacing, textSize.Width, textSize.Height); if (final_text_rect.Bottom > totalArea.Bottom) final_text_rect.Y = totalArea.Top; } textRect = final_text_rect; imageRect = final_image_rect; } private HorizontalAlignment GetHorizontalAlignment(System.Drawing.ContentAlignment align) { switch (align) { case System.Drawing.ContentAlignment.BottomLeft: case System.Drawing.ContentAlignment.MiddleLeft: case System.Drawing.ContentAlignment.TopLeft: return HorizontalAlignment.Left; case System.Drawing.ContentAlignment.BottomCenter: case System.Drawing.ContentAlignment.MiddleCenter: case System.Drawing.ContentAlignment.TopCenter: return HorizontalAlignment.Center; case System.Drawing.ContentAlignment.BottomRight: case System.Drawing.ContentAlignment.MiddleRight: case System.Drawing.ContentAlignment.TopRight: return HorizontalAlignment.Right; } return HorizontalAlignment.Left; } private VerticalAlignment GetVerticalAlignment(System.Drawing.ContentAlignment align) { switch (align) { case System.Drawing.ContentAlignment.TopLeft: case System.Drawing.ContentAlignment.TopCenter: case System.Drawing.ContentAlignment.TopRight: return VerticalAlignment.Top; case System.Drawing.ContentAlignment.MiddleLeft: case System.Drawing.ContentAlignment.MiddleCenter: case System.Drawing.ContentAlignment.MiddleRight: return VerticalAlignment.Center; case System.Drawing.ContentAlignment.BottomLeft: case System.Drawing.ContentAlignment.BottomCenter: case System.Drawing.ContentAlignment.BottomRight: return VerticalAlignment.Bottom; } return VerticalAlignment.Top; } internal Rectangle AlignInRectangle(Rectangle outer, Size inner, System.Drawing.ContentAlignment align) { int x = 0; int y = 0; if (align == System.Drawing.ContentAlignment.BottomLeft || align == System.Drawing.ContentAlignment.MiddleLeft || align == System.Drawing.ContentAlignment.TopLeft) x = outer.X; else if (align == System.Drawing.ContentAlignment.BottomCenter || align == System.Drawing.ContentAlignment.MiddleCenter || align == System.Drawing.ContentAlignment.TopCenter) x = Math.Max(outer.X + ((outer.Width - inner.Width) / 2), outer.Left); else if (align == System.Drawing.ContentAlignment.BottomRight || align == System.Drawing.ContentAlignment.MiddleRight || align == System.Drawing.ContentAlignment.TopRight) x = outer.Right - inner.Width; if (align == System.Drawing.ContentAlignment.TopCenter || align == System.Drawing.ContentAlignment.TopLeft || align == System.Drawing.ContentAlignment.TopRight) y = outer.Y; else if (align == System.Drawing.ContentAlignment.MiddleCenter || align == System.Drawing.ContentAlignment.MiddleLeft || align == System.Drawing.ContentAlignment.MiddleRight) y = outer.Y + (outer.Height - inner.Height) / 2; else if (align == System.Drawing.ContentAlignment.BottomCenter || align == System.Drawing.ContentAlignment.BottomRight || align == System.Drawing.ContentAlignment.BottomLeft) y = outer.Bottom - inner.Height; return new Rectangle(x, y, Math.Min(inner.Width, outer.Width), Math.Min(inner.Height, outer.Height)); } #endregion Button Layout Calculations private void ShowContextMenuStrip() { State = PushButtonState.Pressed; if (m_SplitMenu != null) { m_SplitMenu.Show(this, new Point(0, Height - 1)); } else if (m_SplitMenuStrip != null) { m_SplitMenuStrip.Show(this, new Point(0, Height - 1), ToolStripDropDownDirection.BelowRight); } } void SplitMenuStrip_Opening(object sender, CancelEventArgs e) { isSplitMenuVisible = true; } void SplitMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) { isSplitMenuVisible = false; //if the user clicks outside the button, set the button state if (!Bounds.Contains(Parent.PointToClient(Cursor.Position))) SetButtonDrawState(); } void SplitMenu_Popup(object sender, EventArgs e) { isSplitMenuVisible = true; } void SplitMenu_Collapse() { isSplitMenuVisible = false; //if the user clicks outside the button, set the button state if (!Bounds.Contains(Parent.PointToClient(Cursor.Position))) SetButtonDrawState(); } protected override void WndProc(ref Message m) { if (m.Msg == 530) { //this message is only sent when a ContextMenu is closed (not a ContextMenuStrip) SplitMenu_Collapse(); } base.WndProc(ref m); } private void SetButtonDrawState() { if (Bounds.Contains(Parent.PointToClient(Cursor.Position))) { State = PushButtonState.Hot; } else if (Focused) { State = PushButtonState.Default; } else if (!Enabled) { State = PushButtonState.Disabled; } else { State = PushButtonState.Normal; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { internal partial class CSharpIntroduceVariableService { protected override async Task<Document> IntroduceLocalAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken) { var newLocalNameToken = GenerateUniqueLocalName(document, expression, isConstant, cancellationToken); var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); var modifiers = isConstant ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList); var options = await document.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers, SyntaxFactory.VariableDeclaration( this.GetTypeSyntax(document, options, expression, isConstant, cancellationToken), SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, SyntaxFactory.EqualsValueClause(expression.WithoutTrailingTrivia().WithoutLeadingTrivia()))))); var anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken); var lambdas = anonymousMethodParameters.SelectMany(p => p.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).AsEnumerable()) .Where(n => n is ParenthesizedLambdaExpressionSyntax || n is SimpleLambdaExpressionSyntax) .ToSet(); var parentLambda = GetParentLambda(expression, lambdas); if (parentLambda != null) { return IntroduceLocalDeclarationIntoLambda( document, expression, newLocalName, declarationStatement, parentLambda, allOccurrences, cancellationToken); } else if (IsInExpressionBodiedMember(expression)) { return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } else { return await IntroduceLocalDeclarationIntoBlockAsync( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false); } } private Document IntroduceLocalDeclarationIntoLambda( SemanticDocument document, ExpressionSyntax expression, IdentifierNameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, SyntaxNode oldLambda, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = oldLambda is ParenthesizedLambdaExpressionSyntax ? (ExpressionSyntax)((ParenthesizedLambdaExpressionSyntax)oldLambda).Body : (ExpressionSyntax)((SimpleLambdaExpressionSyntax)oldLambda).Body; var rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken); var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol; var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Block(declarationStatement) : SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)); newBody = newBody.WithAdditionalAnnotations(Formatter.Annotation); var newLambda = oldLambda is ParenthesizedLambdaExpressionSyntax ? ((ParenthesizedLambdaExpressionSyntax)oldLambda).WithBody(newBody) : (SyntaxNode)((SimpleLambdaExpressionSyntax)oldLambda).WithBody(newBody); var newRoot = document.Root.ReplaceNode(oldLambda, newLambda); return document.Document.WithSyntaxRoot(newRoot); } private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet<SyntaxNode> lambdas) { var current = expression; while (current != null) { if (lambdas.Contains(current.Parent)) { return current.Parent; } current = current.Parent as ExpressionSyntax; } return null; } private TypeSyntax GetTypeSyntax(SemanticDocument document, DocumentOptionSet options, ExpressionSyntax expression, bool isConstant, CancellationToken cancellationToken) { var typeSymbol = GetTypeSymbol(document, expression, cancellationToken); if (typeSymbol.ContainsAnonymousType()) { return SyntaxFactory.IdentifierName("var"); } if (!isConstant && CanUseVar(typeSymbol) && TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, options, cancellationToken)) { return SyntaxFactory.IdentifierName("var"); } return typeSymbol.GenerateTypeSyntax(); } private bool CanUseVar(ITypeSymbol typeSymbol) { return typeSymbol.TypeKind != TypeKind.Delegate && !typeSymbol.IsErrorType() && !typeSymbol.IsFormattableString(); } private static async Task<Tuple<SemanticDocument, ISet<ExpressionSyntax>>> ComplexifyParentingStatements( SemanticDocument semanticDocument, ISet<ExpressionSyntax> matches, CancellationToken cancellationToken) { // First, track the matches so that we can get back to them later. var newRoot = semanticDocument.Root.TrackNodes(matches); var newDocument = semanticDocument.Document.WithSyntaxRoot(newRoot); var newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); var newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); // Next, expand the topmost parenting expression of each match, being careful // not to expand the matches themselves. var topMostExpressions = newMatches .Select(m => m.AncestorsAndSelf().OfType<ExpressionSyntax>().Last()) .Distinct(); newRoot = await newSemanticDocument.Root .ReplaceNodesAsync( topMostExpressions, computeReplacementAsync: async (oldNode, newNode, ct) => { return await Simplifier .ExpandAsync( oldNode, newSemanticDocument.Document, expandInsideNode: node => { var expression = node as ExpressionSyntax; return expression == null || !newMatches.Contains(expression); }, cancellationToken: ct) .ConfigureAwait(false); }, cancellationToken: cancellationToken) .ConfigureAwait(false); newDocument = newSemanticDocument.Document.WithSyntaxRoot(newRoot); newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); return Tuple.Create(newSemanticDocument, newMatches); } private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( SemanticDocument document, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = expression.GetAncestorOrThis<ArrowExpressionClauseSyntax>(); var oldParentingNode = oldBody.Parent; var leadingTrivia = oldBody.GetLeadingTrivia() .AddRange(oldBody.ArrowToken.TrailingTrivia); var newStatement = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken); var newBody = SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(newStatement)) .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(oldBody.GetTrailingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode newParentingNode = null; if (oldParentingNode is BasePropertyDeclarationSyntax) { var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, newBody); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor })); newParentingNode = ((BasePropertyDeclarationSyntax)oldParentingNode).RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia); if (newParentingNode.IsKind(SyntaxKind.PropertyDeclaration)) { var propertyDeclaration = ((PropertyDeclarationSyntax)newParentingNode); newParentingNode = propertyDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(propertyDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexerDeclaration = ((IndexerDeclarationSyntax)newParentingNode); newParentingNode = indexerDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(indexerDeclaration.SemicolonToken.TrailingTrivia); } } else if (oldParentingNode is BaseMethodDeclarationSyntax) { newParentingNode = ((BaseMethodDeclarationSyntax)oldParentingNode) .RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia) .WithBody(newBody); if (newParentingNode.IsKind(SyntaxKind.MethodDeclaration)) { var methodDeclaration = ((MethodDeclarationSyntax)newParentingNode); newParentingNode = methodDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(methodDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.OperatorDeclaration)) { var operatorDeclaration = ((OperatorDeclarationSyntax)newParentingNode); newParentingNode = operatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(operatorDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.ConversionOperatorDeclaration)) { var conversionOperatorDeclaration = ((ConversionOperatorDeclarationSyntax)newParentingNode); newParentingNode = conversionOperatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(conversionOperatorDeclaration.SemicolonToken.TrailingTrivia); } } var newRoot = document.Root.ReplaceNode(oldParentingNode, newParentingNode); return document.Document.WithSyntaxRoot(newRoot); } private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync( SemanticDocument document, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var oldOutermostBlock = expression.GetAncestorsOrThis<BlockSyntax>().LastOrDefault(); var matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken); Debug.Assert(matches.Contains(expression)); var complexified = await ComplexifyParentingStatements(document, matches, cancellationToken).ConfigureAwait(false); document = complexified.Item1; matches = complexified.Item2; // Our original expression should have been one of the matches, which were tracked as part // of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First(); var innermostStatements = new HashSet<StatementSyntax>( matches.Select(expr => expr.GetAncestorOrThis<StatementSyntax>())); if (innermostStatements.Count == 1) { // If there was only one match, or all the matches came from the same // statement, then we want to place the declaration right above that // statement. Note: we special case this because the statement we are going // to go above might not be in a block and we may have to generate it return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } var oldInnerMostCommonBlock = matches.FindInnermostCommonBlock(); var allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => expr.GetAncestorsOrThis<StatementSyntax>())); var firstStatementAffectedInBlock = oldInnerMostCommonBlock.Statements.First(allAffectedStatements.Contains); var firstStatementAffectedIndex = oldInnerMostCommonBlock.Statements.IndexOf(firstStatementAffectedInBlock); var newInnerMostBlock = Rewrite( document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken); var statements = new List<StatementSyntax>(); statements.AddRange(newInnerMostBlock.Statements.Take(firstStatementAffectedIndex)); statements.Add(declarationStatement); statements.AddRange(newInnerMostBlock.Statements.Skip(firstStatementAffectedIndex)); var finalInnerMostBlock = newInnerMostBlock.WithStatements( SyntaxFactory.List<StatementSyntax>(statements)); var newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock); return document.Document.WithSyntaxRoot(newRoot); } private Document IntroduceLocalForSingleOccurrenceIntoBlock( SemanticDocument document, ExpressionSyntax expression, NameSyntax localName, LocalDeclarationStatementSyntax localDeclaration, bool allOccurrences, CancellationToken cancellationToken) { var oldStatement = expression.GetAncestorOrThis<StatementSyntax>(); var newStatement = Rewrite( document, expression, localName, document, oldStatement, allOccurrences, cancellationToken); if (oldStatement.IsParentKind(SyntaxKind.Block)) { var oldBlock = oldStatement.Parent as BlockSyntax; var statementIndex = oldBlock.Statements.IndexOf(oldStatement); var newBlock = oldBlock.WithStatements(CreateNewStatementList( oldBlock.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldBlock, newBlock); return document.Document.WithSyntaxRoot(newRoot); } else if (oldStatement.IsParentKind(SyntaxKind.SwitchSection)) { var oldSwitchSection = oldStatement.Parent as SwitchSectionSyntax; var statementIndex = oldSwitchSection.Statements.IndexOf(oldStatement); var newSwitchSection = oldSwitchSection.WithStatements(CreateNewStatementList( oldSwitchSection.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldSwitchSection, newSwitchSection); return document.Document.WithSyntaxRoot(newRoot); } else { // we need to introduce a block to put the original statement, along with // the statement we're generating var newBlock = SyntaxFactory.Block(localDeclaration, newStatement).WithAdditionalAnnotations(Formatter.Annotation); var newRoot = document.Root.ReplaceNode(oldStatement, newBlock); return document.Document.WithSyntaxRoot(newRoot); } } private static SyntaxList<StatementSyntax> CreateNewStatementList( SyntaxList<StatementSyntax> oldStatements, LocalDeclarationStatementSyntax localDeclaration, StatementSyntax newStatement, int statementIndex) { return oldStatements.Take(statementIndex) .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia())) .Concat(newStatement.WithoutLeadingTrivia()) .Concat(oldStatements.Skip(statementIndex + 1)) .ToSyntaxList(); } } }
// 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.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping : Component { private const int DefaultSendBufferSize = 32; // Same as ping.exe on Windows. private const int DefaultTimeout = 5000; // 5 seconds: same as ping.exe on Windows. private const int MaxBufferSize = 65500; // Artificial constraint due to win32 api limitations. private readonly ManualResetEventSlim _lockObject = new ManualResetEventSlim(initialState: true); // doubles as the ability to wait on the current operation private SendOrPostCallback _onPingCompletedDelegate; private bool _disposeRequested = false; private byte[] _defaultSendBuffer = null; private bool _canceled; // Thread safety: private const int Free = 0; private const int InProgress = 1; private new const int Disposed = 2; private int _status = Free; public Ping() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Ping)) { GC.SuppressFinalize(this); } } private void CheckArgs(int timeout, byte[] buffer, PingOptions options) { CheckDisposed(); if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (buffer.Length > MaxBufferSize) { throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer)); } if (timeout < 0) { throw new ArgumentOutOfRangeException(nameof(timeout)); } } private void CheckArgs(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(timeout, buffer, options); if (address == null) { throw new ArgumentNullException(nameof(address)); } // Check if address family is installed. TestIsIpSupported(address); if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address)); } } private void CheckDisposed() { if (_disposeRequested) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckStart() { int currentStatus; lock (_lockObject) { currentStatus = _status; if (currentStatus == Free) { _canceled = false; _status = InProgress; _lockObject.Reset(); return; } } if (currentStatus == InProgress) { throw new InvalidOperationException(SR.net_inasync); } else { Debug.Assert(currentStatus == Disposed, $"Expected currentStatus == Disposed, got {currentStatus}"); throw new ObjectDisposedException(GetType().FullName); } } private static IPAddress GetAddressSnapshot(IPAddress address) { IPAddress addressSnapshot = address.AddressFamily == AddressFamily.InterNetwork ? #pragma warning disable CS0618 // IPAddress.Address is obsoleted, but it's the most efficient way to get the Int32 IPv4 address new IPAddress(address.Address) : #pragma warning restore CS0618 new IPAddress(address.GetAddressBytes(), address.ScopeId); return addressSnapshot; } private void Finish() { lock (_lockObject) { Debug.Assert(_status == InProgress, $"Invalid status: {_status}"); _status = Free; _lockObject.Set(); } if (_disposeRequested) { InternalDispose(); } } // Cancels pending async requests, closes the handles. private void InternalDispose() { _disposeRequested = true; lock (_lockObject) { if (_status != Free) { // Already disposed, or Finish will call Dispose again once Free. return; } _status = Disposed; } InternalDisposeCore(); } protected override void Dispose(bool disposing) { if (disposing) { // Only on explicit dispose. Otherwise, the GC can cleanup everything else. InternalDispose(); } } public event PingCompletedEventHandler PingCompleted; protected void OnPingCompleted(PingCompletedEventArgs e) { PingCompleted?.Invoke(this, e); } public PingReply Send(string hostNameOrAddress) { return Send(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer); } public PingReply Send(string hostNameOrAddress, int timeout) { return Send(hostNameOrAddress, timeout, DefaultSendBuffer); } public PingReply Send(IPAddress address) { return Send(address, DefaultTimeout, DefaultSendBuffer); } public PingReply Send(IPAddress address, int timeout) { return Send(address, timeout, DefaultSendBuffer); } public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer) { return Send(hostNameOrAddress, timeout, buffer, null); } public PingReply Send(IPAddress address, int timeout, byte[] buffer) { return Send(address, timeout, buffer, null); } public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address)) { return Send(address, timeout, buffer, options); } CheckArgs(timeout, buffer, options); return GetAddressAndSend(hostNameOrAddress, timeout, buffer, options); } public PingReply Send(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(address, timeout, buffer, options); // Need to snapshot the address here, so we're sure that it's not changed between now // and the operation, and to be sure that IPAddress.ToString() is called and not some override. IPAddress addressSnapshot = GetAddressSnapshot(address); CheckStart(); try { return SendPingCore(addressSnapshot, buffer, timeout, options); } catch (Exception e) { throw new PingException(SR.net_ping, e); } finally { Finish(); } } public void SendAsync(string hostNameOrAddress, object userToken) { SendAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, object userToken) { SendAsync(hostNameOrAddress, timeout, DefaultSendBuffer, userToken); } public void SendAsync(IPAddress address, object userToken) { SendAsync(address, DefaultTimeout, DefaultSendBuffer, userToken); } public void SendAsync(IPAddress address, int timeout, object userToken) { SendAsync(address, timeout, DefaultSendBuffer, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object userToken) { SendAsync(hostNameOrAddress, timeout, buffer, null, userToken); } public void SendAsync(IPAddress address, int timeout, byte[] buffer, object userToken) { SendAsync(address, timeout, buffer, null, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken) { TranslateTaskToEap(userToken, SendPingAsync(hostNameOrAddress, timeout, buffer, options)); } public void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options, object userToken) { TranslateTaskToEap(userToken, SendPingAsync(address, timeout, buffer, options)); } private void TranslateTaskToEap(object userToken, Task<PingReply> pingTask) { pingTask.ContinueWith((t, state) => { var asyncOp = (AsyncOperation)state; var e = new PingCompletedEventArgs(t.IsCompletedSuccessfully ? t.Result : null, t.Exception, t.IsCanceled, asyncOp.UserSuppliedState); SendOrPostCallback callback = _onPingCompletedDelegate ?? (_onPingCompletedDelegate = new SendOrPostCallback(o => { OnPingCompleted((PingCompletedEventArgs)o); })); asyncOp.PostOperationCompleted(callback, e); }, AsyncOperationManager.CreateOperation(userToken), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } public Task<PingReply> SendPingAsync(IPAddress address) { return SendPingAsync(address, DefaultTimeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress) { return SendPingAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout) { return SendPingAsync(address, timeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout) { return SendPingAsync(hostNameOrAddress, timeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer) { return SendPingAsync(address, timeout, buffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer) { return SendPingAsync(hostNameOrAddress, timeout, buffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(address, timeout, buffer, options); return SendPingAsyncInternal(address, timeout, buffer, options); } private async Task<PingReply> SendPingAsyncInternal(IPAddress address, int timeout, byte[] buffer, PingOptions options) { // Need to snapshot the address here, so we're sure that it's not changed between now // and the operation, and to be sure that IPAddress.ToString() is called and not some override. IPAddress addressSnapshot = GetAddressSnapshot(address); CheckStart(); try { Task<PingReply> pingReplyTask = SendPingAsyncCore(addressSnapshot, buffer, timeout, options); return await pingReplyTask.ConfigureAwait(false); } catch (Exception e) { throw new PingException(SR.net_ping, e); } finally { Finish(); } } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address)) { return SendPingAsync(address, timeout, buffer, options); } CheckArgs(timeout, buffer, options); return GetAddressAndSendAsync(hostNameOrAddress, timeout, buffer, options); } public void SendAsyncCancel() { lock (_lockObject) { if (!_lockObject.IsSet) { // As in the .NET Framework, this doesn't actually cancel an in-progress operation. It just marks it such that // when the operation completes, it's flagged as canceled. _canceled = true; } } // As in the .NET Framework, synchronously wait for the in-flight operation to complete. // If there isn't one in flight, this event will already be set. _lockObject.Wait(); } private PingReply GetAddressAndSend(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { CheckStart(); try { IPAddress[] addresses = Dns.GetHostAddresses(hostNameOrAddress); return SendPingCore(addresses[0], buffer, timeout, options); } catch (Exception e) { throw new PingException(SR.net_ping, e); } finally { Finish(); } } private async Task<PingReply> GetAddressAndSendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { CheckStart(); try { IPAddress[] addresses = await Dns.GetHostAddressesAsync(hostNameOrAddress).ConfigureAwait(false); Task<PingReply> pingReplyTask = SendPingAsyncCore(addresses[0], buffer, timeout, options); return await pingReplyTask.ConfigureAwait(false); } catch (Exception e) { throw new PingException(SR.net_ping, e); } finally { Finish(); } } // Tests if the current machine supports the given ip protocol family. private void TestIsIpSupported(IPAddress ip) { InitializeSockets(); if (ip.AddressFamily == AddressFamily.InterNetwork && !SocketProtocolSupportPal.OSSupportsIPv4) { throw new NotSupportedException(SR.net_ipv4_not_installed); } else if ((ip.AddressFamily == AddressFamily.InterNetworkV6 && !SocketProtocolSupportPal.OSSupportsIPv6)) { throw new NotSupportedException(SR.net_ipv6_not_installed); } } static partial void InitializeSockets(); partial void InternalDisposeCore(); // Creates a default send buffer if a buffer wasn't specified. This follows the ping.exe model. private byte[] DefaultSendBuffer { get { if (_defaultSendBuffer == null) { _defaultSendBuffer = new byte[DefaultSendBufferSize]; for (int i = 0; i < DefaultSendBufferSize; i++) _defaultSendBuffer[i] = (byte)((int)'a' + i % 23); } return _defaultSendBuffer; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the importexport-2010-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ImportExport.Model { /// <summary> /// Output structure for the GetStatus operation. /// </summary> public partial class GetStatusResponse : AmazonWebServiceResponse { private List<Artifact> _artifactList = new List<Artifact>(); private string _carrier; private DateTime? _creationDate; private string _currentManifest; private int? _errorCount; private string _jobId; private JobType _jobType; private string _locationCode; private string _locationMessage; private string _logBucket; private string _logKey; private string _progressCode; private string _progressMessage; private string _signature; private string _signatureFileContents; private string _trackingNumber; /// <summary> /// Gets and sets the property ArtifactList. /// </summary> public List<Artifact> ArtifactList { get { return this._artifactList; } set { this._artifactList = value; } } // Check to see if ArtifactList property is set internal bool IsSetArtifactList() { return this._artifactList != null && this._artifactList.Count > 0; } /// <summary> /// Gets and sets the property Carrier. /// </summary> public string Carrier { get { return this._carrier; } set { this._carrier = value; } } // Check to see if Carrier property is set internal bool IsSetCarrier() { return this._carrier != null; } /// <summary> /// Gets and sets the property CreationDate. /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property CurrentManifest. /// </summary> public string CurrentManifest { get { return this._currentManifest; } set { this._currentManifest = value; } } // Check to see if CurrentManifest property is set internal bool IsSetCurrentManifest() { return this._currentManifest != null; } /// <summary> /// Gets and sets the property ErrorCount. /// </summary> public int ErrorCount { get { return this._errorCount.GetValueOrDefault(); } set { this._errorCount = value; } } // Check to see if ErrorCount property is set internal bool IsSetErrorCount() { return this._errorCount.HasValue; } /// <summary> /// Gets and sets the property JobId. /// </summary> public string JobId { get { return this._jobId; } set { this._jobId = value; } } // Check to see if JobId property is set internal bool IsSetJobId() { return this._jobId != null; } /// <summary> /// Gets and sets the property JobType. /// </summary> public JobType JobType { get { return this._jobType; } set { this._jobType = value; } } // Check to see if JobType property is set internal bool IsSetJobType() { return this._jobType != null; } /// <summary> /// Gets and sets the property LocationCode. /// </summary> public string LocationCode { get { return this._locationCode; } set { this._locationCode = value; } } // Check to see if LocationCode property is set internal bool IsSetLocationCode() { return this._locationCode != null; } /// <summary> /// Gets and sets the property LocationMessage. /// </summary> public string LocationMessage { get { return this._locationMessage; } set { this._locationMessage = value; } } // Check to see if LocationMessage property is set internal bool IsSetLocationMessage() { return this._locationMessage != null; } /// <summary> /// Gets and sets the property LogBucket. /// </summary> public string LogBucket { get { return this._logBucket; } set { this._logBucket = value; } } // Check to see if LogBucket property is set internal bool IsSetLogBucket() { return this._logBucket != null; } /// <summary> /// Gets and sets the property LogKey. /// </summary> public string LogKey { get { return this._logKey; } set { this._logKey = value; } } // Check to see if LogKey property is set internal bool IsSetLogKey() { return this._logKey != null; } /// <summary> /// Gets and sets the property ProgressCode. /// </summary> public string ProgressCode { get { return this._progressCode; } set { this._progressCode = value; } } // Check to see if ProgressCode property is set internal bool IsSetProgressCode() { return this._progressCode != null; } /// <summary> /// Gets and sets the property ProgressMessage. /// </summary> public string ProgressMessage { get { return this._progressMessage; } set { this._progressMessage = value; } } // Check to see if ProgressMessage property is set internal bool IsSetProgressMessage() { return this._progressMessage != null; } /// <summary> /// Gets and sets the property Signature. /// </summary> public string Signature { get { return this._signature; } set { this._signature = value; } } // Check to see if Signature property is set internal bool IsSetSignature() { return this._signature != null; } /// <summary> /// Gets and sets the property SignatureFileContents. /// </summary> public string SignatureFileContents { get { return this._signatureFileContents; } set { this._signatureFileContents = value; } } // Check to see if SignatureFileContents property is set internal bool IsSetSignatureFileContents() { return this._signatureFileContents != null; } /// <summary> /// Gets and sets the property TrackingNumber. /// </summary> public string TrackingNumber { get { return this._trackingNumber; } set { this._trackingNumber = value; } } // Check to see if TrackingNumber property is set internal bool IsSetTrackingNumber() { return this._trackingNumber != null; } } }
using System; using UnityEngine; using UnitySampleAssets.CrossPlatformInput.PlatformSpecific; namespace UnitySampleAssets.CrossPlatformInput { public static class CrossPlatformInputManager { private static VirtualInput virtualInput; static CrossPlatformInputManager() { #if MOBILE_INPUT virtualInput = new MobileInput (); #else virtualInput = new StandaloneInput(); #endif } public static void RegisterVirtualAxis(VirtualAxis axis) { virtualInput.RegisterVirtualAxis(axis); } public static void RegisterVirtualButton(VirtualButton button) { virtualInput.RegisterVirtualButton(button); } public static void UnRegisterVirtualAxis(string _name) { if (_name == null) { throw new ArgumentNullException("_name"); } virtualInput.UnRegisterVirtualAxis(_name); } public static void UnRegisterVirtualButton(string name) { virtualInput.UnRegisterVirtualButton(name); } // returns a reference to a named virtual axis if it exists otherwise null public static VirtualAxis VirtualAxisReference(string name) { return virtualInput.VirtualAxisReference(name); } // returns the platform appropriate axis for the given name public static float GetAxis(string name) { return GetAxis(name, false); } public static float GetAxisRaw(string name) { return GetAxis(name, true); } // private function handles both types of axis (raw and not raw) private static float GetAxis(string name, bool raw) { return virtualInput.GetAxis(name, raw); } // -- Button handling -- public static bool GetButton(string name) { return virtualInput.GetButton(name); } public static bool GetButtonDown(string name) { return virtualInput.GetButtonDown(name); } public static bool GetButtonUp(string name) { return virtualInput.GetButtonUp(name); } public static void SetButtonDown(string name) { virtualInput.SetButtonDown(name); } public static void SetButtonUp(string name) { virtualInput.SetButtonUp(name); } public static void SetAxisPositive(string name) { virtualInput.SetAxisPositive(name); } public static void SetAxisNegative(string name) { virtualInput.SetAxisNegative(name); } public static void SetAxisZero(string name) { virtualInput.SetAxisZero(name); } public static void SetAxis(string name, float value) { virtualInput.SetAxis(name, value); } public static Vector3 mousePosition { get { return virtualInput.MousePosition(); } } public static void SetVirtualMousePositionX(float f) { virtualInput.SetVirtualMousePositionX(f); } public static void SetVirtualMousePositionY(float f) { virtualInput.SetVirtualMousePositionY(f); } public static void SetVirtualMousePositionZ(float f) { virtualInput.SetVirtualMousePositionZ(f); } // virtual axis and button classes - applies to mobile input // Can be mapped to touch joysticks, tilt, gyro, etc, depending on desired implementation. // Could also be implemented by other input devices - kinect, electronic sensors, etc public class VirtualAxis { public string name { get; private set; } private float m_Value; public bool matchWithInputManager { get; private set; } public VirtualAxis(string name) : this(name, true) { } public VirtualAxis(string name, bool matchToInputSettings) { this.name = name; matchWithInputManager = matchToInputSettings; RegisterVirtualAxis(this); } // removes an axes from the cross platform input system public void Remove() { UnRegisterVirtualAxis(name); } // a controller gameobject (eg. a virtual thumbstick) should update this class public void Update(float value) { m_Value = value; } public float GetValue { get { return m_Value; } } public float GetValueRaw { get { return m_Value; } } } // a controller gameobject (eg. a virtual GUI button) should call the // 'pressed' function of this class. Other objects can then read the // Get/Down/Up state of this button. public class VirtualButton { public string name { get; private set; } private int lastPressedFrame = -5; private int releasedFrame = -5; private bool pressed; public bool matchWithInputManager { get; private set; } public VirtualButton(string name) : this(name, true) { } public VirtualButton(string name, bool matchToInputSettings) { this.name = name; matchWithInputManager = matchToInputSettings; // RegisterVirtualButton(this); } // A controller gameobject should call this function when the button is pressed down public void Pressed() { if (pressed) { return; } pressed = true; lastPressedFrame = Time.frameCount; } // A controller gameobject should call this function when the button is released public void Released() { pressed = false; releasedFrame = Time.frameCount; } // the controller gameobject should call Remove when the button is destroyed or disabled public void Remove() { UnRegisterVirtualButton(name); } // these are the states of the button which can be read via the cross platform input system public bool GetButton { get { return pressed; } } public bool GetButtonDown { get { return lastPressedFrame - Time.frameCount == 0; } } public bool GetButtonUp { get { return (releasedFrame == Time.frameCount - 0); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; using Xunit; namespace System.Xml.Tests { public class TCWriterWithMemoryStream { public XmlWriter CreateMemWriter(XmlWriterUtils utils, Stream writerStream, XmlWriterSettings settings) { XmlWriterSettings wSettings = settings.Clone(); wSettings.CloseOutput = false; wSettings.OmitXmlDeclaration = true; wSettings.CheckCharacters = false; XmlWriter w = null; switch (utils.WriterType) { case WriterType.UTF8Writer: wSettings.Encoding = Encoding.UTF8; w = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.UnicodeWriter: wSettings.Encoding = Encoding.Unicode; w = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.WrappedWriter: XmlWriter ww = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); w = WriterHelper.Create(ww, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.CharCheckingWriter: XmlWriter cw = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); XmlWriterSettings cws = settings.Clone(); cws.CheckCharacters = true; w = WriterHelper.Create(cw, cws, overrideAsync: true, async: utils.Async); break; case WriterType.CustomWriter: wSettings.Async = utils.Async; w = new CustomWriter(writerStream, wSettings); break; case WriterType.UTF8WriterIndent: wSettings.Encoding = Encoding.UTF8; wSettings.Indent = true; w = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.UnicodeWriterIndent: wSettings.Encoding = Encoding.Unicode; wSettings.Indent = true; w = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); break; default: throw new Exception("Unknown writer type"); } return w; } [Theory] [XmlWriterInlineData] public void XmlWellFormedWriterDoesNotThrowIndexOutOfRange0(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteCData(string.Empty); w.WriteComment(string.Empty); w.WriteCData(string.Empty); w.WriteComment(string.Empty); } } } [Theory] [XmlWriterInlineData] public void XmlWellFormedWriterDoesNotThrowIndexOutOfRange1(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteRaw(""); w.WriteCData(""); w.WriteComment(""); w.WriteCData(""); w.WriteRaw(""); w.WriteCData(""); } } return; } [Theory] [XmlWriterInlineData] public void XmlWellFormedWriterDoesNotThrowIndexOutOfRange2(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); } } return; } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash0(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { string outputXml; using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteElementString("elem", "text"); w.Flush(); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { outputXml = reader.ReadToEnd(); } } } CError.WriteLine("actual: " + outputXml); CError.Compare(outputXml, "<elem>text</elem>", "wrong xml"); Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash1(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { string outputXml; using (Stream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteElementString("elem", "text"); w.Flush(); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { outputXml = reader.ReadToEnd(); } } } CError.WriteLine("actual: " + outputXml); CError.Compare(outputXml, "<elem>text</elem>", "wrong xml"); Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash2(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { string outputXml; using (MemoryStream ms = new MemoryStream()) { using (Stream bs = ms) { using (XmlWriter w = CreateMemWriter(utils, bs, ws)) { w.WriteElementString("elem", "text"); w.Flush(); bs.Position = 0; using (StreamReader reader = new StreamReader(bs)) { outputXml = reader.ReadToEnd(); } } } } CError.WriteLine("actual: " + outputXml); CError.Compare(outputXml, "<elem>text</elem>", "wrong xml"); Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash3(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { string outputXml; using (Stream ms = new MemoryStream()) { using (Stream bs = ms) { using (XmlWriter w = CreateMemWriter(utils, bs, ws)) { w.WriteElementString("elem", "text"); w.Flush(); bs.Position = 0; using (StreamReader reader = new StreamReader(bs)) { outputXml = reader.ReadToEnd(); } } } } CError.WriteLine("actual: " + outputXml); CError.Compare(outputXml, "<elem>text</elem>", "wrong xml"); Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash4(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteRaw(""); w.WriteCData(""); w.WriteComment(""); w.WriteCData(""); w.WriteRaw(""); w.WriteCData(""); w.WriteEndElement(); w.Flush(); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { reader.ReadToEnd(); } } } Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData] public void DisposedFileStreamDoesNotCauseCrash5(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteCData(string.Empty); w.WriteComment(string.Empty); w.WriteCData(string.Empty); w.WriteComment(string.Empty); w.WriteEndElement(); w.Flush(); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { reader.ReadToEnd(); } } } Assert.True(false); } catch (Exception e) { CError.WriteLine("Exception: " + e); return; } } [Theory] [XmlWriterInlineData(WriterType.All & ~WriterType.Async)] public void DisposedFileStreamDoesNotCauseCrash6(XmlWriterUtils utils) { XmlWriterSettings ws = new XmlWriterSettings(); try { using (MemoryStream ms = new MemoryStream()) { using (XmlWriter w = CreateMemWriter(utils, ms, ws)) { w.WriteStartElement("foo"); w.WriteString(new string('a', (2048 * 3) - 50)); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); w.WriteRaw(""); w.WriteCData(""); w.WriteString(""); w.Flush(); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { reader.ReadToEnd(); } } } Assert.True(false, "Exception was not thrown"); } catch (ObjectDisposedException e) { CError.WriteLine("Exception: " + e); return; } } } }
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide //Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats #define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output) //#define POOLING //Currently using a build setting for this one (also it's experimental) #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 using UnityEngine; using Debug = UnityEngine.Debug; #endif using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Text; /* Copyright (c) 2015 Matt Schoen 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. */ public class JSONObject : IEnumerable { #if POOLING const int MAX_POOL_SIZE = 10000; public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>(); #endif const int MAX_DEPTH = 100; const string INFINITY = "\"INFINITY\""; const string NEGINFINITY = "\"NEGINFINITY\""; const string NaN = "\"NaN\""; public static readonly char[] WHITESPACE = { ' ', '\r', '\n', '\t', '\uFEFF', '\u0009' }; public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED } public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } } public Type type = Type.NULL; public int Count { get { if(list == null) return -1; return list.Count; } } public List<JSONObject> list; public List<string> keys; public string str; #if USEFLOAT public float n; public float f { get { return n; } } #else public double n; public float f { get { return (float)n; } } #endif public bool useInt; public long i; public bool b; public delegate void AddJSONContents(JSONObject self); public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array public JSONObject(Type t) { type = t; switch(t) { case Type.ARRAY: list = new List<JSONObject>(); break; case Type.OBJECT: list = new List<JSONObject>(); keys = new List<string>(); break; } } public JSONObject(bool b) { type = Type.BOOL; this.b = b; } #if USEFLOAT public JSONObject(float f) { type = Type.NUMBER; n = f; } #else public JSONObject(double d) { type = Type.NUMBER; n = d; } #endif public JSONObject(int i) { type = Type.NUMBER; this.i = i; useInt = true; n = i; } public JSONObject(long l) { type = Type.NUMBER; i = l; useInt = true; n = l; } public JSONObject(Dictionary<string, string> dic) { type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, string> kvp in dic) { keys.Add(kvp.Key); list.Add(CreateStringObject(kvp.Value)); } } public JSONObject(Dictionary<string, JSONObject> dic) { type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, JSONObject> kvp in dic) { keys.Add(kvp.Key); list.Add(kvp.Value); } } public JSONObject(AddJSONContents content) { content.Invoke(this); } public JSONObject(JSONObject[] objs) { type = Type.ARRAY; list = new List<JSONObject>(objs); } //Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object public static JSONObject StringObject(string val) { return CreateStringObject(val); } public void Absorb(JSONObject obj) { list.AddRange(obj.list); keys.AddRange(obj.keys); str = obj.str; n = obj.n; useInt = obj.useInt; i = obj.i; b = obj.b; type = obj.type; } public static JSONObject Create() { #if POOLING JSONObject result = null; while(result == null && releaseQueue.Count > 0) { result = releaseQueue.Dequeue(); #if DEV //The following cases should NEVER HAPPEN (but they do...) if(result == null) Debug.WriteLine("wtf " + releaseQueue.Count); else if(result.list != null) Debug.WriteLine("wtflist " + result.list.Count); #endif } if(result != null) return result; #endif return new JSONObject(); } public static JSONObject Create(Type t) { JSONObject obj = Create(); obj.type = t; switch(t) { case Type.ARRAY: obj.list = new List<JSONObject>(); break; case Type.OBJECT: obj.list = new List<JSONObject>(); obj.keys = new List<string>(); break; } return obj; } public static JSONObject Create(bool val) { JSONObject obj = Create(); obj.type = Type.BOOL; obj.b = val; return obj; } public static JSONObject Create(float val) { JSONObject obj = Create(); obj.type = Type.NUMBER; obj.n = val; return obj; } public static JSONObject Create(int val) { JSONObject obj = Create(); obj.type = Type.NUMBER; obj.n = val; obj.useInt = true; obj.i = val; return obj; } public static JSONObject Create(long val) { JSONObject obj = Create(); obj.type = Type.NUMBER; obj.n = val; obj.useInt = true; obj.i = val; return obj; } public static JSONObject CreateStringObject(string val) { JSONObject obj = Create(); obj.type = Type.STRING; obj.str = val; return obj; } public static JSONObject CreateBakedObject(string val) { JSONObject bakedObject = Create(); bakedObject.type = Type.BAKED; bakedObject.str = val; return bakedObject; } /// <summary> /// Create a JSONObject by parsing string data /// </summary> /// <param name="val">The string to be parsed</param> /// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level, /// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param> /// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param> /// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully /// parse "a string" into a string-type </param> /// <returns></returns> public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { JSONObject obj = Create(); obj.Parse(val, maxDepth, storeExcessLevels, strict); return obj; } public static JSONObject Create(AddJSONContents content) { JSONObject obj = Create(); content.Invoke(obj); return obj; } public static JSONObject Create(Dictionary<string, string> dic) { JSONObject obj = Create(); obj.type = Type.OBJECT; obj.keys = new List<string>(); obj.list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, string> kvp in dic) { obj.keys.Add(kvp.Key); obj.list.Add(CreateStringObject(kvp.Value)); } return obj; } public JSONObject() { } #region PARSE public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string) Parse(str, maxDepth, storeExcessLevels, strict); } void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { if(!string.IsNullOrEmpty(str)) { str = str.Trim(WHITESPACE); if(strict) { if(str[0] != '[' && str[0] != '{') { type = Type.NULL; #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.LogWarning #else Debug.WriteLine #endif ("Improper (strict) JSON formatting. First character must be [ or {"); return; } } if(str.Length > 0) { #if UNITY_WP8 || UNITY_WSA if (str == "true") { type = Type.BOOL; b = true; } else if (str == "false") { type = Type.BOOL; b = false; } else if (str == "null") { type = Type.NULL; #else if(string.Compare(str, "true", true) == 0) { type = Type.BOOL; b = true; } else if(string.Compare(str, "false", true) == 0) { type = Type.BOOL; b = false; } else if(string.Compare(str, "null", true) == 0) { type = Type.NULL; #endif #if USEFLOAT } else if(str == INFINITY) { type = Type.NUMBER; n = float.PositiveInfinity; } else if(str == NEGINFINITY) { type = Type.NUMBER; n = float.NegativeInfinity; } else if(str == NaN) { type = Type.NUMBER; n = float.NaN; #else } else if(str == INFINITY) { type = Type.NUMBER; n = double.PositiveInfinity; } else if(str == NEGINFINITY) { type = Type.NUMBER; n = double.NegativeInfinity; } else if(str == NaN) { type = Type.NUMBER; n = double.NaN; #endif } else if(str[0] == '"') { type = Type.STRING; this.str = str.Substring(1, str.Length - 2); } else { int tokenTmp = 1; /* * Checking for the following formatting (www.json.org) * object - {"field1":value,"field2":value} * array - [value,value,value] * value - string - "string" * - number - 0.0 * - bool - true -or- false * - null - null */ int offset = 0; switch(str[offset]) { case '{': type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); break; case '[': type = Type.ARRAY; list = new List<JSONObject>(); break; default: try { #if USEFLOAT n = System.Convert.ToSingle(str); #else n = System.Convert.ToDouble(str); #endif if(!str.Contains(".")) { i = System.Convert.ToInt64(str); useInt = true; } type = Type.NUMBER; } catch(System.FormatException) { type = Type.NULL; #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.LogWarning #else Debug.WriteLine #endif ("improper JSON formatting:" + str); } return; } string propName = ""; bool openQuote = false; bool inProp = false; int depth = 0; while(++offset < str.Length) { if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1) continue; if(str[offset] == '\\') { offset += 1; continue; } if(str[offset] == '"') { if(openQuote) { if(!inProp && depth == 0 && type == Type.OBJECT) propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1); openQuote = false; } else { if(depth == 0 && type == Type.OBJECT) tokenTmp = offset; openQuote = true; } } if(openQuote) continue; if(type == Type.OBJECT && depth == 0) { if(str[offset] == ':') { tokenTmp = offset + 1; inProp = true; } } if(str[offset] == '[' || str[offset] == '{') { depth++; } else if(str[offset] == ']' || str[offset] == '}') { depth--; } //if (encounter a ',' at top level) || a closing ]/} if((str[offset] == ',' && depth == 0) || depth < 0) { inProp = false; string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE); if(inner.Length > 0) { if(type == Type.OBJECT) keys.Add(propName); if(maxDepth != -1) //maxDepth of -1 is the end of the line list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1, storeExcessLevels)); else if(storeExcessLevels) list.Add(CreateBakedObject(inner)); } tokenTmp = offset + 1; } } } } else type = Type.NULL; } else type = Type.NULL; //If the string is missing, this is a null //Profiler.EndSample(); } #endregion public bool IsNumber { get { return type == Type.NUMBER; } } public bool IsNull { get { return type == Type.NULL; } } public bool IsString { get { return type == Type.STRING; } } public bool IsBool { get { return type == Type.BOOL; } } public bool IsArray { get { return type == Type.ARRAY; } } public bool IsObject { get { return type == Type.OBJECT || type == Type.BAKED; } } public void Add(bool val) { Add(Create(val)); } public void Add(float val) { Add(Create(val)); } public void Add(int val) { Add(Create(val)); } public void Add(string str) { Add(CreateStringObject(str)); } public void Add(AddJSONContents content) { Add(Create(content)); } public void Add(JSONObject obj) { if(obj) { //Don't do anything if the object is null if(type != Type.ARRAY) { type = Type.ARRAY; //Congratulations, son, you're an ARRAY now if(list == null) list = new List<JSONObject>(); } list.Add(obj); } } public void AddField(string name, bool val) { AddField(name, Create(val)); } public void AddField(string name, float val) { AddField(name, Create(val)); } public void AddField(string name, int val) { AddField(name, Create(val)); } public void AddField(string name, long val) { AddField(name, Create(val)); } public void AddField(string name, AddJSONContents content) { AddField(name, Create(content)); } public void AddField(string name, string val) { AddField(name, CreateStringObject(val)); } public void AddField(string name, JSONObject obj) { if(obj) { //Don't do anything if the object is null if(type != Type.OBJECT) { if(keys == null) keys = new List<string>(); if(type == Type.ARRAY) { for(int i = 0; i < list.Count; i++) keys.Add(i + ""); } else if(list == null) list = new List<JSONObject>(); type = Type.OBJECT; //Congratulations, son, you're an OBJECT now } keys.Add(name); list.Add(obj); } } public void SetField(string name, string val) { SetField(name, CreateStringObject(val)); } public void SetField(string name, bool val) { SetField(name, Create(val)); } public void SetField(string name, float val) { SetField(name, Create(val)); } public void SetField(string name, int val) { SetField(name, Create(val)); } public void SetField(string name, JSONObject obj) { if(HasField(name)) { list.Remove(this[name]); keys.Remove(name); } AddField(name, obj); } public void RemoveField(string name) { if(keys.IndexOf(name) > -1) { list.RemoveAt(keys.IndexOf(name)); keys.Remove(name); } } public delegate void FieldNotFound(string name); public delegate void GetFieldResponse(JSONObject obj); public bool GetField(out bool field, string name, bool fallback) { field = fallback; return GetField(ref field, name); } public bool GetField(ref bool field, string name, FieldNotFound fail = null) { if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].b; return true; } } if(fail != null) fail.Invoke(name); return false; } #if USEFLOAT public bool GetField(out float field, string name, float fallback) { #else public bool GetField(out double field, string name, double fallback) { #endif field = fallback; return GetField(ref field, name); } #if USEFLOAT public bool GetField(ref float field, string name, FieldNotFound fail = null) { #else public bool GetField(ref double field, string name, FieldNotFound fail = null) { #endif if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].n; return true; } } if(fail != null) fail.Invoke(name); return false; } public bool GetField(out int field, string name, int fallback) { field = fallback; return GetField(ref field, name); } public bool GetField(ref int field, string name, FieldNotFound fail = null) { if(IsObject) { int index = keys.IndexOf(name); if(index >= 0) { field = (int)list[index].n; return true; } } if(fail != null) fail.Invoke(name); return false; } public bool GetField(out long field, string name, long fallback) { field = fallback; return GetField(ref field, name); } public bool GetField(ref long field, string name, FieldNotFound fail = null) { if(IsObject) { int index = keys.IndexOf(name); if(index >= 0) { field = (long)list[index].n; return true; } } if(fail != null) fail.Invoke(name); return false; } public bool GetField(out uint field, string name, uint fallback) { field = fallback; return GetField(ref field, name); } public bool GetField(ref uint field, string name, FieldNotFound fail = null) { if(IsObject) { int index = keys.IndexOf(name); if(index >= 0) { field = (uint)list[index].n; return true; } } if(fail != null) fail.Invoke(name); return false; } public bool GetField(out string field, string name, string fallback) { field = fallback; return GetField(ref field, name); } public bool GetField(ref string field, string name, FieldNotFound fail = null) { if(IsObject) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].str; return true; } } if(fail != null) fail.Invoke(name); return false; } public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) { if(response != null && IsObject) { int index = keys.IndexOf(name); if(index >= 0) { response.Invoke(list[index]); return; } } if(fail != null) fail.Invoke(name); } public JSONObject GetField(string name) { if(IsObject) for(int i = 0; i < keys.Count; i++) if(keys[i] == name) return list[i]; return null; } public bool HasFields(string[] names) { if(!IsObject) return false; for(int i = 0; i < names.Length; i++) if(!keys.Contains(names[i])) return false; return true; } public bool HasField(string name) { if(!IsObject) return false; for(int i = 0; i < keys.Count; i++) if(keys[i] == name) return true; return false; } public void Clear() { type = Type.NULL; if(list != null) list.Clear(); if(keys != null) keys.Clear(); str = ""; n = 0; b = false; } /// <summary> /// Copy a JSONObject. This could probably work better /// </summary> /// <returns></returns> public JSONObject Copy() { return Create(Print()); } /* * The Merge function is experimental. Use at your own risk. */ public void Merge(JSONObject obj) { MergeRecur(this, obj); } /// <summary> /// Merge object right into left recursively /// </summary> /// <param name="left">The left (base) object</param> /// <param name="right">The right (new) object</param> static void MergeRecur(JSONObject left, JSONObject right) { if(left.type == Type.NULL) left.Absorb(right); else if(left.type == Type.OBJECT && right.type == Type.OBJECT) { for(int i = 0; i < right.list.Count; i++) { string key = right.keys[i]; if(right[i].isContainer) { if(left.HasField(key)) MergeRecur(left[key], right[i]); else left.AddField(key, right[i]); } else { if(left.HasField(key)) left.SetField(key, right[i]); else left.AddField(key, right[i]); } } } else if(left.type == Type.ARRAY && right.type == Type.ARRAY) { if(right.Count > left.Count) { #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.LogError #else Debug.WriteLine #endif ("Cannot merge arrays when right object has more elements"); return; } for(int i = 0; i < right.list.Count; i++) { if(left[i].type == right[i].type) { //Only overwrite with the same type if(left[i].isContainer) MergeRecur(left[i], right[i]); else { left[i] = right[i]; } } } } } public void Bake() { if(type != Type.BAKED) { str = Print(); type = Type.BAKED; } } public IEnumerable BakeAsync() { if(type != Type.BAKED) { foreach(string s in PrintAsync()) { if(s == null) yield return s; else { str = s; } } type = Type.BAKED; } } #pragma warning disable 219 public string Print(bool pretty = false) { StringBuilder builder = new StringBuilder(); Stringify(0, builder, pretty); return builder.ToString(); } public IEnumerable<string> PrintAsync(bool pretty = false) { StringBuilder builder = new StringBuilder(); printWatch.Reset(); printWatch.Start(); foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) { yield return null; } yield return builder.ToString(); } #pragma warning restore 219 #region STRINGIFY const float maxFrameTime = 0.008f; static readonly Stopwatch printWatch = new Stopwatch(); IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string //Profiler.BeginSample("JSONprint"); if(depth++ > MAX_DEPTH) { #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.Log #else Debug.WriteLine #endif ("reached max depth!"); yield break; } if(printWatch.Elapsed.TotalSeconds > maxFrameTime) { printWatch.Reset(); yield return null; printWatch.Start(); } switch(type) { case Type.BAKED: builder.Append(str); break; case Type.STRING: builder.AppendFormat("\"{0}\"", str); break; case Type.NUMBER: if(useInt) { builder.Append(i.ToString()); } else { #if USEFLOAT if(float.IsInfinity(n)) builder.Append(INFINITY); else if(float.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(float.IsNaN(n)) builder.Append(NaN); #else if(double.IsInfinity(n)) builder.Append(INFINITY); else if(double.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(double.IsNaN(n)) builder.Append(NaN); #endif else builder.Append(n.ToString()); } break; case Type.OBJECT: builder.Append("{"); if(list.Count > 0) { #if(PRETTY) //for a bit more readability, comment the define above to disable system-wide if(pretty) builder.Append("\n"); #endif for(int i = 0; i < list.Count; i++) { string key = keys[i]; JSONObject obj = list[i]; if(obj) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif builder.AppendFormat("\"{0}\":", key); foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty)) yield return e; builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("}"); break; case Type.ARRAY: builder.Append("["); if(list.Count > 0) { #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif for(int i = 0; i < list.Count; i++) { if(list[i]) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty)) yield return e; builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("]"); break; case Type.BOOL: if(b) builder.Append("true"); else builder.Append("false"); break; case Type.NULL: builder.Append("null"); break; } //Profiler.EndSample(); } //TODO: Refactor Stringify functions to share core logic /* * I know, I know, this is really bad form. It turns out that there is a * significant amount of garbage created when calling as a coroutine, so this * method is duplicated. Hopefully there won't be too many future changes, but * I would still like a more elegant way to optionaly yield */ void Stringify(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string //Profiler.BeginSample("JSONprint"); if(depth++ > MAX_DEPTH) { #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.Log #else Debug.WriteLine #endif ("reached max depth!"); return; } switch(type) { case Type.BAKED: builder.Append(str); break; case Type.STRING: builder.AppendFormat("\"{0}\"", str); break; case Type.NUMBER: if(useInt) { builder.Append(i.ToString()); } else { #if USEFLOAT if(float.IsInfinity(n)) builder.Append(INFINITY); else if(float.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(float.IsNaN(n)) builder.Append(NaN); #else if(double.IsInfinity(n)) builder.Append(INFINITY); else if(double.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(double.IsNaN(n)) builder.Append(NaN); #endif else builder.Append(n.ToString()); } break; case Type.OBJECT: builder.Append("{"); if(list.Count > 0) { #if(PRETTY) //for a bit more readability, comment the define above to disable system-wide if(pretty) builder.Append("\n"); #endif for(int i = 0; i < list.Count; i++) { string key = keys[i]; JSONObject obj = list[i]; if(obj) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif builder.AppendFormat("\"{0}\":", key); obj.Stringify(depth, builder, pretty); builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("}"); break; case Type.ARRAY: builder.Append("["); if(list.Count > 0) { #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif for(int i = 0; i < list.Count; i++) { if(list[i]) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif list[i].Stringify(depth, builder, pretty); builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("]"); break; case Type.BOOL: if(b) builder.Append("true"); else builder.Append("false"); break; case Type.NULL: builder.Append("null"); break; } //Profiler.EndSample(); } #endregion #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 public static implicit operator WWWForm(JSONObject obj) { WWWForm form = new WWWForm(); for(int i = 0; i < obj.list.Count; i++) { string key = i + ""; if(obj.type == Type.OBJECT) key = obj.keys[i]; string val = obj.list[i].ToString(); if(obj.list[i].type == Type.STRING) val = val.Replace("\"", ""); form.AddField(key, val); } return form; } #endif public JSONObject this[int index] { get { if(list.Count > index) return list[index]; return null; } set { if(list.Count > index) list[index] = value; } } public JSONObject this[string index] { get { return GetField(index); } set { SetField(index, value); } } public override string ToString() { return Print(); } public string ToString(bool pretty) { return Print(pretty); } public Dictionary<string, string> ToDictionary() { if(type == Type.OBJECT) { Dictionary<string, string> result = new Dictionary<string, string>(); for(int i = 0; i < list.Count; i++) { JSONObject val = list[i]; switch(val.type) { case Type.STRING: result.Add(keys[i], val.str); break; case Type.NUMBER: result.Add(keys[i], val.n + ""); break; case Type.BOOL: result.Add(keys[i], val.b + ""); break; default: #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.LogWarning #else Debug.WriteLine #endif ("Omitting object: " + keys[i] + " in dictionary conversion"); break; } } return result; } #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 Debug.Log #else Debug.WriteLine #endif ("Tried to turn non-Object JSONObject into a dictionary"); return null; } public static implicit operator bool(JSONObject o) { return o != null; } #if POOLING static bool pool = true; public static void ClearPool() { pool = false; releaseQueue.Clear(); pool = true; } ~JSONObject() { if(pool && releaseQueue.Count < MAX_POOL_SIZE) { type = Type.NULL; list = null; keys = null; str = ""; n = 0; b = false; releaseQueue.Enqueue(this); } } #endif IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } public JSONObjectEnumer GetEnumerator() { return new JSONObjectEnumer(this); } } public class JSONObjectEnumer : IEnumerator { public JSONObject _jobj; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public JSONObjectEnumer(JSONObject jsonObject) { Debug.Assert(jsonObject.isContainer); //must be an array or object to itterate _jobj = jsonObject; } public bool MoveNext() { position++; return (position < _jobj.Count); } public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public JSONObject Current { get { if (_jobj.IsArray) { return _jobj[position]; } else { string key = _jobj.keys[position]; return _jobj[key]; } } } }
// <copyright file="ArrayExtensions.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using IX.StandardExtensions.Contracts; using JetBrains.Annotations; namespace IX.StandardExtensions.Extensions; /// <summary> /// Extensions for array types. /// </summary> [PublicAPI] public static partial class ArrayExtensions { /// <summary> /// Deep clones an array. /// </summary> /// <typeparam name="T">The type of the items of the array to clone.</typeparam> /// <param name="source">The source array.</param> /// <returns>An array of deeply-copied elements from the original array.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> public static T[] DeepClone<T>(this T[] source) where T : IDeepCloneable<T> { Requires.NotNull( source); var length = source.Length; var destination = new T[length]; for (var i = 0; i < length; i++) { destination[i] = source[i].DeepClone(); } return destination; } /// <summary> /// Copies an array with shallow clones of its items. /// </summary> /// <typeparam name="T">The type of the items of the array to clone.</typeparam> /// <param name="source">The source array.</param> /// <returns>An array of deeply-copied elements from the original array.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> public static T[] CopyWithShallowClones<T>(this T[] source) where T : IShallowCloneable<T> { Requires.NotNull( source); var length = source.Length; var destination = new T[length]; for (var i = 0; i < length; i++) { destination[i] = source[i].ShallowClone(); } return destination; } /// <summary> /// Copies all items in the specified source array to a new array. /// </summary> /// <typeparam name="T">The type of the array items.</typeparam> /// <param name="source">The source array.</param> /// <returns>A new array with items copied.</returns> /// <remarks> /// <para> /// This method copies all items by reference for reference types. Their instance will be the same as the /// original source array. /// </para> /// <para>If deep cloning is required, please use the <see cref="DeepClone{T}(T[])" /> instead of this method.</para> /// <para>Value types are value-copied.</para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> public static T[] Copy<T>(this T[] source) { Requires.NotNull( source); var length = source.Length; var destination = new T[length]; Array.Copy( source, destination, length); return destination; } /// <summary> /// Copies all items in the specified source array to a new array. /// </summary> /// <typeparam name="T">The type of the array items.</typeparam> /// <param name="source">The source array.</param> /// <param name="length">The length of the sub-array to copy.</param> /// <returns>A new array with items copied.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="length" /> is greater than 0 /// or /// the length exceeds the bounds of the source array. /// </exception> /// <remarks> /// <para> /// This method copies all items by reference for reference types. Their instance will be the same as the /// original source array. /// </para> /// <para>If deep cloning is required, please use the <see cref="DeepClone{T}(T[])" /> instead of this method.</para> /// <para>Value types are value-copied.</para> /// </remarks> public static T[] Copy<T>( this T[] source, int length) { Requires.NotNull( source); Requires.ValidArrayLength( in length, source, nameof(length)); var destination = new T[length]; Array.Copy( source, destination, length); return destination; } /// <summary> /// Copies all items in the specified source array to a new array. /// </summary> /// <typeparam name="T">The type of the array items.</typeparam> /// <param name="source">The source array.</param> /// <param name="sourceIndex">The index at which to start.</param> /// <param name="length">The length of the sub-array to copy.</param> /// <returns>A new array with items copied.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="sourceIndex" /> is less than 0 or greater than the size of the array /// or /// <paramref name="length" /> is greater than 0 /// or /// the source index and length exceed the bounds of the source array. /// </exception> /// <remarks> /// <para> /// This method copies all items by reference for reference types. Their instance will be the same as the /// original source array. /// </para> /// <para>If deep cloning is required, please use the <see cref="DeepClone{T}(T[])" /> instead of this method.</para> /// <para>Value types are value-copied.</para> /// </remarks> public static T[] Copy<T>( this T[] source, int sourceIndex, int length) { Requires.NotNull( source); Requires.ValidArrayRange( in sourceIndex, in length, source, nameof(length)); var destination = new T[length]; Array.Copy( source, sourceIndex, destination, 0, length); return destination; } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="T">The array type.</typeparam> /// <param name="source">The array to run on.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "Yes, but we don't want that to happen. We're interested in top performance in the loop.")] public static void ForEach<T>( this T[] source, Action<T> action) { Requires.NotNull( source); Requires.NotNull( action); for (var i = 0; i < source.Length; i++) { action(source[i]); } } /// <summary> /// Asynchronously executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="T">The array type.</typeparam> /// <param name="source">The array to run on.</param> /// <param name="action">The action to execute.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>A <see cref="ValueTask" /> representing the current operation.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> /// <remarks> /// <para>This method, due to multiple awaits, is considered to be very slow compared to its synchronous version.</para> /// <para>Please make sure to only use this where asynchronicity is required.</para> /// <para>In CPU-intensive operations, only its synchronous counterpart should be used.</para> /// </remarks> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "Yes, but we don't want that to happen. We're interested in top performance in the loop.")] public static async ValueTask ForEachAsync<T>( this T[] source, Func<T, Task> action, CancellationToken cancellationToken = default) { Requires.NotNull( source); Requires.NotNull( action); if (cancellationToken.IsCancellationRequested) { return; } for (var i = 0; i < source.Length; i++) { await action(source[i]); cancellationToken.ThrowIfCancellationRequested(); } } /// <summary> /// Asynchronously executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="T">The array type.</typeparam> /// <param name="source">The array to run on.</param> /// <param name="action">The action to execute.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>A <see cref="ValueTask" /> representing the current operation.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> /// <remarks> /// <para>This method, due to multiple awaits, is considered to be very slow compared to its synchronous version.</para> /// <para>Please make sure to only use this where asynchronicity is required.</para> /// <para>In CPU-intensive operations, only its synchronous counterpart should be used.</para> /// </remarks> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "Yes, but we don't want that to happen. We're interested in top performance in the loop.")] public static async ValueTask ForEachAsync<T>( this T[] source, Func<T, ValueTask> action, CancellationToken cancellationToken = default) { Requires.NotNull( source); Requires.NotNull( action); if (cancellationToken.IsCancellationRequested) { return; } for (var i = 0; i < source.Length; i++) { await action(source[i]); cancellationToken.ThrowIfCancellationRequested(); } } /// <summary> /// Asynchronously executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="T">The array type.</typeparam> /// <param name="source">The array to run on.</param> /// <param name="action">The action to execute.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>A <see cref="ValueTask" /> representing the current operation.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> /// <remarks> /// <para>This method, due to multiple awaits, is considered to be very slow compared to its synchronous version.</para> /// <para>Please make sure to only use this where asynchronicity is required.</para> /// <para>In CPU-intensive operations, only its synchronous counterpart should be used.</para> /// </remarks> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "Yes, but we don't want that to happen. We're interested in top performance in the loop.")] public static async ValueTask ForEachAsync<T>( this T[] source, Func<T, CancellationToken, Task> action, CancellationToken cancellationToken = default) { Requires.NotNull( source); Requires.NotNull( action); if (cancellationToken.IsCancellationRequested) { return; } for (var i = 0; i < source.Length; i++) { await action(source[i], cancellationToken); cancellationToken.ThrowIfCancellationRequested(); } } /// <summary> /// Asynchronously executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="T">The array type.</typeparam> /// <param name="source">The array to run on.</param> /// <param name="action">The action to execute.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>A <see cref="ValueTask" /> representing the current operation.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> /// <remarks> /// <para>This method, due to multiple awaits, is considered to be very slow compared to its synchronous version.</para> /// <para>Please make sure to only use this where asynchronicity is required.</para> /// <para>In CPU-intensive operations, only its synchronous counterpart should be used.</para> /// </remarks> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "Yes, but we don't want that to happen. We're interested in top performance in the loop.")] public static async ValueTask ForEachAsync<T>( this T[] source, Func<T, CancellationToken, ValueTask> action, CancellationToken cancellationToken = default) { Requires.NotNull( source); Requires.NotNull( action); if (cancellationToken.IsCancellationRequested) { return; } for (var i = 0; i < source.Length; i++) { await action(source[i], cancellationToken); cancellationToken.ThrowIfCancellationRequested(); } } }
using UnityEngine; using System.Collections; using Ecosim; using Ecosim.SceneData; using System.Threading; public class GameMenu : MonoBehaviour { private static GameMenu self; public static bool show = true; public GUISkin skin; public Texture2D banner; public GameObject background; private Scene scene; GUIStyle styleLightNormalLeft; GUIStyle styleDarkNormalLeft; GUIStyle styleLightNormal; GUIStyle styleDarkNormal; GUIStyle styleDarkOver; static int defaultQuality = -1; public static void ActivateMenu () { self.enabled = true; self.state = State.Main; // Don't show the background if (self.background) self.background.SetActive (false); } void Awake () { self = this; GameSettings.Setup (); if (defaultQuality < 0) { defaultQuality = QualitySettings.GetQualityLevel (); } } void OnEnable () { if (background) background.SetActive (true); } void OnDisable () { if (background) background.SetActive (false); } void OnDestroy () { self = null; } void Start () { styleLightNormalLeft = skin.FindStyle ("Arial16-50"); styleDarkNormalLeft = skin.FindStyle ("Arial16-75"); styleLightNormal = skin.FindStyle ("Arial16-50-Centre"); styleDarkNormal = skin.FindStyle ("Arial16-75-Centre"); styleDarkOver = skin.FindStyle ("Arial16-W-Centre"); player = new PlayerInfo (); player.firstName = PlayerPrefs.GetString ("PlayerFirstName", "John"); player.familyName = PlayerPrefs.GetString ("PlayerFamilyName", "Fisher"); player.isMale = (PlayerPrefs.GetString ("PlayerGender", "M") == "M"); } int sWidth; int sHeight; int xOffset; enum State { Idle, Main, Settings, LoadNew, LoadNew2, LoadNew3, Continue1, }; volatile State state = State.Main; void RenderBanner (int index) { int hheight = sHeight / 2; int hwidth = sWidth / 2; GUI.Label (new Rect (xOffset + hwidth - (banner.width*0.5f), hheight + 33 * index - banner.height, banner.width, banner.height), banner, GUIStyle.none); } void MainCtrl (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (scene != null) { if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back to game", styleDarkNormal, styleDarkOver)) { state = State.Idle; enabled = false; GameControl.ActivateGameControl (scene); } if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back to menu", styleDarkNormal, styleDarkOver)) { scene = null; TerrainMgr.self.SetupTerrain (scene); CameraControl.SetupCamera (scene); EditorCtrl.self.SceneIsLoaded (scene); state = State.Main; if (background) background.SetActive (true); } } else { if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Start new game", styleDarkNormal, styleDarkOver)) { scenes = Scene.ListAvailableScenarios (); state = State.LoadNew; } if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Continue existing game", styleDarkNormal, styleDarkOver)) { saveGames = Scene.ListSaveGames (); state = State.Continue1; } } if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Settings", styleDarkNormal, styleDarkOver)) { scenePath = GameSettings.ScenePath; savePath = GameSettings.SaveGamesPath; state = State.Settings; } if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Quit", styleDarkNormal, styleDarkOver)) { Application.Quit (); } if (Application.isEditor || GameSettings.ALLOW_EDITOR && (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift))) { if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Editor", styleDarkNormal, styleDarkOver)) { Application.LoadLevelAsync ("Editor"); state = State.Idle; SimpleSpinner.ActivateSpinner (); } } // Export button /*if (scene != null && scene.exporter.exportEnabled) { if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Export data...", styleDarkNormal, styleDarkOver)) { scene.exporter.ExportCurrentData (); } }*/ } private string scenePath; private string savePath; void Settings (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back", styleDarkNormal, styleDarkOver)) { state = State.Main; } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Scene path", styleDarkNormal); scenePath = SimpleGUI.TextField (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 361, 32), scenePath, styleLightNormalLeft); if (SimpleGUI.Button (new Rect (xOffset + hwidth + 181, hheight + 33 * index, 64, 32), "Set", styleDarkNormal, styleDarkOver)) { GameSettings.ScenePath = scenePath; scenePath = GameSettings.ScenePath; } if (SimpleGUI.Button (new Rect (xOffset + hwidth + 246, hheight + 33 * index, 64, 32), "Reset", styleDarkNormal, styleDarkOver)) { GameSettings.ScenePath = GameSettings.DefaultScenePath; scenePath = GameSettings.ScenePath; } index++; SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Save path", styleDarkNormal); savePath = SimpleGUI.TextField (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 361, 32), savePath, styleLightNormalLeft); if (SimpleGUI.Button (new Rect (xOffset + hwidth + 181, hheight + 33 * index, 64, 32), "Set", styleDarkNormal, styleDarkOver)) { GameSettings.SaveGamesPath = savePath; savePath = GameSettings.SaveGamesPath; } if (SimpleGUI.Button (new Rect (xOffset + hwidth + 246, hheight + 33 * index, 64, 32), "Reset", styleDarkNormal, styleDarkOver)) { GameSettings.SaveGamesPath = GameSettings.DefaultSaveGamesPath; savePath = GameSettings.SaveGamesPath; } index++; SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Graphics", styleDarkNormal); int quality = QualitySettings.GetQualityLevel (); int newQuality = (int)SimpleGUI.Slider (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 361, 32), quality, 0, 5); if (newQuality != quality) { QualitySettings.SetQualityLevel (newQuality); TerrainMgr.self.UpdateQualitySettings (); } SimpleGUI.Label (new Rect (xOffset + hwidth + 181, hheight + 33 * index, 64, 32), QualitySettings.names [quality], styleDarkNormal); if (SimpleGUI.Button (new Rect (xOffset + hwidth + 246, hheight + 33 * index, 64, 32), "Reset", styleDarkNormal, styleDarkOver)) { QualitySettings.SetQualityLevel (defaultQuality); TerrainMgr.self.UpdateQualitySettings (); } index++; } Scene[] scenes; SaveGame[] saveGames; Scene loadScene; PlayerInfo player; IEnumerator COLoadGame (int slotNr) { state = State.Idle; SimpleSpinner.ActivateSpinner (); scene = null; yield return 0; try { scene = Scene.StartNewGame (loadScene.sceneName, slotNr, player); } catch (System.Exception e) { Log.LogException (e); } yield return 0; TerrainMgr.self.SetupTerrain (scene); CameraControl.SetupCamera (scene); EditorCtrl.self.SceneIsLoaded (scene); //if (background) background.SetActive (false); yield return 0; SimpleSpinner.DeactivateSpinner (); if (scene != null) { state = State.Idle; enabled = false; GameControl.ActivateGameControl (scene); scene.InitActions (true); scene.InitReports (true); GameControl.InterfaceChanged (); } else { state = State.Main; } } IEnumerator COContinueGame (int slotNr) { state = State.Idle; SimpleSpinner.ActivateSpinner (); scene = null; yield return 0; try { scene = Scene.LoadExistingGame (slotNr); } catch (System.Exception e) { Log.LogException (e); } yield return 0; TerrainMgr.self.SetupTerrain (scene); CameraControl.SetupCamera (scene); EditorCtrl.self.SceneIsLoaded (scene); //if (background) background.SetActive (false); yield return 0; SimpleSpinner.DeactivateSpinner (); if (scene != null) { state = State.Idle; enabled = false; GameControl.ActivateGameControl (scene); scene.InitActions (false); scene.InitReports (false); GameControl.InterfaceChanged (); } else { state = State.Main; } } void Continue1 (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back", styleDarkNormal, styleDarkOver)) { state = State.Main; } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Continue existing game", styleLightNormal); int x = 0; int slotNr = 0; foreach (SaveGame s in saveGames) { string slotName = (s == null) ? "<Empty>" : (s.sceneName + '\n' + "<size=12>" + s.playerInfo.firstName + ' ' + s.playerInfo.familyName + '\n' + s.date.ToString ("HH:mm dd-MM-yyyy") + "</size>"); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), slotName, styleDarkNormal, styleDarkOver)) { // scene = Scene.StartNewGame (loadScene.sceneName, slotNr, player); StartCoroutine (COContinueGame (slotNr)); } slotNr++; x ++; if (x > 2) { index += 2; x = 0; } } while (x > 0) { SimpleGUI.Label (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), "", styleDarkNormal); if (x > 2) { index += 2; x = 0; } } } void StartNewGame3 (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back", styleDarkNormal, styleDarkOver)) { state = State.LoadNew2; } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Save game slot", styleLightNormal); int x = 0; int slotNr = 0; foreach (SaveGame s in saveGames) { string slotName = (s == null) ? "<Empty>" : (s.sceneName + '\n' + "<size=12>" + s.playerInfo.firstName + ' ' + s.playerInfo.familyName + '\n' + s.date.ToString ("HH:mm dd-MM-yyyy") + "</size>"); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), slotName, styleDarkNormal, styleDarkOver)) { // scene = Scene.StartNewGame (loadScene.sceneName, slotNr, player); StartCoroutine (COLoadGame (slotNr)); } slotNr++; x ++; if (x > 2) { index += 2; x = 0; } } while (x > 0) { SimpleGUI.Label (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), "", styleDarkNormal); if (x > 2) { index += 2; x = 0; } } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Pick a game slot to automatically save your game at the start of each new year.", styleLightNormal); //"Progress is automatically saved at the start of each year.", styleLightNormal); } void StartNewGame2 (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back", styleDarkNormal, styleDarkOver)) { state = State.LoadNew; } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "What's your name?", styleLightNormal); SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Given name", styleLightNormal); player.firstName = SimpleGUI.TextField (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 491, 32), player.firstName, styleDarkNormalLeft); index ++; SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Family name", styleLightNormal); player.familyName = SimpleGUI.TextField (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 491, 32), player.familyName, styleDarkNormalLeft); index ++; SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index, 128, 32), "Gender", styleLightNormal); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 181, hheight + 33 * index, 245, 32), "Male", player.isMale ? styleDarkOver : styleDarkNormal, styleDarkOver)) { player.isMale = true; } if (SimpleGUI.Button (new Rect (xOffset + hwidth + 65, hheight + 33 * index, 245, 32), "Female", player.isMale ? styleDarkNormal : styleDarkOver, styleDarkOver)) { player.isMale = false; } index++; if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Continue", styleDarkNormal, styleDarkOver)) { saveGames = Scene.ListSaveGames (); state = State.LoadNew3; PlayerPrefs.SetString ("PlayerFirstName", player.firstName); PlayerPrefs.SetString ("PlayerFamilyName", player.familyName); PlayerPrefs.SetString ("PlayerGender", player.isMale ? "M" : "F"); } } void StartNewGame (int mx, int my) { int hheight = sHeight / 2; int hwidth = sWidth / 2; int index = -3; RenderBanner (index); if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Back", styleDarkNormal, styleDarkOver)) { state = State.Main; } SimpleGUI.Label (new Rect (xOffset + hwidth - 310, hheight + 33 * index++, 620, 32), "Choose a game", styleLightNormal); int x = 0; foreach (Scene s in scenes) { if (SimpleGUI.Button (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), s.sceneName, styleDarkNormal, styleDarkOver)) { loadScene = s; state = State.LoadNew2; } x ++; if (x > 2) { index += 2; x = 0; } } while (x > 0) { SimpleGUI.Label (new Rect (xOffset + hwidth - 310 + 207 * x, hheight + 33 * index, 206, 65), "", styleDarkNormal); x++; if (x > 2) { index += 2; x = 0; } } } void OnGUI () { if (state == State.Idle || !show) return; sWidth = Screen.width; sHeight = Screen.height; if (EditorCtrl.self.isOpen) { xOffset = 400; sWidth -= 400; } else { xOffset = 0; } Vector2 mousePos = Input.mousePosition; int mx = (int)mousePos.x; int my = sHeight - (int)mousePos.y; switch (state) { case State.Main : MainCtrl (mx, my); break; case State.LoadNew : StartNewGame (mx, my); break; case State.LoadNew2 : StartNewGame2 (mx, my); break; case State.LoadNew3 : StartNewGame3 (mx, my); break; case State.Continue1 : Continue1 (mx, my); break; case State.Settings : Settings (mx, my); break; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Globalization { public partial class CompareInfo { // ICU uses a char* (UTF-8) to represent a locale name. private readonly byte[] m_sortNameAsUtf8; internal unsafe CompareInfo(CultureInfo culture) { m_name = culture.m_name; m_sortName = culture.SortName; m_sortNameAsUtf8 = System.Text.Encoding.UTF8.GetBytes(m_sortName); } internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); if (value.Length == 0) { return startIndex; } // TODO (dotnet/corefx#3468): Move this into the shim so we don't have to do the ToUpper or call substring. if (ignoreCase) { source = source.ToUpper(CultureInfo.InvariantCulture); value = value.ToUpper(CultureInfo.InvariantCulture); } source = source.Substring(startIndex, count); for (int i = 0; i + value.Length <= source.Length; i++) { for (int j = 0; j < value.Length; j++) { if (source[i + j] != value[j]) { break; } if (j == value.Length - 1) { return i + startIndex; } } } return -1; } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); if (value.Length == 0) { return startIndex; } // TODO (dotnet/corefx#3468): Move this into the shim so we don't have to do the ToUpper or call substring. if (ignoreCase) { source = source.ToUpper(CultureInfo.InvariantCulture); value = value.ToUpper(CultureInfo.InvariantCulture); } source = source.Substring(startIndex - count + 1, count); int last = -1; int cur = 0; while ((cur = IndexOfOrdinal(source, value, last + 1, source.Length - last - 1, false)) != -1) { last = cur; } return last >= 0 ? last + startIndex - count + 1 : -1; } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0); } [System.Security.SecuritySafeCritical] private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2); } [System.Security.SecuritySafeCritical] private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Contract.Assert(string1 != null); Contract.Assert(string2 != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); fixed (char* pString1 = string1) { fixed (char* pString2 = string2) { return Interop.GlobalizationInterop.CompareString(m_sortNameAsUtf8, pString1 + offset1, length1, pString2 + offset2, length2, options); } } } [System.Security.SecuritySafeCritical] private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { return startIndex; } if (options == CompareOptions.Ordinal) { return IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false); } fixed (char* pSource = source) { int lastIndex = Interop.GlobalizationInterop.IndexOf(m_sortNameAsUtf8, target, pSource + startIndex, count, options); return lastIndex != -1 ? lastIndex + startIndex : -1; } } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { return startIndex; } if (options == CompareOptions.Ordinal) { return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false); } // startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source // of the start of the string that is count characters away from startIndex. int leftStartIndex = (startIndex - count + 1); fixed (char* pSource = source) { int lastIndex = Interop.GlobalizationInterop.LastIndexOf(m_sortNameAsUtf8, target, pSource + (startIndex - count + 1), count, options); return lastIndex != -1 ? lastIndex + leftStartIndex : -1; } } private bool StartsWith(string source, string prefix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(prefix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.GlobalizationInterop.StartsWith(m_sortNameAsUtf8, prefix, source, source.Length, options); } private bool EndsWith(string source, string suffix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(suffix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.GlobalizationInterop.EndsWith(m_sortNameAsUtf8, suffix, source, source.Length, options); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, null, 0, options); // As an optimization, for small sort keys we allocate the buffer on the stack. if (sortKeyLength <= 256) { byte* pSortKey = stackalloc byte[sortKeyLength]; Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, pSortKey, sortKeyLength, options); return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy); } byte[] sortKey = new byte[sortKeyLength]; fixed(byte* pSortKey = sortKey) { Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, pSortKey, sortKeyLength, options); return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy); } } [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy); } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.IO; using Soomla; using Soomla.Profile; using Soomla.Example; /// <summary> /// This class contains functions that initialize the game and that display the different screens of the game. /// </summary> public class ExampleWindow : MonoBehaviour { private static ExampleWindow instance = null; public string fontSuffix = ""; private static bool isVisible = false; private bool isInit = false; private Provider targetProvider = Provider.GOOGLE; private Reward exampleReward = new BadgeReward("example_reward", "Example Social Reward"); /// <summary> /// Initializes the game state before the game starts. /// </summary> void Awake(){ if(instance == null){ //making sure we only initialize one instance. instance = this; GameObject.DontDestroyOnLoad(this.gameObject); } else { //Destroying unused instances. GameObject.Destroy(this); } //FONT //using max to be certain we have the longest side of the screen, even if we are in portrait. if(Mathf.Max(Screen.width, Screen.height) > 640){ fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original } } private Texture2D tBackground; private Texture2D tShed; private Texture2D tBGBar; private Texture2D tShareDisable; private Texture2D tShare; private Texture2D tSharePress; private Texture2D tShareStoryDisable; private Texture2D tShareStory; private Texture2D tShareStoryPress; private Texture2D tUploadDisable; private Texture2D tUpload; private Texture2D tUploadPress; private Texture2D tConnect; private Texture2D tConnectPress; private Texture2D tLogout; private Texture2D tLogoutPress; private Font fgoodDog; // private bool bScreenshot = false; /// <summary> /// Starts this instance. /// Use this for initialization. /// </summary> void Start () { fgoodDog = (Font)Resources.Load("Fonts/GoodDog" + fontSuffix); tBackground = (Texture2D)Resources.Load("Profile/BG"); tShed = (Texture2D)Resources.Load("Profile/Headline"); tBGBar = (Texture2D)Resources.Load("Profile/BG-Bar"); tShareDisable = (Texture2D)Resources.Load("Profile/BTN-Share-Disable"); tShare = (Texture2D)Resources.Load("Profile/BTN-Share-Normal"); tSharePress = (Texture2D)Resources.Load("Profile/BTN-Share-Press"); tShareStoryDisable = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Disable"); tShareStory = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Normal"); tShareStoryPress = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Press"); tUploadDisable = (Texture2D)Resources.Load("Profile/BTN-Upload-Disable"); tUpload = (Texture2D)Resources.Load("Profile/BTN-Upload-Normal"); tUploadPress = (Texture2D)Resources.Load("Profile/BTN-Upload-Press"); tConnect = (Texture2D)Resources.Load("Profile/BTN-Connect"); tConnectPress = (Texture2D)Resources.Load("Profile/BTN-Connect-Press"); tLogout = (Texture2D)Resources.Load("Profile/BTN-LogOut"); tLogoutPress = (Texture2D)Resources.Load("Profile/BTN-LogOut-Press"); // examples of catching fired events ProfileEvents.OnSoomlaProfileInitialized += () => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "SoomlaProfile Initialized !"); isInit = true; }; ProfileEvents.OnUserRatingEvent += () => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "User opened rating page"); }; ProfileEvents.OnLoginFinished += (UserProfile UserProfile, string payload) => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "login finished for: " + UserProfile.toJSONObject().print()); SoomlaProfile.GetContacts(targetProvider); }; ProfileEvents.OnGetContactsFinished += (Provider provider, SocialPageData<UserProfile> contactsData, string payload) => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "get contacts for: " + contactsData.PageData.Count + " page: " + contactsData.PageNumber + " More? " + contactsData.HasMore); foreach (var profile in contactsData.PageData) { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "Contact: " + profile.toJSONObject().print()); } if (contactsData.HasMore) { SoomlaProfile.GetContacts(targetProvider); } }; SoomlaProfile.Initialize(); // SoomlaProfile.OpenAppRatingPage(); #if UNITY_IPHONE Handheld.SetActivityIndicatorStyle(UnityEngine.iOS.ActivityIndicatorStyle.Gray); #elif UNITY_ANDROID Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small); #endif } /// <summary> /// Sets the window to open, and sets the GUI state to welcome. /// </summary> public static void OpenWindow(){ isVisible = true; } /// <summary> /// Sets the window to closed. /// </summary> public static void CloseWindow(){ isVisible = false; } /// <summary> /// Implements the game behavior of MuffinRush. /// Overrides the superclass function in order to provide functionality for our game. /// </summary> void Update () { if (Application.platform == RuntimePlatform.Android) { if (Input.GetKeyUp(KeyCode.Escape)) { //quit application on back button Application.Quit(); return; } } } /// <summary> /// Calls the relevant function to display the correct screen of the game. /// </summary> void OnGUI(){ if(!isVisible){ return; } GUI.skin.horizontalScrollbar = GUIStyle.none; GUI.skin.verticalScrollbar = GUIStyle.none; welcomeScreen(); } /// <summary> /// Displays the welcome screen of the game. /// </summary> void welcomeScreen() { Color backupColor = GUI.color; float vertGap = 80f; //drawing background, just using a white pixel here GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tBackground); GUI.DrawTexture(new Rect(0,0,Screen.width,timesH(240f)), tShed, ScaleMode.StretchToFill, true); float rowsTop = 300.0f; float rowsHeight = 120.0f; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tShare; GUI.skin.button.hover.background = tShare; GUI.skin.button.active.background = tSharePress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ SoomlaProfile.UpdateStatus(targetProvider, "I LOVE SOOMLA ! http://www.soom.la", null, exampleReward); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 30; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"I Love SOOMLA!"); GUI.color = backupColor; rowsTop += vertGap + rowsHeight; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tShareStory; GUI.skin.button.hover.background = tShareStory; GUI.skin.button.active.background = tShareStoryPress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ SoomlaProfile.UpdateStory(targetProvider, "The story of SOOMBOT (Profile Test App)", "The story of SOOMBOT (Profile Test App)", "SOOMBOT Story", "DESCRIPTION", "http://about.soom.la/soombots", "http://about.soom.la/wp-content/uploads/2014/05/330x268-spockbot.png", null, exampleReward); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareStoryDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 25; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Full story of The SOOMBOT!"); GUI.color = backupColor; rowsTop += vertGap + rowsHeight; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tUpload; GUI.skin.button.hover.background = tUpload; GUI.skin.button.active.background = tUploadPress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ // string fileName = "soom.jpg"; // string path = ""; // // #if UNITY_IOS // path = Application.dataPath + "/Raw/" + fileName; // #elif UNITY_ANDROID // path = "jar:file://" + Application.dataPath + "!/assets/" + fileName; // #endif // // byte[] bytes = File.ReadAllBytes(path); // SoomlaProfile.UploadImage(targetProvider, "Awesome Test App of SOOMLA Profile!", fileName, bytes, 10, null, exampleReward); SoomlaProfile.UploadCurrentScreenShot(this, targetProvider, "Awesome Test App of SOOMLA Profile!", "This a screenshot of the current state of SOOMLA's test app on my computer.", null); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tUploadDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 28; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Current Screenshot"); GUI.color = backupColor; if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tLogout; GUI.skin.button.hover.background = tLogout; GUI.skin.button.active.background = tLogoutPress; if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){ SoomlaProfile.Logout(targetProvider); } } else if (isInit) { GUI.skin.button.normal.background = tConnect; GUI.skin.button.hover.background = tConnect; GUI.skin.button.active.background = tConnectPress; if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){ SoomlaProfile.Login(targetProvider, null, exampleReward); } } } private static string ScreenShotName(int width, int height) { return string.Format("{0}/screen_{1}x{2}_{3}.png", Application.persistentDataPath, width, height, System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")); } private float timesW(float f) { return (float)(f/640.0)*Screen.width; } private float timesH(float f) { return (float)(f/1136.0)*Screen.height; } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.SS.UserModel; using System.Collections.Generic; using System; using NUnit.Framework; using NPOI.HSSF.UserModel; namespace TestCases.SS.UserModel { /** * Tests of implementation of {@link DataFormat} * */ public class BaseTestDataFormat { protected ITestDataProvider _testDataProvider; public BaseTestDataFormat() : this(TestCases.HSSF.HSSFITestDataProvider.Instance) { } /** * @param testDataProvider an object that provides test data in HSSF / XSSF specific way */ protected BaseTestDataFormat(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } public void AssertNotBuiltInFormat(String customFmt) { //check it is not in built-in formats Assert.AreEqual(-1, BuiltinFormats.GetBuiltinFormat(customFmt)); } [Test] public void TestBuiltinFormats() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IDataFormat df = wb.CreateDataFormat(); List<String> formats = HSSFDataFormat.GetBuiltinFormats(); for (int idx = 0; idx < formats.Count; idx++) { String fmt = formats[idx]; Assert.AreEqual(idx, df.GetFormat(fmt)); } //default format for new cells is General ISheet sheet = wb.CreateSheet(); ICell cell = sheet.CreateRow(0).CreateCell(0); Assert.AreEqual(0, cell.CellStyle.DataFormat); Assert.AreEqual("General", cell.CellStyle.GetDataFormatString()); //create a custom data format String customFmt = "#0.00 AM/PM"; //check it is not in built-in formats AssertNotBuiltInFormat(customFmt); int customIdx = df.GetFormat(customFmt); //The first user-defined format starts at 164. Assert.IsTrue(customIdx >= HSSFDataFormat.FIRST_USER_DEFINED_FORMAT_INDEX); //read and verify the string representation Assert.AreEqual(customFmt, df.GetFormat((short)customIdx)); wb.Close(); } /** * [Bug 49928] formatCellValue returns incorrect value for \u00a3 formatted cells */ public virtual void Test49928() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook("49928.xls"); DoTest49928Core(wb); } protected String poundFmt = "\"\u00a3\"#,##0;[Red]\\-\"\u00a3\"#,##0"; public void DoTest49928Core(IWorkbook wb) { DataFormatter df = new DataFormatter(); ISheet sheet = wb.GetSheetAt(0); ICell cell = sheet.GetRow(0).GetCell(0); ICellStyle style = cell.CellStyle; // not expected normally, id of a custom format should be greater // than BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX short poundFmtIdx = 6; Assert.AreEqual(poundFmt, style.GetDataFormatString()); Assert.AreEqual(poundFmtIdx, style.DataFormat); Assert.AreEqual("\u00a31", df.FormatCellValue(cell)); IDataFormat dataFormat = wb.CreateDataFormat(); Assert.AreEqual(poundFmtIdx, dataFormat.GetFormat(poundFmt)); Assert.AreEqual(poundFmt, dataFormat.GetFormat(poundFmtIdx)); } [Test] public void TestReadbackFormat() { ReadbackFormat("built-in format", "0.00"); ReadbackFormat("overridden built-in format", poundFmt); String customFormat = "#0.00 AM/PM"; AssertNotBuiltInFormat(customFormat); ReadbackFormat("custom format", customFormat); } private void ReadbackFormat(String msg, String fmt) { IWorkbook wb = _testDataProvider.CreateWorkbook(); try { IDataFormat dataFormat = wb.CreateDataFormat(); short fmtIdx = dataFormat.GetFormat(fmt); String readbackFmt = dataFormat.GetFormat(fmtIdx); Assert.AreEqual(fmt, readbackFmt, msg); } finally { wb.Close(); } } public void DoTest58532Core(IWorkbook wb) { ISheet s = wb.GetSheetAt(0); DataFormatter fmt = new DataFormatter(); IFormulaEvaluator eval = wb.GetCreationHelper().CreateFormulaEvaluator(); // Column A is the raw values // Column B is the ##/#K/#M values // Column C is strings of what they should look like // Column D is the #.##/#.#K/#.#M values // Column E is strings of what they should look like String formatKMWhole = "[>999999]#,,\"M\";[>999]#,\"K\";#"; String formatKM3dp = "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000"; // Check the formats are as expected IRow headers = s.GetRow(0); Assert.IsNotNull(headers); Assert.AreEqual(formatKMWhole, headers.GetCell(1).StringCellValue); Assert.AreEqual(formatKM3dp, headers.GetCell(3).StringCellValue); IRow r2 = s.GetRow(1); Assert.IsNotNull(r2); Assert.AreEqual(formatKMWhole, r2.GetCell(1).CellStyle.GetDataFormatString()); Assert.AreEqual(formatKM3dp, r2.GetCell(3).CellStyle.GetDataFormatString()); // For all of the contents rows, check that DataFormatter is able // to format the cells to the same value as the one next to it for (int rn = 1; rn < s.LastRowNum; rn++) { IRow r = s.GetRow(rn); if (r == null) break; double value = r.GetCell(0).NumericCellValue; String expWhole = r.GetCell(2).StringCellValue; String exp3dp = r.GetCell(4).StringCellValue; Assert.AreEqual(expWhole, fmt.FormatCellValue(r.GetCell(1), eval), "Wrong formatting of " + value + " for row " + rn); Assert.AreEqual(exp3dp, fmt.FormatCellValue(r.GetCell(3), eval), "Wrong formatting of " + value + " for row " + rn); } } /** * Localised accountancy formats */ [Test] public void Test58536() { IWorkbook wb = _testDataProvider.CreateWorkbook(); DataFormatter formatter = new DataFormatter(); IDataFormat fmt = wb.CreateDataFormat(); ISheet sheet = wb.CreateSheet(); IRow r = sheet.CreateRow(0); char pound = '\u00A3'; String formatUK = "_-[$" + pound + "-809]* #,##0_-;\\-[$" + pound + "-809]* #,##0_-;_-[$" + pound + "-809]* \"-\"??_-;_-@_-"; ICellStyle cs = wb.CreateCellStyle(); cs.DataFormat = (fmt.GetFormat(formatUK)); ICell pve = r.CreateCell(0); pve.SetCellValue(12345); pve.CellStyle = (cs); ICell nve = r.CreateCell(1); nve.SetCellValue(-12345); nve.CellStyle = (cs); ICell zero = r.CreateCell(2); zero.SetCellValue(0); zero.CellStyle = (cs); Assert.AreEqual(pound + " 12,345", formatter.FormatCellValue(pve)); Assert.AreEqual("-" + pound + " 12,345", formatter.FormatCellValue(nve)); // TODO Fix this to not have an extra 0 at the end //assertEquals(pound+" - ", formatter.formatCellValue(zero)); wb.Close(); } /** * Using a single quote (') instead of a comma (,) as * a number separator, eg 1000 -> 1'000 */ [Test] public void Test55265() { IWorkbook wb = _testDataProvider.CreateWorkbook(); try { DataFormatter formatter = new DataFormatter(); IDataFormat fmt = wb.CreateDataFormat(); ISheet sheet = wb.CreateSheet(); IRow r = sheet.CreateRow(0); ICellStyle cs = wb.CreateCellStyle(); cs.DataFormat = (fmt.GetFormat("#'##0")); ICell zero = r.CreateCell(0); zero.SetCellValue(0); zero.CellStyle = (cs); ICell sml = r.CreateCell(1); sml.SetCellValue(12); sml.CellStyle = (cs); ICell med = r.CreateCell(2); med.SetCellValue(1234); med.CellStyle = (cs); ICell lge = r.CreateCell(3); lge.SetCellValue(12345678); lge.CellStyle = (cs); Assert.AreEqual("0", formatter.FormatCellValue(zero)); Assert.AreEqual("12", formatter.FormatCellValue(sml)); Assert.AreEqual("1'234", formatter.FormatCellValue(med)); Assert.AreEqual("12'345'678", formatter.FormatCellValue(lge)); } finally { wb.Close(); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="IncomeRangeViewServiceClient"/> instances.</summary> public sealed partial class IncomeRangeViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="IncomeRangeViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="IncomeRangeViewServiceSettings"/>.</returns> public static IncomeRangeViewServiceSettings GetDefault() => new IncomeRangeViewServiceSettings(); /// <summary> /// Constructs a new <see cref="IncomeRangeViewServiceSettings"/> object with default settings. /// </summary> public IncomeRangeViewServiceSettings() { } private IncomeRangeViewServiceSettings(IncomeRangeViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetIncomeRangeViewSettings = existing.GetIncomeRangeViewSettings; OnCopy(existing); } partial void OnCopy(IncomeRangeViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IncomeRangeViewServiceClient.GetIncomeRangeView</c> and /// <c>IncomeRangeViewServiceClient.GetIncomeRangeViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetIncomeRangeViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="IncomeRangeViewServiceSettings"/> object.</returns> public IncomeRangeViewServiceSettings Clone() => new IncomeRangeViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="IncomeRangeViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class IncomeRangeViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<IncomeRangeViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public IncomeRangeViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public IncomeRangeViewServiceClientBuilder() { UseJwtAccessWithScopes = IncomeRangeViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref IncomeRangeViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IncomeRangeViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override IncomeRangeViewServiceClient Build() { IncomeRangeViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<IncomeRangeViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<IncomeRangeViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private IncomeRangeViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return IncomeRangeViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<IncomeRangeViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return IncomeRangeViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => IncomeRangeViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => IncomeRangeViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => IncomeRangeViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>IncomeRangeViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage income range views. /// </remarks> public abstract partial class IncomeRangeViewServiceClient { /// <summary> /// The default endpoint for the IncomeRangeViewService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default IncomeRangeViewService scopes.</summary> /// <remarks> /// The default IncomeRangeViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="IncomeRangeViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="IncomeRangeViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="IncomeRangeViewServiceClient"/>.</returns> public static stt::Task<IncomeRangeViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new IncomeRangeViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="IncomeRangeViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="IncomeRangeViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="IncomeRangeViewServiceClient"/>.</returns> public static IncomeRangeViewServiceClient Create() => new IncomeRangeViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="IncomeRangeViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="IncomeRangeViewServiceSettings"/>.</param> /// <returns>The created <see cref="IncomeRangeViewServiceClient"/>.</returns> internal static IncomeRangeViewServiceClient Create(grpccore::CallInvoker callInvoker, IncomeRangeViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } IncomeRangeViewService.IncomeRangeViewServiceClient grpcClient = new IncomeRangeViewService.IncomeRangeViewServiceClient(callInvoker); return new IncomeRangeViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC IncomeRangeViewService client</summary> public virtual IncomeRangeViewService.IncomeRangeViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::IncomeRangeView GetIncomeRangeView(GetIncomeRangeViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(GetIncomeRangeViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(GetIncomeRangeViewRequest request, st::CancellationToken cancellationToken) => GetIncomeRangeViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::IncomeRangeView GetIncomeRangeView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetIncomeRangeView(new GetIncomeRangeViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetIncomeRangeViewAsync(new GetIncomeRangeViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetIncomeRangeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::IncomeRangeView GetIncomeRangeView(gagvr::IncomeRangeViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetIncomeRangeView(new GetIncomeRangeViewRequest { ResourceNameAsIncomeRangeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(gagvr::IncomeRangeViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetIncomeRangeViewAsync(new GetIncomeRangeViewRequest { ResourceNameAsIncomeRangeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the income range view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(gagvr::IncomeRangeViewName resourceName, st::CancellationToken cancellationToken) => GetIncomeRangeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>IncomeRangeViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage income range views. /// </remarks> public sealed partial class IncomeRangeViewServiceClientImpl : IncomeRangeViewServiceClient { private readonly gaxgrpc::ApiCall<GetIncomeRangeViewRequest, gagvr::IncomeRangeView> _callGetIncomeRangeView; /// <summary> /// Constructs a client wrapper for the IncomeRangeViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="IncomeRangeViewServiceSettings"/> used within this client. /// </param> public IncomeRangeViewServiceClientImpl(IncomeRangeViewService.IncomeRangeViewServiceClient grpcClient, IncomeRangeViewServiceSettings settings) { GrpcClient = grpcClient; IncomeRangeViewServiceSettings effectiveSettings = settings ?? IncomeRangeViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetIncomeRangeView = clientHelper.BuildApiCall<GetIncomeRangeViewRequest, gagvr::IncomeRangeView>(grpcClient.GetIncomeRangeViewAsync, grpcClient.GetIncomeRangeView, effectiveSettings.GetIncomeRangeViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetIncomeRangeView); Modify_GetIncomeRangeViewApiCall(ref _callGetIncomeRangeView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetIncomeRangeViewApiCall(ref gaxgrpc::ApiCall<GetIncomeRangeViewRequest, gagvr::IncomeRangeView> call); partial void OnConstruction(IncomeRangeViewService.IncomeRangeViewServiceClient grpcClient, IncomeRangeViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC IncomeRangeViewService client</summary> public override IncomeRangeViewService.IncomeRangeViewServiceClient GrpcClient { get; } partial void Modify_GetIncomeRangeViewRequest(ref GetIncomeRangeViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::IncomeRangeView GetIncomeRangeView(GetIncomeRangeViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetIncomeRangeViewRequest(ref request, ref callSettings); return _callGetIncomeRangeView.Sync(request, callSettings); } /// <summary> /// Returns the requested income range view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::IncomeRangeView> GetIncomeRangeViewAsync(GetIncomeRangeViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetIncomeRangeViewRequest(ref request, ref callSettings); return _callGetIncomeRangeView.Async(request, callSettings); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Reflection; using System.Text.RegularExpressions; using System.Text; using NUnit.Framework.Api; using NUnit.Framework.Internal; using NUnit.Framework.Extensibility; namespace NUnit.Framework.Builders { /// <summary> /// Built-in SuiteBuilder for NUnit TestFixture /// </summary> public class NUnitTestFixtureBuilder : ISuiteBuilder { #region Static Fields static readonly string NO_TYPE_ARGS_MSG = "Fixture type contains generic parameters. You must either provide " + "Type arguments or specify constructor arguments that allow NUnit " + "to deduce the Type arguments."; #endregion #region Instance Fields /// <summary> /// The NUnitTestFixture being constructed; /// </summary> private TestFixture fixture; #if NUNITLITE private Extensibility.ITestCaseBuilder2 testBuilder = new NUnitTestCaseBuilder(); #else private Extensibility.ITestCaseBuilder2 testBuilder = CoreExtensions.Host.TestBuilders; private Extensibility.ITestDecorator testDecorators = CoreExtensions.Host.TestDecorators; #endif #endregion #region ISuiteBuilder Methods /// <summary> /// Checks to see if the fixture type has the TestFixtureAttribute /// </summary> /// <param name="type">The fixture type to check</param> /// <returns>True if the fixture can be built, false if not</returns> public bool CanBuildFrom(Type type) { if ( type.IsAbstract && !type.IsSealed ) return false; if (type.IsDefined(typeof(TestFixtureAttribute), true)) return true; #if CLR_2_0 || CLR_4_0 // Generics must have a TestFixtureAttribute if (type.IsGenericTypeDefinition) return false; #endif return Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestAttribute), true) || Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseAttribute), true) || Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseSourceAttribute), true) || Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TheoryAttribute), true); } /// <summary> /// Build a TestSuite from type provided. /// </summary> /// <param name="type"></param> /// <returns></returns> public Test BuildFrom(Type type) { TestFixtureAttribute[] attrs = GetTestFixtureAttributes(type); #if CLR_2_0 || CLR_4_0 if (type.IsGenericType) return BuildMultipleFixtures(type, attrs); #endif switch (attrs.Length) { case 0: return BuildSingleFixture(type, null); case 1: object[] args = (object[])attrs[0].Arguments; return args == null || args.Length == 0 ? BuildSingleFixture(type, attrs[0]) : BuildMultipleFixtures(type, attrs); default: return BuildMultipleFixtures(type, attrs); } } #endregion #region Helper Methods private Test BuildMultipleFixtures(Type type, TestFixtureAttribute[] attrs) { TestSuite suite = new ParameterizedFixtureSuite(type); if (attrs.Length > 0) { foreach (TestFixtureAttribute attr in attrs) suite.Add(BuildSingleFixture(type, attr)); } else { suite.RunState = RunState.NotRunnable; suite.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); } return suite; } private Test BuildSingleFixture(Type type, TestFixtureAttribute attr) { object[] arguments = null; if (attr != null) { arguments = (object[])attr.Arguments; #if CLR_2_0 || CLR_4_0 if (type.ContainsGenericParameters) { Type[] typeArgs = (Type[])attr.TypeArgs; if( typeArgs.Length > 0 || TypeHelper.CanDeduceTypeArgsFromArgs(type, arguments, ref typeArgs)) { type = TypeHelper.MakeGenericType(type, typeArgs); } } #endif } this.fixture = new TestFixture(type, arguments); CheckTestFixtureIsValid(fixture); #if PORTABLE fixture.ApplyAttributesToTest(type.AsCustomAttributeProvider()); #else fixture.ApplyAttributesToTest(type); #endif if (fixture.RunState == RunState.Runnable && attr != null) { if (attr.Ignore) { fixture.RunState = RunState.Ignored; fixture.Properties.Set(PropertyNames.SkipReason, attr.IgnoreReason); } } AddTestCases(type); return this.fixture; } /// <summary> /// Method to add test cases to the newly constructed fixture. /// </summary> /// <param name="fixtureType"></param> private void AddTestCases( Type fixtureType ) { IList methods = fixtureType.GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static ); foreach(MethodInfo method in methods) { Test test = BuildTestCase(method, this.fixture); if(test != null) { this.fixture.Add( test ); } } } /// <summary> /// Method to create a test case from a MethodInfo and add /// it to the fixture being built. It first checks to see if /// any global TestCaseBuilder addin wants to build the /// test case. If not, it uses the internal builder /// collection maintained by this fixture builder. After /// building the test case, it applies any decorators /// that have been installed. /// /// The default implementation has no test case builders. /// Derived classes should add builders to the collection /// in their constructor. /// </summary> /// <param name="method">The MethodInfo for which a test is to be created</param> /// <param name="suite">The test suite being built.</param> /// <returns>A newly constructed Test</returns> private Test BuildTestCase( MethodInfo method, TestSuite suite ) { #if NUNITLITE return testBuilder.CanBuildFrom(method, suite) ? testBuilder.BuildFrom(method, suite) : null; #else Test test = testBuilder.BuildFrom( method, suite ); if ( test != null ) test = testDecorators.Decorate( test, method ); return test; #endif } private void CheckTestFixtureIsValid(TestFixture fixture) { Type fixtureType = fixture.FixtureType; #if CLR_2_0 || CLR_4_0 if (fixtureType.ContainsGenericParameters) { SetNotRunnable(fixture, NO_TYPE_ARGS_MSG); return; } #endif if( !IsStaticClass(fixtureType) && !HasValidConstructor(fixtureType, fixture.arguments) ) { SetNotRunnable(fixture, "No suitable constructor was found"); return; } if (!CheckSetUpTearDownMethods(fixture, fixture.SetUpMethods)) return; if (!CheckSetUpTearDownMethods(fixture, fixture.TearDownMethods)) return; if (!CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureSetUpAttribute), true))) return; CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureTearDownAttribute), true)); } private static bool HasValidConstructor(Type fixtureType, object[] args) { Type[] argTypes; // Note: This could be done more simply using // Type.EmptyTypes and Type.GetTypeArray() but // they don't exist in all runtimes we support. if (args == null) argTypes = new Type[0]; else { argTypes = new Type[args.Length]; int index = 0; foreach (object arg in args) argTypes[index++] = arg.GetType(); } return fixtureType.GetConstructor(argTypes) != null; } private void SetNotRunnable(TestFixture fixture, string reason) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, reason); } private static bool IsStaticClass(Type type) { return type.IsAbstract && type.IsSealed; } private bool CheckSetUpTearDownMethods(TestFixture fixture, MethodInfo[] methods) { foreach (MethodInfo method in methods) if (method.IsAbstract || !method.IsPublic && !method.IsFamily || method.GetParameters().Length > 0 || !method.ReturnType.Equals(typeof(void))) { SetNotRunnable(fixture, string.Format("Invalid signature for Setup or TearDown method: {0}", method.Name)); return false; } return true; } /// <summary> /// Get TestFixtureAttributes following a somewhat obscure /// set of rules to eliminate spurious duplication of fixtures. /// 1. If there are any attributes with args, they are the only /// ones returned and those without args are ignored. /// 2. No more than one attribute without args is ever returned. /// </summary> private TestFixtureAttribute[] GetTestFixtureAttributes(Type type) { TestFixtureAttribute[] attrs = (TestFixtureAttribute[])type.GetCustomAttributes(typeof(TestFixtureAttribute), true); // Just return - no possibility of duplication if (attrs.Length <= 1) return attrs; int withArgs = 0; bool[] hasArgs = new bool[attrs.Length]; // Count and record those attrs with arguments for (int i = 0; i < attrs.Length; i++) { TestFixtureAttribute attr = attrs[i]; if (attr.Arguments.Length > 0 || attr.TypeArgs.Length > 0) { withArgs++; hasArgs[i] = true; } } // If all attributes have args, just return them if (withArgs == attrs.Length) return attrs; // If all attributes are without args, just return the first found if (withArgs == 0) return new TestFixtureAttribute[] { attrs[0] }; // Some of each type, so extract those with args int count = 0; TestFixtureAttribute[] result = new TestFixtureAttribute[withArgs]; for (int i = 0; i < attrs.Length; i++) if (hasArgs[i]) result[count++] = attrs[i]; return result; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace MediaApp.Common { /// <summary> /// SuspensionManager captures global session state to simplify process lifetime management /// for an application. Note that session state will be automatically cleared under a variety /// of conditions and should only be used to store information that would be convenient to /// carry across sessions, but that should be discarded when an application crashes or is /// upgraded. /// </summary> internal sealed class SuspensionManager { private static Dictionary<string, object> _sessionState = new Dictionary<string, object>(); private static List<Type> _knownTypes = new List<Type>(); private const string sessionStateFilename = "_sessionState.xml"; /// <summary> /// Provides access to global session state for the current session. This state is /// serialized by <see cref="SaveAsync"/> and restored by /// <see cref="RestoreAsync"/>, so values must be serializable by /// <see cref="DataContractSerializer"/> and should be as compact as possible. Strings /// and other self-contained data types are strongly recommended. /// </summary> public static Dictionary<string, object> SessionState { get { return _sessionState; } } /// <summary> /// List of custom types provided to the <see cref="DataContractSerializer"/> when /// reading and writing session state. Initially empty, additional types may be /// added to customize the serialization process. /// </summary> public static List<Type> KnownTypes { get { return _knownTypes; } } /// <summary> /// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also preserve their current /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity /// to save its state. /// </summary> /// <returns>An asynchronous task that reflects when session state has been saved.</returns> public static async Task SaveAsync() { try { // Save the navigation state for all registered frames foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Serialize the session state synchronously to avoid asynchronous access to shared // state MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Get an output stream for the SessionState file and write the state asynchronously StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { sessionData.Seek(0, SeekOrigin.Begin); await sessionData.CopyToAsync(fileStream); } } catch (Exception e) { throw new SuspensionManagerException(e); } } /// <summary> /// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its /// state. /// </summary> /// <param name="sessionBaseKey">An optional key that identifies the type of session. /// This can be used to distinguish between multiple application launch scenarios.</param> /// <returns>An asynchronous task that reflects when session state has been read. The /// content of <see cref="SessionState"/> should not be relied upon until this task /// completes.</returns> public static async Task RestoreAsync(String sessionBaseKey = null) { _sessionState = new Dictionary<String, Object>(); try { // Get the input stream for the SessionState file StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // Deserialize the Session State DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // Restore any registered frames to their saved state foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } } private static DependencyProperty FrameSessionStateKeyProperty = DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null); private static DependencyProperty FrameSessionBaseKeyProperty = DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null); private static DependencyProperty FrameSessionStateProperty = DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null); private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>(); /// <summary> /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to /// and restored from <see cref="SessionState"/>. Frames should be registered once /// immediately after creation if they will participate in session state management. Upon /// registration if state has already been restored for the specified key /// the navigation history will immediately be restored. Subsequent invocations of /// <see cref="RestoreAsync"/> will also restore navigation history. /// </summary> /// <param name="frame">An instance whose navigation history should be managed by /// <see cref="SuspensionManager"/></param> /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to /// store navigation-related information.</param> /// <param name="sessionBaseKey">An optional key that identifies the type of session. /// This can be used to distinguish between multiple application launch scenarios.</param> public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null) { if (frame.GetValue(FrameSessionStateKeyProperty) != null) { throw new InvalidOperationException("Frames can only be registered to one session state key"); } if (frame.GetValue(FrameSessionStateProperty) != null) { throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all"); } if (!string.IsNullOrEmpty(sessionBaseKey)) { frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey); sessionStateKey = sessionBaseKey + "_" + sessionStateKey; } // Use a dependency property to associate the session key with a frame, and keep a list of frames whose // navigation state should be managed frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey); _registeredFrames.Add(new WeakReference<Frame>(frame)); // Check to see if navigation state can be restored RestoreFrameNavigationState(frame); } /// <summary> /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/> /// from <see cref="SessionState"/>. Any navigation state previously captured will be /// removed. /// </summary> /// <param name="frame">An instance whose navigation history should no longer be /// managed.</param> public static void UnregisterFrame(Frame frame) { // Remove session state and remove the frame from the list of frames whose navigation // state will be saved (along with any weak references that are no longer reachable) SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty)); _registeredFrames.RemoveAll((weakFrameReference) => { Frame testFrame; return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame; }); } /// <summary> /// Provides storage for session state associated with the specified <see cref="Frame"/>. /// Frames that have been previously registered with <see cref="RegisterFrame"/> have /// their session state saved and restored automatically as a part of the global /// <see cref="SessionState"/>. Frames that are not registered have transient state /// that can still be useful when restoring pages that have been discarded from the /// navigation cache. /// </summary> /// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage /// page-specific state instead of working with frame session state directly.</remarks> /// <param name="frame">The instance for which session state is desired.</param> /// <returns>A collection of state subject to the same serialization mechanism as /// <see cref="SessionState"/>.</returns> public static Dictionary<String, Object> SessionStateForFrame(Frame frame) { var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty); if (frameState == null) { var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty); if (frameSessionKey != null) { // Registered frames reflect the corresponding session state if (!_sessionState.ContainsKey(frameSessionKey)) { _sessionState[frameSessionKey] = new Dictionary<String, Object>(); } frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey]; } else { // Frames that aren't registered have transient state frameState = new Dictionary<String, Object>(); } frame.SetValue(FrameSessionStateProperty, frameState); } return frameState; } private static void RestoreFrameNavigationState(Frame frame) { var frameState = SessionStateForFrame(frame); if (frameState.ContainsKey("Navigation")) { frame.SetNavigationState((String)frameState["Navigation"]); } } private static void SaveFrameNavigationState(Frame frame) { var frameState = SessionStateForFrame(frame); frameState["Navigation"] = frame.GetNavigationState(); } } public class SuspensionManagerException : Exception { public SuspensionManagerException() { } public SuspensionManagerException(Exception e) : base("SuspensionManager failed", e) { } } }
using System; using MonoMac.Foundation; using dex.net; using System.Collections.Generic; using MonoMac.AppKit; using System.Collections; namespace DexMac { internal interface IDataSource { int GetChildrenCount (); NSObject GetObjectValue (); NSObject GetChild (int index); bool ItemExpandable (); } public class PackageModel : NSObject, IDataSource, IComparable<PackageModel> { internal string _package; internal List<ClassModel> _classes; internal BitArray _filter; public PackageModel (string packageName) { _package = packageName; _classes = new List<ClassModel> (); } public bool IsClassInPackage(Class dexClass) { var package = dexClass.Name.Substring(0, dexClass.Name.LastIndexOf('.')); return _package.Equals (package); } public void InitFilter () { _filter = new BitArray (_classes.Count, true); } #region IDataSource public int GetChildrenCount () { return _filter.TrueCount(); } public NSObject GetObjectValue () { return (NSString)_package; } public NSObject GetChild (int index) { return _classes [_filter.MapIndex(index)]; } public bool ItemExpandable () { return _filter.TrueCount() > 0; } #endregion #region IComparable<PackageModel> Members public int CompareTo(PackageModel p) { return _package.CompareTo(p._package); } #endregion } public class ClassModel : NSObject, IDataSource { internal Class _class; internal List<MethodModel> _methods; internal BitArray _filter; public ClassModel (Class dexClass) { _class = dexClass; _methods = new List<MethodModel> (); foreach (var method in _class.GetMethods ()) { _methods.Add(new MethodModel(dexClass, method)); } _filter = new BitArray (_methods.Count, true); } #region IDataSource public int GetChildrenCount () { return _filter.TrueCount(); } public NSObject GetObjectValue () { return (NSString)_class.Name.Substring(_class.Name.LastIndexOf('.')+1); } public NSObject GetChild (int index) { return _methods [_filter.MapIndex(index)]; } public bool ItemExpandable () { return _filter.TrueCount() > 0; } #endregion } public class MethodModel : NSObject, IDataSource { internal Class _class; internal Method _method; public MethodModel (Class dexClass, Method method) { _class = dexClass; _method = method; } #region IDataSource public int GetChildrenCount () { return 0; } public NSObject GetObjectValue () { return (NSString)_method.Name; } public NSObject GetChild (int index) { return null; } public bool ItemExpandable () { return false; } #endregion } public class DexDataSource : NSOutlineViewDataSource { public List<PackageModel> Packages { get; set; } private BitArray _filter = new BitArray(0); public DexDataSource() { Packages = new List<PackageModel> (); } public void SetData(Dex dex) { Packages.Clear (); var packages = new Dictionary<string, PackageModel>(); foreach (var dexClass in dex.GetClasses()) { var lastDotPosition = dexClass.Name.LastIndexOf ('.'); string packageName; if (lastDotPosition >= 0) { packageName = dexClass.Name.Substring (0, dexClass.Name.LastIndexOf ('.')); } else { packageName = "default"; } PackageModel package; if (!packages.TryGetValue (packageName, out package)) { package = new PackageModel(packageName); packages.Add (packageName, package); } package._classes.Add (new ClassModel (dexClass)); } Packages.AddRange (packages.Values); Packages.Sort (); _filter.Length = Packages.Count; _filter.SetAll (true); foreach (var packageModel in Packages) { packageModel.InitFilter (); } } public void SetFilter(string filter) { filter = filter.ToLower (); _filter.SetAll (false); var currentPackage = 0; foreach (var package in Packages) { if (package._package.ToLower().IndexOf(filter) >= 0) { _filter.Set (currentPackage, true); } package._filter.SetAll (false); var currentClass = 0; foreach (var clazz in package._classes) { if (clazz._class.Name.ToLower().IndexOf(filter) >= 0) { package._filter.Set (currentClass, true); _filter.Set (currentPackage, true); } clazz._filter.SetAll (false); var currentMethod = 0; foreach (var method in clazz._methods) { if (method._method.Name.ToLower().IndexOf(filter) >= 0) { clazz._filter.Set (currentMethod, true); package._filter.Set (currentClass, true); _filter.Set (currentPackage, true); } currentMethod++; } currentClass++; } currentPackage++; } } public void ResetFilter() { _filter.SetAll (true); foreach (var package in Packages) { package._filter.SetAll (true); foreach (var clazz in package._classes) { clazz._filter.SetAll (true); } } } public override int GetChildrenCount (NSOutlineView outlineView, NSObject item) { if (item == null) { return _filter.TrueCount(); } return (item as IDataSource).GetChildrenCount (); } public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn tableColumn, NSObject item) { if (item != null) { return (item as IDataSource).GetObjectValue (); } return (NSString)"Error!"; } public override NSObject GetChild (NSOutlineView outlineView, int index, NSObject item) { if (item == null) { return Packages [_filter.MapIndex(index)]; } else { return (item as IDataSource).GetChild (index); } } public override bool ItemExpandable (NSOutlineView outlineView, NSObject item) { if (item == null || item is MethodModel) return false; return (item as IDataSource).ItemExpandable (); } } public static class BitArrayExtensions { public static int TrueCount(this BitArray bitArray) { var count = 0; for (int i=0; i<bitArray.Count; i++) { if (bitArray [i]) { count++; } } return count; } public static int MapIndex(this BitArray bitArray, int index) { var count = 0; for (int i=0; i<bitArray.Count; i++) { if (bitArray [i]) { if (count == index) { return i; } count++; } } return -1; } } }
#region File Description //----------------------------------------------------------------------------- // Projectile.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace VectorRumble { /// <summary> /// Base class for all projectiles that exist in the game. /// </summary> abstract class Projectile : Actor { #region Fields /// <summary> /// The player who fired this projectile. /// </summary> protected Ship owner; /// <summary> /// The speed that the projectile will move at. /// </summary> protected float speed = 0f; /// <summary> /// The amount that this projectile hurts it's target and those around it. /// </summary> protected float damageAmount = 0f; /// <summary> /// The radius at which this projectile hurts other actors when it explodes. /// </summary> protected float damageRadius = 0f; /// <summary> /// The amount of time before this projectile dies on it's own. /// </summary> protected float duration = 0f; /// <summary> /// If true, this object will damage it's owner if it hits it /// </summary> protected bool damageOwner = true; /// <summary> /// If true, this object explodes - calling Explode() - when it dies. /// </summary> protected bool explodes = false; /// <summary> /// The colors used in the particle system shown when this projectile hits. /// </summary> protected Color[] explosionColors; #endregion #region Properties public Ship Owner { get { return owner; } } #endregion #region Initialization /// <summary> /// Constructs a new projectile. /// </summary> /// <param name="world">The world that this projectile belongs to.</param> /// <param name="owner">The ship that fired this projectile, if any.</param> /// <param name="direction">The initial direction for this projectile.</param> public Projectile(World world, Ship owner, Vector2 direction) : base(world) { this.owner = owner; this.position = owner.Position; this.velocity = direction; } #endregion #region Update /// <summary> /// Update the projectile. /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> public override void Update(float elapsedTime) { // projectiles can "time out" if (duration > 0f) { duration -= elapsedTime; if (duration < 0f) { Die(null); } } base.Update(elapsedTime); } #endregion #region Interaction /// <summary> /// Damages all actors in a radius around the projectile. /// </summary> /// <param name="touchedActor">The actor that was originally hit.</param> public virtual void Explode(Actor touchedActor) { // if there is no radius, then don't bother if (damageRadius <= 0f) { return; } // check each actor for damage foreach (Actor actor in world.Actors) { // don't bother if it's already dead if (actor.Dead == true) { continue; } // don't hurt the actor that the projectile hit, it's already hurt if (actor == touchedActor) { continue; } // don't hit the owner if the damageOwner flag is off if ((actor == owner) && (damageOwner == false)) { continue; } // measure the distance to the actor and see if it's in range float distance = (actor.Position - this.Position).Length(); if (distance <= damageRadius) { // adjust the amount of damage based on the distance // -- note that damageRadius <= 0 is accounted for earlier float adjustedDamage = damageAmount * (damageRadius - distance) / damageRadius; // if we're still damaging the actor, then go ahead and apply it if (adjustedDamage > 0f) { actor.Damage(this, adjustedDamage); } } } } /// <summary> /// Defines the interaction between this projectile and a target actor /// when they touch. /// </summary> /// <param name="target">The actor that is touching this object.</param> /// <returns>True if the objects meaningfully interacted.</returns> public override bool Touch(Actor target) { // check the target, if we have one if (target != null) { // don't bother hitting any power-ups if (target is PowerUp) { return false; } // don't hit the owner if the damageOwner flag isn't set if ((target == owner) && (this.damageOwner == false)) { return false; } // don't hit other projectiles from the same ship Projectile projectile = target as Projectile; if ((projectile != null) && (projectile.Owner == this.Owner)) { return false; } // damage the target target.Damage(this, this.damageAmount); } // either we hit something or the target is null - in either case, die Die(target); return base.Touch(target); } /// <summary> /// Kills this projectile, in response to the given actor. /// </summary> /// <param name="source">The actor responsible for the kill.</param> public override void Die(Actor source) { if (dead == false) { base.Die(source); if (dead && explodes) { Explode(source); } } } /// <summary> /// Place this projectile in the world. /// </summary> /// <param name="findSpawnPoint"> /// If true, the actor's position is changed to a valid, non-colliding point. /// </param> public override void Spawn(bool findSpawnPoint) { Vector2 newVelocity = speed * Vector2.Normalize(velocity); base.Spawn(findSpawnPoint); // reset the velocity to the speed times the current direction; velocity = newVelocity; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DotNetMVC.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Connections; using Cassandra.Connections.Control; using Cassandra.DataStax.Graph; using Cassandra.DataStax.Insights; using Cassandra.DataStax.Insights.InfoProviders; using Cassandra.DataStax.Insights.InfoProviders.StartupMessage; using Cassandra.DataStax.Insights.InfoProviders.StatusMessage; using Cassandra.DataStax.Insights.MessageFactories; using Cassandra.DataStax.Insights.Schema.StartupMessage; using Cassandra.DataStax.Insights.Schema.StatusMessage; using Cassandra.ExecutionProfiles; using Cassandra.Helpers; using Cassandra.MetadataHelpers; using Cassandra.Metrics; using Cassandra.Metrics.Abstractions; using Cassandra.Metrics.Providers.Null; using Cassandra.Observers; using Cassandra.ProtocolEvents; using Cassandra.Requests; using Cassandra.Serialization; using Cassandra.SessionManagement; using Cassandra.Tasks; using Microsoft.IO; namespace Cassandra { /// <summary> /// The configuration of the cluster. It configures the following: <ul> <li>Cassandra /// binary protocol level configuration (compression).</li> <li>Connection /// pooling configurations.</li> <li>low-level tcp configuration options /// (tcpNoDelay, keepAlive, ...).</li> </ul> /// </summary> public class Configuration { internal const string DefaultExecutionProfileName = "default"; internal const string DefaultSessionName = "s"; /// <summary> /// Gets the policies set for the cluster. /// </summary> public Policies Policies { get; } /// <summary> /// Gets the low-level tcp configuration options used (tcpNoDelay, keepAlive, ...). /// </summary> public SocketOptions SocketOptions { get; private set; } /// <summary> /// The Cassandra binary protocol level configuration (compression). /// </summary> /// /// <returns>the protocol options.</returns> public ProtocolOptions ProtocolOptions { get; private set; } /// <summary> /// The connection pooling configuration, defaults to null. /// </summary> /// <returns>the pooling options.</returns> public PoolingOptions PoolingOptions { get; } /// <summary> /// The .net client additional options configuration. /// </summary> public ClientOptions ClientOptions { get; private set; } /// <summary> /// The query configuration. /// </summary> public QueryOptions QueryOptions { get; private set; } /// <summary> /// The authentication provider used to connect to the Cassandra cluster. /// </summary> /// <returns>the authentication provider in use.</returns> internal IAuthProvider AuthProvider { get; private set; } // Not exposed yet on purpose /// <summary> /// The authentication provider used to connect to the Cassandra cluster. /// </summary> /// <returns>the authentication provider in use.</returns> internal IAuthInfoProvider AuthInfoProvider { get; private set; } // Not exposed yet on purpose /// <summary> /// The address translator used to translate Cassandra node address. /// </summary> /// <returns>the address translator in use.</returns> public IAddressTranslator AddressTranslator { get; private set; } /// <summary> /// Gets a read only key value map of execution profiles that were configured with /// <see cref="Builder.WithExecutionProfiles"/>. The keys are execution profile names and the values /// are <see cref="IExecutionProfile"/> instances. /// </summary> public IReadOnlyDictionary<string, IExecutionProfile> ExecutionProfiles { get; } /// <summary> /// <see cref="Builder.WithUnresolvedContactPoints"/> /// </summary> public bool KeepContactPointsUnresolved { get; } /// <summary> /// Shared reusable timer /// </summary> internal HashedWheelTimer Timer { get; private set; } /// <summary> /// Shared buffer pool /// </summary> internal RecyclableMemoryStreamManager BufferPool { get; private set; } /// <summary> /// Gets or sets the list of <see cref="TypeSerializer{T}"/> defined. /// </summary> internal IEnumerable<ITypeSerializer> TypeSerializers { get; set; } internal MetadataSyncOptions MetadataSyncOptions { get; } internal IStartupOptionsFactory StartupOptionsFactory { get; } internal ISessionFactory SessionFactory { get; } internal IRequestOptionsMapper RequestOptionsMapper { get; } internal IRequestHandlerFactory RequestHandlerFactory { get; } internal IHostConnectionPoolFactory HostConnectionPoolFactory { get; } internal IRequestExecutionFactory RequestExecutionFactory { get; } internal IConnectionFactory ConnectionFactory { get; } internal IControlConnectionFactory ControlConnectionFactory { get; } internal IPrepareHandlerFactory PrepareHandlerFactory { get; } internal ITimerFactory TimerFactory { get; } internal IEndPointResolver EndPointResolver { get; } internal IDnsResolver DnsResolver { get; } internal IMetadataRequestHandler MetadataRequestHandler { get; } internal ITopologyRefresherFactory TopologyRefresherFactory { get; } internal ISchemaParserFactory SchemaParserFactory { get; } internal ISupportedOptionsInitializerFactory SupportedOptionsInitializerFactory { get; } internal IProtocolVersionNegotiator ProtocolVersionNegotiator { get; } internal IServerEventsSubscriber ServerEventsSubscriber { get; } internal IDriverMetricsProvider MetricsProvider { get; } internal DriverMetricsOptions MetricsOptions { get; } internal string SessionName { get; } internal bool MetricsEnabled { get; } internal IObserverFactoryBuilder ObserverFactoryBuilder { get; } internal static string DefaultApplicationVersion => string.Empty; internal static string FallbackApplicationName => AssemblyHelpers.GetEntryAssembly()?.GetName().Name ?? Builder.DefaultApplicationName; /// <summary> /// The version of the application using the created cluster instance. /// </summary> public string ApplicationVersion { get; } /// <summary> /// The name of the application using the created cluster instance. /// </summary> public string ApplicationName { get; } /// <summary> /// Specifies whether <see cref="ApplicationName"/> was generated by the driver. /// </summary> public bool ApplicationNameWasGenerated { get; } /// <summary> /// A unique identifier for the created cluster instance. /// </summary> public Guid ClusterId { get; } /// <summary> /// Gets the options related to graph instance. /// </summary> public GraphOptions GraphOptions { get; protected set; } /// <summary> /// Whether beta protocol versions will be considered by the driver during /// the protocol version negotiation. /// </summary> public bool AllowBetaProtocolVersions { get; } /// <summary> /// The key is the execution profile name and the value is the IRequestOptions instance /// built from the execution profile with that key. /// </summary> internal IReadOnlyDictionary<string, IRequestOptions> RequestOptions { get; } /// <summary> /// Configuration options for monitor reporting /// </summary> public MonitorReportingOptions MonitorReportingOptions { get; } internal IInsightsSupportVerifier InsightsSupportVerifier { get; } internal IInsightsClientFactory InsightsClientFactory { get; } internal IRequestOptions DefaultRequestOptions => RequestOptions[Configuration.DefaultExecutionProfileName]; internal static IInsightsSupportVerifier DefaultInsightsSupportVerifier => new InsightsSupportVerifier(); internal static IInsightsClientFactory DefaultInsightsClientFactory => new InsightsClientFactory( Configuration.DefaultInsightsStartupMessageFactory, Configuration.DefaultInsightsStatusMessageFactory); internal static IInsightsMessageFactory<InsightsStartupData> DefaultInsightsStartupMessageFactory => new InsightsStartupMessageFactory( Configuration.DefaultInsightsMetadataFactory, Configuration.DefaultInsightsInfoProvidersCollection ); internal static IInsightsMessageFactory<InsightsStatusData> DefaultInsightsStatusMessageFactory => new InsightsStatusMessageFactory( Configuration.DefaultInsightsMetadataFactory, new NodeStatusInfoProvider() ); internal static IInsightsMetadataFactory DefaultInsightsMetadataFactory => new InsightsMetadataFactory(new InsightsMetadataTimestampGenerator()); internal static InsightsInfoProvidersCollection DefaultInsightsInfoProvidersCollection => new InsightsInfoProvidersCollection( new PlatformInfoProvider(), new ExecutionProfileInfoProvider( new LoadBalancingPolicyInfoProvider(new ReconnectionPolicyInfoProvider()), new SpeculativeExecutionPolicyInfoProvider(), new RetryPolicyInfoProvider()), new PoolSizeByHostDistanceInfoProvider(), new AuthProviderInfoProvider(), new DataCentersInfoProvider(), new OtherOptionsInfoProvider(), new ConfigAntiPatternsInfoProvider(), new ReconnectionPolicyInfoProvider(), new DriverInfoProvider(), new HostnameInfoProvider()); internal IContactPointParser ContactPointParser { get; } internal IServerNameResolver ServerNameResolver { get; } internal Configuration() : this(Policies.DefaultPolicies, new ProtocolOptions(), null, new SocketOptions(), new ClientOptions(), NoneAuthProvider.Instance, null, new QueryOptions(), new DefaultAddressTranslator(), new Dictionary<string, IExecutionProfile>(), null, null, null, null, null, null, null, null, null, null, null, null, null) { } /// <summary> /// Creates a new instance. This class is also used to shareable a context across all instance that are created below one Cluster instance. /// One configuration instance per Cluster instance. /// </summary> internal Configuration(Policies policies, ProtocolOptions protocolOptions, PoolingOptions poolingOptions, SocketOptions socketOptions, ClientOptions clientOptions, IAuthProvider authProvider, IAuthInfoProvider authInfoProvider, QueryOptions queryOptions, IAddressTranslator addressTranslator, IReadOnlyDictionary<string, IExecutionProfile> executionProfiles, MetadataSyncOptions metadataSyncOptions, IEndPointResolver endPointResolver, IDriverMetricsProvider driverMetricsProvider, DriverMetricsOptions metricsOptions, string sessionName, GraphOptions graphOptions, Guid? clusterId, string appVersion, string appName, MonitorReportingOptions monitorReportingOptions, TypeSerializerDefinitions typeSerializerDefinitions, bool? keepContactPointsUnresolved, bool? allowBetaProtocolVersions, ISessionFactory sessionFactory = null, IRequestOptionsMapper requestOptionsMapper = null, IStartupOptionsFactory startupOptionsFactory = null, IInsightsSupportVerifier insightsSupportVerifier = null, IRequestHandlerFactory requestHandlerFactory = null, IHostConnectionPoolFactory hostConnectionPoolFactory = null, IRequestExecutionFactory requestExecutionFactory = null, IConnectionFactory connectionFactory = null, IControlConnectionFactory controlConnectionFactory = null, IPrepareHandlerFactory prepareHandlerFactory = null, ITimerFactory timerFactory = null, IObserverFactoryBuilder observerFactoryBuilder = null, IInsightsClientFactory insightsClientFactory = null, IContactPointParser contactPointParser = null, IServerNameResolver serverNameResolver = null, IDnsResolver dnsResolver = null, IMetadataRequestHandler metadataRequestHandler = null, ITopologyRefresherFactory topologyRefresherFactory = null, ISchemaParserFactory schemaParserFactory = null, ISupportedOptionsInitializerFactory supportedOptionsInitializerFactory = null, IProtocolVersionNegotiator protocolVersionNegotiator = null, IServerEventsSubscriber serverEventsSubscriber = null) { AddressTranslator = addressTranslator ?? throw new ArgumentNullException(nameof(addressTranslator)); QueryOptions = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions)); GraphOptions = graphOptions ?? new GraphOptions(); ClusterId = clusterId ?? Guid.NewGuid(); ApplicationVersion = appVersion ?? Configuration.DefaultApplicationVersion; ApplicationName = appName ?? Configuration.FallbackApplicationName; ApplicationNameWasGenerated = appName == null; Policies = policies; ProtocolOptions = protocolOptions; PoolingOptions = poolingOptions; SocketOptions = socketOptions; ClientOptions = clientOptions; AuthProvider = authProvider; AuthInfoProvider = authInfoProvider; StartupOptionsFactory = startupOptionsFactory ?? new StartupOptionsFactory(ClusterId, ApplicationVersion, ApplicationName); SessionFactory = sessionFactory ?? new SessionFactory(); RequestOptionsMapper = requestOptionsMapper ?? new RequestOptionsMapper(); MetadataSyncOptions = metadataSyncOptions?.Clone() ?? new MetadataSyncOptions(); DnsResolver = dnsResolver ?? new DnsResolver(); MetadataRequestHandler = metadataRequestHandler ?? new MetadataRequestHandler(); TopologyRefresherFactory = topologyRefresherFactory ?? new TopologyRefresherFactory(); SchemaParserFactory = schemaParserFactory ?? new SchemaParserFactory(); SupportedOptionsInitializerFactory = supportedOptionsInitializerFactory ?? new SupportedOptionsInitializerFactory(); ProtocolVersionNegotiator = protocolVersionNegotiator ?? new ProtocolVersionNegotiator(); ServerEventsSubscriber = serverEventsSubscriber ?? new ServerEventsSubscriber(); MetricsOptions = metricsOptions ?? new DriverMetricsOptions(); MetricsProvider = driverMetricsProvider ?? new NullDriverMetricsProvider(); SessionName = sessionName; MetricsEnabled = driverMetricsProvider != null; TypeSerializers = typeSerializerDefinitions?.Definitions; KeepContactPointsUnresolved = keepContactPointsUnresolved ?? false; AllowBetaProtocolVersions = allowBetaProtocolVersions ?? false; ObserverFactoryBuilder = observerFactoryBuilder ?? (MetricsEnabled ? (IObserverFactoryBuilder)new MetricsObserverFactoryBuilder() : new NullObserverFactoryBuilder()); RequestHandlerFactory = requestHandlerFactory ?? new RequestHandlerFactory(); HostConnectionPoolFactory = hostConnectionPoolFactory ?? new HostConnectionPoolFactory(); RequestExecutionFactory = requestExecutionFactory ?? new RequestExecutionFactory(); ConnectionFactory = connectionFactory ?? new ConnectionFactory(); ControlConnectionFactory = controlConnectionFactory ?? new ControlConnectionFactory(); PrepareHandlerFactory = prepareHandlerFactory ?? new PrepareHandlerFactory(); TimerFactory = timerFactory ?? new TaskBasedTimerFactory(); RequestOptions = RequestOptionsMapper.BuildRequestOptionsDictionary(executionProfiles, policies, socketOptions, clientOptions, queryOptions, GraphOptions); ExecutionProfiles = BuildExecutionProfilesDictionary(executionProfiles, RequestOptions); MonitorReportingOptions = monitorReportingOptions ?? new MonitorReportingOptions(); InsightsSupportVerifier = insightsSupportVerifier ?? Configuration.DefaultInsightsSupportVerifier; InsightsClientFactory = insightsClientFactory ?? Configuration.DefaultInsightsClientFactory; ServerNameResolver = serverNameResolver ?? new ServerNameResolver(ProtocolOptions); EndPointResolver = endPointResolver ?? new EndPointResolver(ServerNameResolver); ContactPointParser = contactPointParser ?? new ContactPointParser(DnsResolver, ProtocolOptions, ServerNameResolver, KeepContactPointsUnresolved); // Create the buffer pool with 16KB for small buffers and 256Kb for large buffers. // The pool does not eagerly reserve the buffers, so it doesn't take unnecessary memory // to create the instance. BufferPool = new RecyclableMemoryStreamManager(16 * 1024, 256 * 1024, ProtocolOptions.MaximumFrameLength); Timer = new HashedWheelTimer(); } /// <summary> /// Clones (shallow) the provided execution profile dictionary and add the default profile if not there yet. /// </summary> private IReadOnlyDictionary<string, IExecutionProfile> BuildExecutionProfilesDictionary( IReadOnlyDictionary<string, IExecutionProfile> executionProfiles, IReadOnlyDictionary<string, IRequestOptions> requestOptions) { var executionProfilesDictionary = executionProfiles.ToDictionary(profileKvp => profileKvp.Key, profileKvp => profileKvp.Value); var defaultOptions = requestOptions[Configuration.DefaultExecutionProfileName]; executionProfilesDictionary[Configuration.DefaultExecutionProfileName] = new ExecutionProfile(defaultOptions); return executionProfilesDictionary; } /// <summary> /// Gets the pooling options. If not specified, creates a new instance with the default by protocol version. /// This instance is not stored. /// </summary> internal PoolingOptions GetOrCreatePoolingOptions(ProtocolVersion protocolVersion) { return PoolingOptions ?? PoolingOptions.Create(protocolVersion); } internal int? GetHeartBeatInterval() { return PoolingOptions != null ? PoolingOptions.GetHeartBeatInterval() : PoolingOptions.Create().GetHeartBeatInterval(); } /// <summary> /// Sets the default consistency level. /// </summary> internal void SetDefaultConsistencyLevel(ConsistencyLevel consistencyLevel) { QueryOptions.SetDefaultConsistencyLevel(consistencyLevel); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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.UnitTests.LayoutRenderers { using System; using System.Reflection; using System.Threading; using Xunit; public class CallSiteTests : NLogTestBase { #if !SILVERLIGHT [Fact] public void LineNumberTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); #line 100000 logger.Debug("msg"); string lastMessage = GetDebugLastMessage("debug"); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf("callsitetests.cs:10000", StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #line default } #endif [Fact] public void MethodNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } [Fact] public void ClassNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + " msg"); } [Fact] public void ClassNameWithPaddingTestTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void MethodNameWithPaddingTestTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg"); } [Fact] public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); Action action = () => logger.Debug("msg"); action.Invoke(); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg"); } [Fact] public void CleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest"); } } [Fact] public void DontCleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>")); } } [Fact] public void CleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); } } [Fact] public void DontCleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.Contains("+<>")); } } } }
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Text; using System.Data.Common; using Epi.Data.MongoDB.Forms; using System.IO; using Epi.Data.MongoDB; using Epi; using System.Windows.Forms; namespace Epi.Data.MongoDB { /// <summary> /// MongoDBColumnType - Database Factory for MongoDB Databases /// </summary> public class MongoDBDBFactory : IDbDriverFactory { #region Connection string on different OS //Windows // "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass"; //Linux with MONO: filepath is all of the below statement // "database=myDB;server=/var/lib/MongoDB/MongoDB.sock;user id=myUser; pwd=myPass"; #endregion private MongoDBConnectionStringBuilder MongoDBConnBuild = new MongoDBConnectionStringBuilder(); public bool ArePrerequisitesMet() { return true; } public string PrerequisiteMessage { get { return string.Empty; } } #region IDbDriverFactory Members /// <summary> /// Create a database /// </summary> /// <param name="dbInfo">DbDriverInfo</param> public void CreatePhysicalDatabase(DbDriverInfo dbInfo) { MongoDBConnectionStringBuilder masterBuilder = new MongoDBConnectionStringBuilder(dbInfo.DBCnnStringBuilder.ToString()); MongoDBConnectionStringBuilder tempBuilder = new MongoDBConnectionStringBuilder(dbInfo.DBCnnStringBuilder.ToString()); //tempBuilder = dbInfo.DBCnnStringBuilder as MongoDBConnectionStringBuilder; //The "test" database is installed by default with MongoDB. System needs to login to this database to create a new database. tempBuilder.Database = "information_schema"; MongoDBConnection masterConnection = new MongoDBConnection(tempBuilder.ToString()); try { MongoDBCommand command = masterConnection.CreateCommand() as MongoDBCommand; if(dbInfo.DBName != null) { command.CommandText = "create database " + dbInfo.DBName + ";"; } masterConnection.Open(); //Logger.Log(command.CommandText); command.ExecuteNonQuery(); //reset database to new database for correct storage of meta tables tempBuilder.Database = dbInfo.DBName; } catch (Exception ex) { throw new System.ApplicationException("Could not create new MongoDB Database", ex);//(Epi.SharedStrings.CAN_NOT_CREATE_NEW_MYSQL, ex); } finally { masterConnection.Close(); } } /// <summary> /// Create an instance of database object /// </summary> /// <param name="connectionStringBuilder">A connection string builder which contains the connection string</param> /// <returns>IDbDriver instance</returns> public IDbDriver CreateDatabaseObject(System.Data.Common.DbConnectionStringBuilder connectionStringBuilder) { IDbDriver instance = new MongoDBDatabase(); instance.ConnectionString = connectionStringBuilder.ConnectionString; return instance; } /// <summary> /// Create a database with a name that has already been established /// </summary> /// <param name="configDatabaseKey">Name of the database</param> /// <returns>IDbDriver instance</returns> public IDbDriver CreateDatabaseObjectByConfiguredName(string configDatabaseKey) { //may not use since PHIN is .MDB IDbDriver instance = null; Configuration config = Configuration.GetNewInstance(); DataRow[] result = config.DatabaseConnections.Select("Name='" + configDatabaseKey + "'"); if (result.Length == 1) { Epi.DataSets.Config.DatabaseRow dbConnection = (Epi.DataSets.Config.DatabaseRow)result[0]; MongoDBConnectionStringBuilder MongoDBConnectionBuilder = new MongoDBConnectionStringBuilder(dbConnection.ConnectionString); instance = CreateDatabaseObject(MongoDBConnectionBuilder); } else { throw new GeneralException("Database name is not configured."); } return instance; } /// <summary> /// Launch GUI for connection string for an existing database Throws NotSupportedException if there is /// no GUI associated with the current environment. /// </summary> /// <returns>IConnectionStringGui</returns> public IConnectionStringGui GetConnectionStringGuiForExistingDb() { if (Configuration.Environment == ExecutionEnvironment.WindowsApplication) { return new ExistingConnectionStringDialog(); } else { throw new NotSupportedException("No GUI associated with current environment."); } } /// <summary> /// Launch GUI for connection string for a new database Throws NotSupportedException if there is /// no GUI associated with the current environment. /// </summary> /// <returns>IConnectionStringGui</returns> public IConnectionStringGui GetConnectionStringGuiForNewDb() { if (Configuration.Environment == ExecutionEnvironment.WindowsApplication) { return new NonExistingConnectionStringDialog(); } else { throw new NotSupportedException("No GUI associated with current environment."); } } /// <summary> /// Get a new connection, given a fileName /// </summary> /// <param name="fileName">Name of the file to become the connectionString</param> /// <returns>System.Data.Common.DbConnectionStringBuilder</returns> public System.Data.Common.DbConnectionStringBuilder RequestNewConnection(string fileName) { DbConnectionStringBuilder dbStringBuilder = new DbConnectionStringBuilder(false); //dbStringBuilder.ConnectionString = fileName; return dbStringBuilder; } /// <summary> /// Get the default connection /// </summary> /// <param name="databaseName">Name of the database to get the default connection from</param> /// <returns></returns> public System.Data.Common.DbConnectionStringBuilder RequestDefaultConnection(string databaseName, string projectName = "") { DbConnectionStringBuilder dbStringBuilder = new DbConnectionStringBuilder(false); dbStringBuilder.ConnectionString = MongoDBDatabase.BuildDefaultConnectionString(databaseName); return dbStringBuilder; } /// <summary> /// Default MongoDB ConnectionString request. /// </summary> /// <param name="database">Data store.</param> /// <param name="server">Server location of database.</param> /// <param name="user">User account login Id.</param> /// <param name="password">User account password.</param> /// <returns>Strongly typed connection string builder.</returns> public System.Data.Common.DbConnectionStringBuilder RequestDefaultConnection(string database, string server, string user, string password) { MongoDBConnBuild.AutoCache = false; //.PersistSecurityInfo = false; MongoDBConnBuild.Database = database; MongoDBConnBuild.Server = server; MongoDBConnBuild.User = user; MongoDBConnBuild.Password = password; return (MongoDBConnBuild as DbConnectionStringBuilder); } public bool CanClaimConnectionString(string connectionString) { string conn = connectionString.ToLowerInvariant(); if (conn.Contains("mongodb")) { return true; } else { return false; } } #endregion public string ConvertFileStringToConnectionString(string fileString) { return fileString; } public string GetCreateFromDataTableSQL(string tableName, DataTable table) { throw new NotImplementedException(); } public string SQLGetType(object type, int columnSize, int numericPrecision, int numericScale) { throw new NotImplementedException(); } } }
// 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; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Roslyn.Utilities; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.CodeAnalysis.CompilerServer; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class ManagedCompiler : ToolTask { private CancellationTokenSource _sharedCompileCts; internal readonly PropertyDictionary _store = new PropertyDictionary(); public ManagedCompiler() { TaskResources = ErrorString.ResourceManager; } #region Properties // Please keep these alphabetized. public string[] AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[])_store[nameof(AdditionalLibPaths)]; } } public string[] AddModules { set { _store[nameof(AddModules)] = value; } get { return (string[])_store[nameof(AddModules)]; } } public ITaskItem[] AdditionalFiles { set { _store[nameof(AdditionalFiles)] = value; } get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; } } public ITaskItem[] Analyzers { set { _store[nameof(Analyzers)] = value; } get { return (ITaskItem[])_store[nameof(Analyzers)]; } } // We do not support BugReport because it always requires user interaction, // which will cause a hang. public string CodeAnalysisRuleSet { set { _store[nameof(CodeAnalysisRuleSet)] = value; } get { return (string)_store[nameof(CodeAnalysisRuleSet)]; } } public int CodePage { set { _store[nameof(CodePage)] = value; } get { return _store.GetOrDefault(nameof(CodePage), 0); } } [Output] public ITaskItem[] CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; } } public string DebugType { set { _store[nameof(DebugType)] = value; } get { return (string)_store[nameof(DebugType)]; } } public string DefineConstants { set { _store[nameof(DefineConstants)] = value; } get { return (string)_store[nameof(DefineConstants)]; } } public bool DelaySign { set { _store[nameof(DelaySign)] = value; } get { return _store.GetOrDefault(nameof(DelaySign), false); } } public bool Deterministic { set { _store[nameof(Deterministic)] = value; } get { return _store.GetOrDefault(nameof(Deterministic), false); } } public bool EmitDebugInformation { set { _store[nameof(EmitDebugInformation)] = value; } get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); } } public string ErrorLog { set { _store[nameof(ErrorLog)] = value; } get { return (string)_store[nameof(ErrorLog)]; } } public string Features { set { _store[nameof(Features)] = value; } get { return (string)_store[nameof(Features)]; } } public int FileAlignment { set { _store[nameof(FileAlignment)] = value; } get { return _store.GetOrDefault(nameof(FileAlignment), 0); } } public bool HighEntropyVA { set { _store[nameof(HighEntropyVA)] = value; } get { return _store.GetOrDefault(nameof(HighEntropyVA), false); } } public string KeyContainer { set { _store[nameof(KeyContainer)] = value; } get { return (string)_store[nameof(KeyContainer)]; } } public string KeyFile { set { _store[nameof(KeyFile)] = value; } get { return (string)_store[nameof(KeyFile)]; } } public ITaskItem[] LinkResources { set { _store[nameof(LinkResources)] = value; } get { return (ITaskItem[])_store[nameof(LinkResources)]; } } public string MainEntryPoint { set { _store[nameof(MainEntryPoint)] = value; } get { return (string)_store[nameof(MainEntryPoint)]; } } public bool NoConfig { set { _store[nameof(NoConfig)] = value; } get { return _store.GetOrDefault(nameof(NoConfig), false); } } public bool NoLogo { set { _store[nameof(NoLogo)] = value; } get { return _store.GetOrDefault(nameof(NoLogo), false); } } public bool NoWin32Manifest { set { _store[nameof(NoWin32Manifest)] = value; } get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); } } public bool Optimize { set { _store[nameof(Optimize)] = value; } get { return _store.GetOrDefault(nameof(Optimize), false); } } [Output] public ITaskItem OutputAssembly { set { _store[nameof(OutputAssembly)] = value; } get { return (ITaskItem)_store[nameof(OutputAssembly)]; } } public string Platform { set { _store[nameof(Platform)] = value; } get { return (string)_store[nameof(Platform)]; } } public bool Prefer32Bit { set { _store[nameof(Prefer32Bit)] = value; } get { return _store.GetOrDefault(nameof(Prefer32Bit), false); } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[] References { set { _store[nameof(References)] = value; } get { return (ITaskItem[])_store[nameof(References)]; } } public bool ReportAnalyzer { set { _store[nameof(ReportAnalyzer)] = value; } get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); } } public ITaskItem[] Resources { set { _store[nameof(Resources)] = value; } get { return (ITaskItem[])_store[nameof(Resources)]; } } public ITaskItem[] ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[])_store[nameof(ResponseFiles)]; } } public bool SkipCompilerExecution { set { _store[nameof(SkipCompilerExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); } } public ITaskItem[] Sources { set { if (UsedCommandLineTool) { NormalizePaths(value); } _store[nameof(Sources)] = value; } get { return (ITaskItem[])_store[nameof(Sources)]; } } public string SubsystemVersion { set { _store[nameof(SubsystemVersion)] = value; } get { return (string)_store[nameof(SubsystemVersion)]; } } public string TargetType { set { _store[nameof(TargetType)] = value.ToLower(CultureInfo.InvariantCulture); } get { return (string)_store[nameof(TargetType)]; } } public bool TreatWarningsAsErrors { set { _store[nameof(TreatWarningsAsErrors)] = value; } get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); } } public bool Utf8Output { set { _store[nameof(Utf8Output)] = value; } get { return _store.GetOrDefault(nameof(Utf8Output), false); } } public string Win32Icon { set { _store[nameof(Win32Icon)] = value; } get { return (string)_store[nameof(Win32Icon)]; } } public string Win32Manifest { set { _store[nameof(Win32Manifest)] = value; } get { return (string)_store[nameof(Win32Manifest)]; } } public string Win32Resource { set { _store[nameof(Win32Resource)] = value; } get { return (string)_store[nameof(Win32Resource)]; } } public string PathMap { set { _store[nameof(PathMap)] = value; } get { return (string)_store[nameof(PathMap)]; } } /// <summary> /// If this property is true then the task will take every C# or VB /// compilation which is queued by MSBuild and send it to the /// VBCSCompiler server instance, starting a new instance if necessary. /// If false, we will use the values from ToolPath/Exe. /// </summary> public bool UseSharedCompilation { set { _store[nameof(UseSharedCompilation)] = value; } get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); } } // Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the // managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit // property is set. internal string PlatformWith32BitPreference { get { string platform = Platform; if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit) { platform = "anycpu32bitpreferred"; } return platform; } } /// <summary> /// Overridable property specifying the encoding of the captured task standard output stream /// </summary> protected override Encoding StandardOutputEncoding { get { return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding; } } #endregion internal abstract BuildProtocolConstants.RequestLanguage Language { get; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands) .Select(arg => new TaskItem(arg)).ToArray(); } if (SkipCompilerExecution) { return 0; } if (!UseSharedCompilation || !string.IsNullOrEmpty(ToolPath)) { return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } using (_sharedCompileCts = new CancellationTokenSource()) { try { CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'"); CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'"); var responseTask = BuildClient.TryRunServerCompilation( Language, TryGetClientDir() ?? Path.GetDirectoryName(pathToTool), CurrentDirectoryToUse(), GetArguments(commandLineCommands, responseFileCommands), _sharedCompileCts.Token, libEnvVariable: LibDirectoryToUse()); responseTask.Wait(_sharedCompileCts.Token); var response = responseTask.Result; if (response != null) { ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands); } else { ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } } catch (OperationCanceledException) { ExitCode = 0; } catch (Exception e) { Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); LogErrorOutput(e.ToString()); ExitCode = -1; } } return ExitCode; } /// <summary> /// Try to get the directory this assembly is in. Returns null if assembly /// was in the GAC. /// </summary> private static string TryGetClientDir() { var assembly = typeof(ManagedCompiler).Assembly; if (assembly.GlobalAssemblyCache) return null; var uri = new Uri(assembly.CodeBase); string assemblyPath = uri.IsFile ? uri.LocalPath : Assembly.GetCallingAssembly().Location; return Path.GetDirectoryName(assemblyPath); } /// <summary> /// Cancel the in-process build task. /// </summary> public override void Cancel() { base.Cancel(); _sharedCompileCts?.Cancel(); } /// <summary> /// Get the current directory that the compiler should run in. /// </summary> private string CurrentDirectoryToUse() { // ToolTask has a method for this. But it may return null. Use the process directory // if ToolTask didn't override. MSBuild uses the process directory. string workingDirectory = GetWorkingDirectory(); if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = Directory.GetCurrentDirectory(); return workingDirectory; } /// <summary> /// Get the "LIB" environment variable, or NULL if none. /// </summary> private string LibDirectoryToUse() { // First check the real environment. string libDirectory = Environment.GetEnvironmentVariable("LIB"); // Now go through additional environment variables. string[] additionalVariables = EnvironmentVariables; if (additionalVariables != null) { foreach (string var in EnvironmentVariables) { if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase)) { libDirectory = var.Substring(4); } } } return libDirectory; } /// <summary> /// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need /// to create our own. /// </summary> [Output] public new int ExitCode { get; private set; } /// <summary> /// Handle a response from the server, reporting messages and returning /// the appropriate exit code. /// </summary> private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands) { switch (response.Type) { case BuildResponse.ResponseType.MismatchedVersion: LogErrorOutput(CommandLineParser.MismatchedVersionErrorText); return -1; case BuildResponse.ResponseType.Completed: var completedResponse = (CompletedBuildResponse)response; LogMessages(completedResponse.Output, StandardOutputImportanceToUse); if (LogStandardErrorAsError) { LogErrorOutput(completedResponse.ErrorOutput); } else { LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse); } return completedResponse.ReturnCode; case BuildResponse.ResponseType.AnalyzerInconsistency: return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); default: throw new InvalidOperationException("Encountered unknown response type"); } } private void LogErrorOutput(string output) { string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedMessage = line.Trim(); if (trimmedMessage != "") { Log.LogError(trimmedMessage); } } } /// <summary> /// Log each of the messages in the given output with the given importance. /// We assume each line is a message to log. /// </summary> /// <remarks> /// Should be "private protected" visibility once it is introduced into C#. /// </remarks> internal abstract void LogMessages(string output, MessageImportance messageImportance); public string GenerateResponseFileContents() { return GenerateResponseFileCommands(); } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).ToArray(); } /// <summary> /// Returns the command line switch used by the tool executable to specify the response file /// Will only be called if the task returned a non empty string from GetResponseFileCommands /// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands /// </summary> protected override string GenerateResponseFileCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } protected override string GenerateCommandLineCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddCommandLineCommands(commandLineBuilder); return commandLineBuilder.ToString(); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig)); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { // If outputAssembly is not specified, then an "/out: <name>" option won't be added to // overwrite the one resulting from the OutputAssembly member of the CompilerParameters class. // In that case, we should set the outputAssembly member based on the first source file. if ( (OutputAssembly == null) && (Sources != null) && (Sources.Length > 0) && (ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here. ) { try { OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec)); } catch (ArgumentException e) { throw new ArgumentException(e.Message, "Sources"); } if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".dll"; } else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".netmodule"; } else { OutputAssembly.ItemSpec += ".exe"; } } commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ","); commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage)); ConfigureDebugProperties(); // The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter // because it's more specific. Order matters on the command-line, and the last one wins. // /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none. commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation)); commandLine.AppendSwitchIfNotNull("/debug:", DebugType); commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign)); commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment)); commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer); commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" }); commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo)); commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest)); commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize)); commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic)); commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap); commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly); commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet); commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog); commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion); commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer)); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" }); commandLine.AppendSwitchIfNotNull("/target:", TargetType); commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors)); commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output)); commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon); commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest); AddFeatures(commandLine, Features); AddAnalyzersToCommandLine(commandLine, Analyzers); AddAdditionalFilesToCommandLine(commandLine); // Append the sources. commandLine.AppendFileNamesIfNotNull(Sources, " "); } /// <summary> /// Adds a "/features:" switch to the command line for each provided feature. /// </summary> internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features) { if (string.IsNullOrEmpty(features)) { return; } foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features)) { commandLine.AppendSwitchIfNotNull("/features:", feature.Trim()); } } /// <summary> /// Adds a "/analyzer:" switch to the command line for each provided analyzer. /// </summary> internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers) { // If there were no analyzers passed in, don't add any /analyzer: switches // on the command-line. if (analyzers == null) { return; } foreach (ITaskItem analyzer in analyzers) { commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec); } } /// <summary> /// Adds a "/additionalfile:" switch to the command line for each additional file. /// </summary> private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine) { // If there were no additional files passed in, don't add any /additionalfile: switches // on the command-line. if (AdditionalFiles == null) { return; } foreach (ITaskItem additionalFile in AdditionalFiles) { commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec); } } /// <summary> /// Configure the debug switches which will be placed on the compiler command-line. /// The matrix of debug type and symbol inputs and the desired results is as follows: /// /// Debug Symbols DebugType Desired Results /// True Full /debug+ /debug:full /// True PdbOnly /debug+ /debug:PdbOnly /// True None /debug- /// True Blank /debug+ /// False Full /debug- /debug:full /// False PdbOnly /debug- /debug:PdbOnly /// False None /debug- /// False Blank /debug- /// Blank Full /debug:full /// Blank PdbOnly /debug:PdbOnly /// Blank None /debug- /// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this /// Release: Blank Blank "Nothing for either switch" /// /// The logic is as follows: /// If debugtype is none set debugtype to empty and debugSymbols to false /// If debugType is blank use the debugsymbols "as is" /// If debug type is set, use its value and the debugsymbols value "as is" /// </summary> private void ConfigureDebugProperties() { // If debug type is set we need to take some action depending on the value. If debugtype is not set // We don't need to modify the EmitDebugInformation switch as its value will be used as is. if (_store[nameof(DebugType)] != null) { // If debugtype is none then only show debug- else use the debug type and the debugsymbols as is. if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0) { _store[nameof(DebugType)] = null; _store[nameof(EmitDebugInformation)] = false; } } } /// <summary> /// Validate parameters, log errors and warnings and return true if /// Execute should proceed. /// </summary> protected override bool ValidateParameters() { return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log) { return ListHasNoDuplicateItems(itemList, parameterName, null, log); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> /// <param name="itemList"></param> /// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param> /// <param name="parameterName"></param> /// <param name="log"></param> private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log) { if (itemList == null || itemList.Length == 0) { return true; } Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in itemList) { string key; string disambiguatingMetadataValue = null; if (disambiguatingMetadataName != null) { disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName); } if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { key = item.ItemSpec; } else { key = item.ItemSpec + ":" + disambiguatingMetadataValue; } if (alreadySeen.ContainsKey(key)) { if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName); } else { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName); } return false; } else { alreadySeen[key] = string.Empty; } } return true; } /// <summary> /// Allows tool to handle the return code. /// This method will only be called with non-zero exitCode. /// </summary> protected override bool HandleTaskExecutionErrors() { // For managed compilers, the compiler should emit the appropriate // error messages before returning a non-zero exit code, so we don't // normally need to emit any additional messages now. // // If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code. // We can only do this for the command line compiler: if the inproc compiler was used, // we can't tell what if anything it logged as it logs directly to Visual Studio's output window. // if (!Log.HasLoggedErrors && UsedCommandLineTool) { // This will log a message "MSB3093: The command exited with code {0}." base.HandleTaskExecutionErrors(); } return false; } /// <summary> /// Takes a list of files and returns the normalized locations of these files /// </summary> private void NormalizePaths(ITaskItem[] taskItems) { foreach (var item in taskItems) { item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec); } } /// <summary> /// Whether the command line compiler was invoked, instead /// of the host object compiler. /// </summary> protected bool UsedCommandLineTool { get; set; } private bool _hostCompilerSupportsAllParameters; protected bool HostCompilerSupportsAllParameters { get { return _hostCompilerSupportsAllParameters; } set { _hostCompilerSupportsAllParameters = value; } } /// <summary> /// Checks the bool result from calling one of the methods on the host compiler object to /// set one of the parameters. If it returned false, that means the host object doesn't /// support a particular parameter or variation on a parameter. So we log a comment, /// and set our state so we know not to call the host object to do the actual compilation. /// </summary> /// <owner>RGoel</owner> protected void CheckHostObjectSupport ( string parameterName, bool resultFromHostObjectSetOperation ) { if (!resultFromHostObjectSetOperation) { Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName); _hostCompilerSupportsAllParameters = false; } } /// <summary> /// Checks to see whether all of the passed-in references exist on disk before we launch the compiler. /// </summary> /// <owner>RGoel</owner> protected bool CheckAllReferencesExistOnDisk() { if (null == References) { // No references return true; } bool success = true; foreach (ITaskItem reference in References) { if (!File.Exists(reference.ItemSpec)) { success = false; Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec); } } return success; } /// <summary> /// The IDE and command line compilers unfortunately differ in how win32 /// manifests are specified. In particular, the command line compiler offers a /// "/nowin32manifest" switch, while the IDE compiler does not offer analogous /// functionality. If this switch is omitted from the command line and no win32 /// manifest is specified, the compiler will include a default win32 manifest /// named "default.win32manifest" found in the same directory as the compiler /// executable. Again, the IDE compiler does not offer analogous support. /// /// We'd like to imitate the command line compiler's behavior in the IDE, but /// it isn't aware of the default file, so we must compute the path to it if /// noDefaultWin32Manifest is false and no win32Manifest was provided by the /// project. /// /// This method will only be called during the initialization of the host object, /// which is only used during IDE builds. /// </summary> /// <returns>the path to the win32 manifest to provide to the host object</returns> internal string GetWin32ManifestSwitch ( bool noDefaultWin32Manifest, string win32Manifest ) { if (!noDefaultWin32Manifest) { if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource)) { // We only want to consider the default.win32manifest if this is an executable if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase) && !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase)) { // We need to compute the path to the default win32 manifest string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile ( "default.win32manifest", TargetDotNetFrameworkVersion.VersionLatest ); if (null == pathToDefaultManifest) { // This is rather unlikely, and the inproc compiler seems to log an error anyway. // So just a message is fine. Log.LogMessageFromResources ( "General_ExpectedFileMissing", "default.win32manifest" ); } return pathToDefaultManifest; } } } return win32Manifest; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SampleWebApi.Inheritance.WebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcurrentBag.cs // // An unordered collection that allows duplicates and that provides add and get operations. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents an thread-safe, unordered collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the bag.</typeparam> /// <remarks> /// <para> /// Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support /// duplicates. <see cref="ConcurrentBag{T}"/> is a thread-safe bag implementation, optimized for /// scenarios where the same thread will be both producing and consuming data stored in the bag. /// </para> /// <para> /// <see cref="ConcurrentBag{T}"/> accepts null reference (Nothing in Visual Basic) as a valid /// value for reference types. /// </para> /// <para> /// All public and protected members of <see cref="ConcurrentBag{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { // ThreadLocalList object that contains the data per thread private ThreadLocal<ThreadLocalList> _locals; // This head and tail pointers points to the first and last local lists, to allow enumeration on the thread locals objects private volatile ThreadLocalList _headList, _tailList; // A flag used to tell the operations thread that it must synchronize the operation, this flag is set/unset within // GlobalListsLock lock private bool _needSync; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/> /// class. /// </summary> public ConcurrentBag() { Initialize(null); } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/> /// class that contains elements copied from the specified collection. /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentBag{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference /// (Nothing in Visual Basic).</exception> public ConcurrentBag(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection", SR.ConcurrentBag_Ctor_ArgumentNullException); } Initialize(collection); } /// <summary> /// Local helper function to initialize a new bag object /// </summary> /// <param name="collection">An enumeration containing items with which to initialize this bag.</param> private void Initialize(IEnumerable<T> collection) { _locals = new ThreadLocal<ThreadLocalList>(); // Copy the collection to the bag if (collection != null) { ThreadLocalList list = GetThreadList(true); foreach (T item in collection) { list.Add(item, false); } } } /// <summary> /// Adds an object to the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="item">The object to be added to the /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types.</param> public void Add(T item) { // Get the local list for that thread, create a new list if this thread doesn't exist //(first time to call add) ThreadLocalList list = GetThreadList(true); AddInternal(list, item); } /// <summary> /// </summary> /// <param name="list"></param> /// <param name="item"></param> private void AddInternal(ThreadLocalList list, T item) { bool lockTaken = false; try { #pragma warning disable 0420 Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Add); #pragma warning restore 0420 //Synchronization cases: // if the list count is less than two to avoid conflict with any stealing thread // if _needSync is set, this means there is a thread that needs to freeze the bag if (list.Count < 2 || _needSync) { // reset it back to zero to avoid deadlock with stealing thread list._currentOp = (int)ListOperation.None; Monitor.Enter(list, ref lockTaken); } list.Add(item, lockTaken); } finally { list._currentOp = (int)ListOperation.None; if (lockTaken) { Monitor.Exit(list); } } } /// <summary> /// Attempts to add an object to the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="item">The object to be added to the /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types.</param> /// <returns>Always returns true</returns> bool IProducerConsumerCollection<T>.TryAdd(T item) { Add(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains the object /// removed from the <see cref="ConcurrentBag{T}"/> or the default value /// of <typeparamref name="T"/> if the operation failed.</param> /// <returns>true if an object was removed successfully; otherwise, false.</returns> public bool TryTake(out T result) { return TryTakeOrPeek(out result, true); } /// <summary> /// Attempts to return an object from the <see cref="ConcurrentBag{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the <see cref="ConcurrentBag{T}"/> or the default value of /// <typeparamref name="T"/> if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { return TryTakeOrPeek(out result, false); } /// <summary> /// Local helper function to Take or Peek an item from the bag /// </summary> /// <param name="result">To receive the item retrieved from the bag</param> /// <param name="take">True means Take operation, false means Peek operation</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryTakeOrPeek(out T result, bool take) { // Get the local list for that thread, return null if the thread doesn't exit //(this thread never add before) ThreadLocalList list = GetThreadList(false); if (list == null || list.Count == 0) { return Steal(out result, take); } bool lockTaken = false; try { if (take) // Take operation { #pragma warning disable 0420 Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Take); #pragma warning restore 0420 //Synchronization cases: // if the list count is less than or equal two to avoid conflict with any stealing thread // if _needSync is set, this means there is a thread that needs to freeze the bag if (list.Count <= 2 || _needSync) { // reset it back to zero to avoid deadlock with stealing thread list._currentOp = (int)ListOperation.None; Monitor.Enter(list, ref lockTaken); // Double check the count and steal if it became empty if (list.Count == 0) { // Release the lock before stealing if (lockTaken) { try { } finally { lockTaken = false; // reset lockTaken to avoid calling Monitor.Exit again in the finally block Monitor.Exit(list); } } return Steal(out result, true); } } list.Remove(out result); } else { if (!list.Peek(out result)) { return Steal(out result, false); } } } finally { list._currentOp = (int)ListOperation.None; if (lockTaken) { Monitor.Exit(list); } } return true; } /// <summary> /// Local helper function to retrieve a thread local list by a thread object /// </summary> /// <param name="forceCreate">Create a new list if the thread does ot exist</param> /// <returns>The local list object</returns> private ThreadLocalList GetThreadList(bool forceCreate) { ThreadLocalList list = _locals.Value; if (list != null) { return list; } else if (forceCreate) { // Acquire the lock to update the _tailList pointer lock (GlobalListsLock) { if (_headList == null) { list = new ThreadLocalList(Environment.CurrentManagedThreadId); _headList = list; _tailList = list; } else { list = GetUnownedList(); if (list == null) { list = new ThreadLocalList(Environment.CurrentManagedThreadId); _tailList._nextList = list; _tailList = list; } } _locals.Value = list; } } else { return null; } Debug.Assert(list != null); return list; } /// <summary> /// Try to reuse an unowned list if exist /// unowned lists are the lists that their owner threads are aborted or terminated /// this is workaround to avoid memory leaks. /// </summary> /// <returns>The list object, null if all lists are owned</returns> private ThreadLocalList GetUnownedList() { //the global lock must be held at this point Debug.Assert(Monitor.IsEntered(GlobalListsLock)); int currentThreadId = Environment.CurrentManagedThreadId; ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._ownerThreadId == currentThreadId) { return currentList; } currentList = currentList._nextList; } return null; } /// <summary> /// Local helper method to steal an item from any other non empty thread /// It enumerate all other threads in two passes first pass acquire the lock with TryEnter if succeeded /// it steals the item, otherwise it enumerate them again in 2nd pass and acquire the lock using Enter /// </summary> /// <param name="result">To receive the item retrieved from the bag</param> /// <param name="take">Whether to remove or peek.</param> /// <returns>True if succeeded, false otherwise.</returns> private bool Steal(out T result, bool take) { #if FEATURE_TRACING if (take) CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryTakeSteals(); else CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryPeekSteals(); #endif bool loop; List<int> versionsList = new List<int>(); // save the lists version do { versionsList.Clear(); //clear the list from the previous iteration loop = false; ThreadLocalList currentList = _headList; while (currentList != null) { versionsList.Add(currentList._version); if (currentList._head != null && TrySteal(currentList, out result, take)) { return true; } currentList = currentList._nextList; } // verify versioning, if other items are added to this list since we last visit it, we should retry currentList = _headList; foreach (int version in versionsList) { if (version != currentList._version) //oops state changed { loop = true; if (currentList._head != null && TrySteal(currentList, out result, take)) return true; } currentList = currentList._nextList; } } while (loop); result = default(T); return false; } /// <summary> /// local helper function tries to steal an item from given local list /// </summary> private bool TrySteal(ThreadLocalList list, out T result, bool take) { lock (list) { if (CanSteal(list)) { list.Steal(out result, take); return true; } result = default(T); return false; } } /// <summary> /// Local helper function to check the list if it became empty after acquiring the lock /// and wait if there is unsynchronized Add/Take operation in the list to be done /// </summary> /// <param name="list">The list to steal</param> /// <returns>True if can steal, false otherwise</returns> private static bool CanSteal(ThreadLocalList list) { if (list.Count <= 2 && list._currentOp != (int)ListOperation.None) { SpinWait spinner = new SpinWait(); while (list._currentOp != (int)ListOperation.None) { spinner.SpinOnce(); } } return list.Count > 0; } /// <summary> /// Copies the <see cref="ConcurrentBag{T}"/> elements to an existing /// one-dimensional <see cref="T:System.Array">Array</see>, starting at the specified array /// index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentBag{T}"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- the number of elements in the source <see /// cref="ConcurrentBag{T}"/> is greater than the available space from /// <paramref name="index"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array", SR.ConcurrentBag_CopyTo_ArgumentNullException); } if (index < 0) { throw new ArgumentOutOfRangeException ("index", SR.ConcurrentBag_CopyTo_ArgumentOutOfRangeException); } // Short path if the bag is empty if (_headList == null) return; bool lockTaken = false; try { FreezeBag(ref lockTaken); ToList().CopyTo(array, index); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentBag{T}"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array", SR.ConcurrentBag_CopyTo_ArgumentNullException); } bool lockTaken = false; try { FreezeBag(ref lockTaken); ((ICollection)ToList()).CopyTo(array, index); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Copies the <see cref="ConcurrentBag{T}"/> elements to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentBag{T}"/>.</returns> public T[] ToArray() { // Short path if the bag is empty if (_headList == null) return new T[0]; bool lockTaken = false; try { FreezeBag(ref lockTaken); return ToList().ToArray(); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentBag{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the bag. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the bag. /// </remarks> public IEnumerator<T> GetEnumerator() { // Short path if the bag is empty if (_headList == null) return ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator(); bool lockTaken = false; try { FreezeBag(ref lockTaken); return ToList().GetEnumerator(); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentBag{T}"/>.</returns> /// <remarks> /// The items enumerated represent a moment-in-time snapshot of the contents /// of the bag. It does not reflect any update to the collection after /// <see cref="GetEnumerator"/> was called. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((ConcurrentBag<T>)this).GetEnumerator(); } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentBag{T}"/>.</value> /// <remarks> /// The count returned represents a moment-in-time snapshot of the contents /// of the bag. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. /// </remarks> public int Count { get { // Short path if the bag is empty if (_headList == null) return 0; bool lockTaken = false; try { FreezeBag(ref lockTaken); return GetCountInternal(); } finally { UnfreezeBag(lockTaken); } } } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentBag{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentBag{T}"/> is empty; otherwise, false.</value> public bool IsEmpty { get { if (_headList == null) return true; bool lockTaken = false; try { FreezeBag(ref lockTaken); ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._head != null) //at least this list is not empty, we return false { return false; } currentList = currentList._nextList; } return true; } finally { UnfreezeBag(lockTaken); } } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentBag{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// A global lock object, used in two cases: /// 1- To maintain the _tailList pointer for each new list addition process ( first time a thread called Add ) /// 2- To freeze the bag in GetEnumerator, CopyTo, ToArray and Count members /// </summary> private object GlobalListsLock { get { Debug.Assert(_locals != null); return _locals; } } #region Freeze bag helper methods /// <summary> /// Local helper method to freeze all bag operations, it /// 1- Acquire the global lock to prevent any other thread to freeze the bag, and also new new thread can be added /// to the dictionary /// 2- Then Acquire all local lists locks to prevent steal and synchronized operations /// 3- Wait for all un-synchronized operations to be done /// </summary> /// <param name="lockTaken">Retrieve the lock taken result for the global lock, to be passed to Unfreeze method</param> private void FreezeBag(ref bool lockTaken) { Debug.Assert(!Monitor.IsEntered(GlobalListsLock)); // global lock to be safe against multi threads calls count and corrupt _needSync Monitor.Enter(GlobalListsLock, ref lockTaken); // This will force any future add/take operation to be synchronized _needSync = true; //Acquire all local lists locks AcquireAllLocks(); // Wait for all un-synchronized operation to be done WaitAllOperations(); } /// <summary> /// Local helper method to unfreeze the bag from a frozen state /// </summary> /// <param name="lockTaken">The lock taken result from the Freeze method</param> private void UnfreezeBag(bool lockTaken) { ReleaseAllLocks(); _needSync = false; if (lockTaken) { Monitor.Exit(GlobalListsLock); } } /// <summary> /// local helper method to acquire all local lists locks /// </summary> private void AcquireAllLocks() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); bool lockTaken = false; ThreadLocalList currentList = _headList; while (currentList != null) { // Try/Finally block to avoid thread abort between acquiring the lock and setting the taken flag try { Monitor.Enter(currentList, ref lockTaken); } finally { if (lockTaken) { currentList._lockTaken = true; lockTaken = false; } } currentList = currentList._nextList; } } /// <summary> /// Local helper method to release all local lists locks /// </summary> private void ReleaseAllLocks() { ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._lockTaken) { currentList._lockTaken = false; Monitor.Exit(currentList); } currentList = currentList._nextList; } } /// <summary> /// Local helper function to wait all unsynchronized operations /// </summary> private void WaitAllOperations() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._currentOp != (int)ListOperation.None) { SpinWait spinner = new SpinWait(); while (currentList._currentOp != (int)ListOperation.None) { spinner.SpinOnce(); } } currentList = currentList._nextList; } } /// <summary> /// Local helper function to get the bag count, the caller should call it from Freeze/Unfreeze block /// </summary> /// <returns>The current bag count</returns> private int GetCountInternal() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); int count = 0; ThreadLocalList currentList = _headList; while (currentList != null) { checked { count += currentList.Count; } currentList = currentList._nextList; } return count; } /// <summary> /// Local helper function to return the bag item in a list, this is mainly used by CopyTo and ToArray /// This is not thread safe, should be called in Freeze/UnFreeze bag block /// </summary> /// <returns>List the contains the bag items</returns> private List<T> ToList() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); List<T> list = new List<T>(); ThreadLocalList currentList = _headList; while (currentList != null) { Node currentNode = currentList._head; while (currentNode != null) { list.Add(currentNode._value); currentNode = currentNode._next; } currentList = currentList._nextList; } return list; } #endregion #region Inner Classes /// <summary> /// A class that represents a node in the lock thread list /// </summary> internal class Node { public Node(T value) { _value = value; } public readonly T _value; public Node _next; public Node _prev; } /// <summary> /// A class that represents the lock thread list /// </summary> internal class ThreadLocalList { // Tead node in the list, null means the list is empty internal volatile Node _head; // Tail node for the list private volatile Node _tail; // The current list operation internal volatile int _currentOp; // The list count from the Add/Take perspective private int _count; // The stealing count internal int _stealCount; // Next list in the dictionary values internal volatile ThreadLocalList _nextList; // Set if the locl lock is taken internal bool _lockTaken; // The owner thread for this list internal int _ownerThreadId; // the version of the list, incremented only when the list changed from empty to non empty state internal volatile int _version; /// <summary> /// ThreadLocalList constructor /// </summary> /// <param name="ownerThread">The owner thread for this list</param> internal ThreadLocalList(int ownerThreadId) { _ownerThreadId = ownerThreadId; } /// <summary> /// Add new item to head of the list /// </summary> /// <param name="item">The item to add.</param> /// <param name="updateCount">Whether to update the count.</param> internal void Add(T item, bool updateCount) { checked { _count++; } Node node = new Node(item); if (_head == null) { Debug.Assert(_tail == null); _head = node; _tail = node; _version++; // changing from empty state to non empty state } else { node._next = _head; _head._prev = node; _head = node; } if (updateCount) // update the count to avoid overflow if this add is synchronized { _count = _count - _stealCount; _stealCount = 0; } } /// <summary> /// Remove an item from the head of the list /// </summary> /// <param name="result">The removed item</param> internal void Remove(out T result) { Debug.Assert(_head != null); Node head = _head; _head = _head._next; if (_head != null) { _head._prev = null; } else { _tail = null; } _count--; result = head._value; } /// <summary> /// Peek an item from the head of the list /// </summary> /// <param name="result">the peeked item</param> /// <returns>True if succeeded, false otherwise</returns> internal bool Peek(out T result) { Node head = _head; if (head != null) { result = head._value; return true; } result = default(T); return false; } /// <summary> /// Steal an item from the tail of the list /// </summary> /// <param name="result">the removed item</param> /// <param name="remove">remove or peek flag</param> internal void Steal(out T result, bool remove) { Node tail = _tail; Debug.Assert(tail != null); if (remove) // Take operation { _tail = _tail._prev; if (_tail != null) { _tail._next = null; } else { _head = null; } // Increment the steal count _stealCount++; } result = tail._value; } /// <summary> /// Gets the total list count, it's not thread safe, may provide incorrect count if it is called concurrently /// </summary> internal int Count { get { return _count - _stealCount; } } } #endregion } /// <summary> /// List operations for ConcurrentBag /// </summary> internal enum ListOperation { None, Add, Take }; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; namespace Orleans.Runtime.GrainDirectory { [Serializable] internal class ActivationInfo : IActivationInfo { public SiloAddress SiloAddress { get; private set; } public DateTime TimeCreated { get; private set; } public GrainDirectoryEntryStatus RegistrationStatus { get; set; } public ActivationInfo(SiloAddress siloAddress, GrainDirectoryEntryStatus registrationStatus) { SiloAddress = siloAddress; TimeCreated = DateTime.UtcNow; RegistrationStatus = registrationStatus; } public ActivationInfo(IActivationInfo iActivationInfo) { SiloAddress = iActivationInfo.SiloAddress; TimeCreated = iActivationInfo.TimeCreated; RegistrationStatus = iActivationInfo.RegistrationStatus; } public bool OkToRemove(UnregistrationCause cause, TimeSpan lazyDeregistrationDelay) { switch (cause) { case UnregistrationCause.Force: return true; case UnregistrationCause.CacheInvalidation: return RegistrationStatus == GrainDirectoryEntryStatus.Cached; case UnregistrationCause.NonexistentActivation: { if (RegistrationStatus == GrainDirectoryEntryStatus.Cached) return true; // cache entries are always removed var delayparameter = lazyDeregistrationDelay; if (delayparameter <= TimeSpan.Zero) return false; // no lazy deregistration else return (TimeCreated <= DateTime.UtcNow - delayparameter); } default: throw new OrleansException("unhandled case"); } } public override string ToString() { return String.Format("{0}, {1}", SiloAddress, TimeCreated); } } [Serializable] internal class GrainInfo : IGrainInfo { public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; } public int VersionTag { get; private set; } public bool SingleInstance { get; private set; } private static readonly SafeRandom rand; internal const int NO_ETAG = -1; static GrainInfo() { rand = new SafeRandom(); } internal GrainInfo() { Instances = new Dictionary<ActivationId, IActivationInfo>(); VersionTag = 0; SingleInstance = false; } public bool AddActivation(ActivationId act, SiloAddress silo) { if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act)) { throw new InvalidOperationException( "Attempting to add a second activation to an existing grain in single activation mode"); } IActivationInfo info; if (Instances.TryGetValue(act, out info)) { if (info.SiloAddress.Equals(silo)) { // just refresh, no need to generate new VersionTag return false; } } Instances[act] = new ActivationInfo(silo, GrainDirectoryEntryStatus.ClusterLocal); VersionTag = rand.Next(); return true; } public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus) { SingleInstance = true; if (Instances.Count > 0) { var item = Instances.First(); return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key); } else { Instances.Add(act, new ActivationInfo(silo, registrationStatus)); VersionTag = rand.Next(); return ActivationAddress.GetAddress(silo, grain, act); } } public bool RemoveActivation(ActivationId act, UnregistrationCause cause, TimeSpan lazyDeregistrationDelay, out IActivationInfo info, out bool wasRemoved) { info = null; wasRemoved = false; if (Instances.TryGetValue(act, out info) && info.OkToRemove(cause, lazyDeregistrationDelay)) { Instances.Remove(act); wasRemoved = true; VersionTag = rand.Next(); } return Instances.Count == 0; } public Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainId grain, IGrainInfo other) { bool modified = false; foreach (var pair in other.Instances) { if (Instances.ContainsKey(pair.Key)) continue; Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus); modified = true; } if (modified) { VersionTag = rand.Next(); } if (SingleInstance && (Instances.Count > 0)) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. var orderedActivations = Instances.OrderBy(pair => pair.Key); var activationToKeep = orderedActivations.First(); var activationsToDrop = orderedActivations.Skip(1); Instances.Clear(); Instances.Add(activationToKeep.Key, activationToKeep.Value); var mapping = new Dictionary<SiloAddress, List<ActivationAddress>>(); foreach (var activationPair in activationsToDrop) { var activation = ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key); List<ActivationAddress> activationsToRemoveOnSilo; if (!mapping.TryGetValue(activation.Silo, out activationsToRemoveOnSilo)) { activationsToRemoveOnSilo = mapping[activation.Silo] = new List<ActivationAddress>(1); } activationsToRemoveOnSilo.Add(activation); } return mapping; } return null; } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo) { SingleInstance = true; if (Instances.Count > 0) { Instances.Remove(oldActivation); } Instances.Add(activation, new ActivationInfo(silo, GrainDirectoryEntryStatus.Cached)); } public bool UpdateClusterRegistrationStatus(ActivationId activationId, GrainDirectoryEntryStatus status, GrainDirectoryEntryStatus? compareWith = null) { IActivationInfo activationInfo; if (!Instances.TryGetValue(activationId, out activationInfo)) return false; if (compareWith.HasValue && compareWith.Value != activationInfo.RegistrationStatus) return false; activationInfo.RegistrationStatus = status; return true; } } internal class GrainDirectoryPartition { // Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full // parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do // a lot more lookups and so can sort periodically? /// <summary> /// contains a map from grain to its list of activations along with the version (etag) counter for the list /// </summary> private Dictionary<GrainId, IGrainInfo> partitionData; private readonly object lockable; private readonly ILogger log; private readonly ILoggerFactory loggerFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly IOptions<GrainDirectoryOptions> grainDirectoryOptions; [ThreadStatic] private static ActivationId[] activationIdsHolder; [ThreadStatic] private static IActivationInfo[] activationInfosHolder; internal int Count { get { return partitionData.Count; } } public GrainDirectoryPartition(ISiloStatusOracle siloStatusOracle, IOptions<GrainDirectoryOptions> grainDirectoryOptions, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory) { partitionData = new Dictionary<GrainId, IGrainInfo>(); lockable = new object(); log = loggerFactory.CreateLogger<GrainDirectoryPartition>(); this.siloStatusOracle = siloStatusOracle; this.grainDirectoryOptions = grainDirectoryOptions; this.grainFactory = grainFactory; this.loggerFactory = loggerFactory; } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } internal void Clear() { lock (lockable) { partitionData.Clear(); } } /// <summary> /// Returns all entries stored in the partition as an enumerable collection /// </summary> /// <returns></returns> public Dictionary<GrainId, IGrainInfo> GetItems() { lock (lockable) { return partitionData.Copy(); } } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <returns>The version associated with this directory mapping</returns> internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo) { if (!IsValidSilo(silo)) { return GrainInfo.NO_ETAG; } IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } grainInfo.AddActivation(activation, silo); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding activation for grain {0}", grain.ToString()); return grainInfo.VersionTag; } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <param name="registrationStatus"></param> /// <returns>The registered ActivationAddress and version associated with this directory mapping</returns> internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding single activation for grain {0}{1}{2}", silo, grain, activation); AddressAndTag result = new AddressAndTag(); if (!IsValidSilo(silo)) return result; IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } result.Address = grainInfo.AddSingleActivation(grain, activation, silo, registrationStatus); result.VersionTag = grainInfo.VersionTag; } return result; } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force) { IActivationInfo ignore1; bool ignore2; RemoveActivation(grain, activation, cause, out ignore1, out ignore2); } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> /// <param name="entry">returns the entry, if found </param> /// <param name="wasRemoved">returns whether the entry was actually removed</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved) { wasRemoved = false; entry = null; lock (lockable) { if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, this.grainDirectoryOptions.Value.LazyDeregistrationDelay, out entry, out wasRemoved)) // if the last activation for the grain was removed, we remove the entire grain info partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved); } /// <summary> /// Removes the grain (and, effectively, all its activations) from the diretcory /// </summary> /// <param name="grain"></param> internal void RemoveGrain(GrainId grain) { lock (lockable) { partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing grain {0}", grain.ToString()); } /// <summary> /// Returns a list of activations (along with the version number of the list) for the given grain. /// If the grain is not found, null is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal AddressesAndTag LookUpActivations(GrainId grain) { var result = new AddressesAndTag(); ActivationId[] activationIds; IActivationInfo[] activationInfos; const int arrayReusingThreshold = 100; int grainInfoInstancesCount; lock (lockable) { IGrainInfo graininfo; if (!partitionData.TryGetValue(grain, out graininfo)) { return result; } result.VersionTag = graininfo.VersionTag; grainInfoInstancesCount = graininfo.Instances.Count; if (grainInfoInstancesCount < arrayReusingThreshold) { if ((activationIds = activationIdsHolder) == null) { activationIdsHolder = activationIds = new ActivationId[arrayReusingThreshold]; } if ((activationInfos = activationInfosHolder) == null) { activationInfosHolder = activationInfos = new IActivationInfo[arrayReusingThreshold]; } } else { activationIds = new ActivationId[grainInfoInstancesCount]; activationInfos = new IActivationInfo[grainInfoInstancesCount]; } graininfo.Instances.Keys.CopyTo(activationIds, 0); graininfo.Instances.Values.CopyTo(activationInfos, 0); } result.Addresses = new List<ActivationAddress>(grainInfoInstancesCount); for (var i = 0; i < grainInfoInstancesCount; i++) { var activationInfo = activationInfos[i]; if (IsValidSilo(activationInfo.SiloAddress)) { result.Addresses.Add(ActivationAddress.GetAddress(activationInfo.SiloAddress, grain, activationIds[i])); } activationInfos[i] = null; activationIds[i] = null; } return result; } /// <summary> /// Returns the activation of a single-activation grain, if present. /// </summary> internal GrainDirectoryEntryStatus TryGetActivation(GrainId grain, out ActivationAddress address, out int version) { IGrainInfo grainInfo; address = null; version = 0; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainDirectoryEntryStatus.Invalid; } var first = grainInfo.Instances.FirstOrDefault(); if (first.Value != null) { address = ActivationAddress.GetAddress(first.Value.SiloAddress, grain, first.Key); version = grainInfo.VersionTag; return first.Value.RegistrationStatus; } } return GrainDirectoryEntryStatus.Invalid; } /// <summary> /// Returns the version number of the list of activations for the grain. /// If the grain is not found, -1 is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal int GetGrainETag(GrainId grain) { IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainInfo.NO_ETAG; } return grainInfo.VersionTag; } } /// <summary> /// Merges one partition into another, assuming partitions are disjoint. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="other"></param> internal void Merge(GrainDirectoryPartition other) { lock (lockable) { foreach (var pair in other.partitionData) { if (partitionData.ContainsKey(pair.Key)) { if (log.IsEnabled(LogLevel.Debug)) log.Debug("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions"); var activationsToDrop = partitionData[pair.Key].Merge(pair.Key, pair.Value); if (activationsToDrop == null) continue; foreach (var siloActivations in activationsToDrop) { var remoteCatalog = grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, siloActivations.Key); remoteCatalog.DeleteActivations(siloActivations.Value).Ignore(); } } else { partitionData.Add(pair.Key, pair.Value); } } } } /// <summary> /// Runs through all entries in the partition and moves/copies (depending on the given flag) the /// entries satisfying the given predicate into a new partition. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param> /// <param name="modifyOrigin">flag controling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param> /// <returns>new grain directory partition containing entries satisfying the given predicate</returns> internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin) { var newDirectory = new GrainDirectoryPartition(this.siloStatusOracle, this.grainDirectoryOptions, this.grainFactory, this.loggerFactory); if (modifyOrigin) { // SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here List<KeyValuePair<GrainId, IGrainInfo>> pairs; lock (lockable) { pairs = partitionData.Where(pair => predicate(pair.Key)).ToList(); } foreach (var pair in pairs) { newDirectory.partitionData.Add(pair.Key, pair.Value); } lock (lockable) { foreach (var pair in pairs) { partitionData.Remove(pair.Key); } } } else { lock (lockable) { foreach (var pair in partitionData.Where(pair => predicate(pair.Key))) { newDirectory.partitionData.Add(pair.Key, pair.Value); } } } return newDirectory; } internal List<ActivationAddress> ToListOfActivations(bool singleActivation) { var result = new List<ActivationAddress>(); lock (lockable) { foreach (var pair in partitionData) { var grain = pair.Key; if (pair.Value.SingleInstance == singleActivation) { result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key)) .Where(addr => IsValidSilo(addr.Silo))); } } } return result; } /// <summary> /// Sets the internal parition dictionary to the one given as input parameter. /// This method is supposed to be used by handoff manager to update the old partition with a new partition. /// </summary> /// <param name="newPartitionData">new internal partition dictionary</param> internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData) { partitionData = newPartitionData; } /// <summary> /// Updates partition with a new delta of changes. /// This method is supposed to be used by handoff manager to update the partition with a set of delta changes. /// </summary> /// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition. /// If the value for a given key in the delta is valid, then existing entry in the partition is replaced. /// Otherwise, i.e., if the value is null, the corresponding entry is removed. /// </param> internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta) { lock (lockable) { foreach (GrainId grain in newPartitionDelta.Keys) { if (newPartitionDelta[grain] != null) { partitionData[grain] = newPartitionDelta[grain]; } else { partitionData.Remove(grain); } } } } public override string ToString() { var sb = new StringBuilder(); lock (lockable) { foreach (var grainEntry in partitionData) { foreach (var activationEntry in grainEntry.Value.Instances) { sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]"). Append(" => ").Append(activationEntry.Key.ToString()). Append(" @ ").AppendLine(activationEntry.Value.ToString()); } } } return sb.ToString(); } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationAddress otherClusterAddress) { lock (lockable) { if (partitionData.ContainsKey(grain)) { partitionData[grain].CacheOrUpdateRemoteClusterRegistration(grain, oldActivation, otherClusterAddress.Activation, otherClusterAddress.Silo); } else { AddSingleActivation(grain, otherClusterAddress.Activation, otherClusterAddress.Silo, GrainDirectoryEntryStatus.Cached); } } } public bool UpdateClusterRegistrationStatus(GrainId grain, ActivationId activationId, GrainDirectoryEntryStatus registrationStatus, GrainDirectoryEntryStatus? compareWith = null) { lock (lockable) { IGrainInfo graininfo; if (partitionData.TryGetValue(grain, out graininfo)) { return graininfo.UpdateClusterRegistrationStatus(activationId, registrationStatus, compareWith); } return false; } } } }
using System; using System.Drawing; using System.Windows.Forms; using Barcode_Reader_Demo; using Barcode_Reader_Demo.Properties; namespace Barcode_Reader_Demo { partial class BarcodeReaderDemo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.picBoxWebCam = new System.Windows.Forms.PictureBox(); this.lbMoveBar = new System.Windows.Forms.Label(); this.picboxZoomOut = new System.Windows.Forms.PictureBox(); this.picboxZoomIn = new System.Windows.Forms.PictureBox(); this.picboxDeleteAll = new System.Windows.Forms.PictureBox(); this.picboxDelete = new System.Windows.Forms.PictureBox(); this.picboxFirst = new System.Windows.Forms.PictureBox(); this.picboxLast = new System.Windows.Forms.PictureBox(); this.picboxNext = new System.Windows.Forms.PictureBox(); this.picboxPrevious = new System.Windows.Forms.PictureBox(); this.cbxViewMode = new System.Windows.Forms.ComboBox(); this.picboxMin = new System.Windows.Forms.PictureBox(); this.picboxClose = new System.Windows.Forms.PictureBox(); this.lbDiv = new System.Windows.Forms.Label(); this.tbxCurrentImageIndex = new System.Windows.Forms.TextBox(); this.tbxTotalImageNum = new System.Windows.Forms.TextBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.panelLoad = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel(); this.label24 = new System.Windows.Forms.Label(); this.picboxLoadImage = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.panelWebCam = new System.Windows.Forms.Panel(); this.lblWebCamSrc = new System.Windows.Forms.Label(); this.cbxWebCamSrc = new System.Windows.Forms.ComboBox(); this.lblWebCamRes = new System.Windows.Forms.Label(); this.cbxWebCamRes = new System.Windows.Forms.ComboBox(); this.panelWebcamNote = new System.Windows.Forms.Panel(); this.labelWebcamNote = new System.Windows.Forms.Label(); this.panelAcquire = new System.Windows.Forms.Panel(); this.rdbtnGray = new System.Windows.Forms.RadioButton(); this.cbxResolution = new System.Windows.Forms.ComboBox(); this.picboxScan = new System.Windows.Forms.PictureBox(); this.rdbtnBW = new System.Windows.Forms.RadioButton(); this.lbResolution = new System.Windows.Forms.Label(); this.rdbtnColor = new System.Windows.Forms.RadioButton(); this.lbPixelType = new System.Windows.Forms.Label(); this.lbSelectSource = new System.Windows.Forms.Label(); this.cbxSource = new System.Windows.Forms.ComboBox(); this.panelReadSetting = new System.Windows.Forms.Panel(); this.label6 = new System.Windows.Forms.Label(); this.cbxBarcodeFormat = new System.Windows.Forms.ComboBox(); this.panelReadMoreSetting = new System.Windows.Forms.Panel(); this.panelReadBarcode = new System.Windows.Forms.Panel(); this.picboxReadBarcode = new System.Windows.Forms.PictureBox(); this.picboxStopBarcode = new System.Windows.Forms.PictureBox(); this.picboxFit = new System.Windows.Forms.PictureBox(); this.picboxOriginalSize = new System.Windows.Forms.PictureBox(); this.tbxResult = new System.Windows.Forms.TextBox(); this.lblCloseResult = new System.Windows.Forms.Label(); this.dsViewer = new Dynamsoft.Forms.DSViewer(); ((System.ComponentModel.ISupportInitialize)(this.picBoxWebCam)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxZoomOut)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxZoomIn)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxDeleteAll)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxDelete)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxFirst)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxLast)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxNext)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxPrevious)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxMin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxClose)).BeginInit(); this.panelLoad.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picboxLoadImage)).BeginInit(); this.panelWebCam.SuspendLayout(); this.panelWebcamNote.SuspendLayout(); this.panelAcquire.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picboxScan)).BeginInit(); this.panelReadSetting.SuspendLayout(); this.panelReadMoreSetting.SuspendLayout(); this.panelReadBarcode.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picboxReadBarcode)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxStopBarcode)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxFit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxOriginalSize)).BeginInit(); this.SuspendLayout(); // // picBoxWebCam // this.picBoxWebCam.BackColor = System.Drawing.Color.White; this.picBoxWebCam.Location = new System.Drawing.Point(6, 48); this.picBoxWebCam.Name = "picBoxWebCam"; this.picBoxWebCam.Size = new System.Drawing.Size(563, 628); this.picBoxWebCam.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.picBoxWebCam.TabIndex = 2; this.picBoxWebCam.TabStop = false; this.picBoxWebCam.Visible = false; // // lbMoveBar // this.lbMoveBar.BackColor = System.Drawing.Color.Transparent; this.lbMoveBar.Location = new System.Drawing.Point(0, 1); this.lbMoveBar.Name = "lbMoveBar"; this.lbMoveBar.Size = new System.Drawing.Size(897, 32); this.lbMoveBar.TabIndex = 18; this.lbMoveBar.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lbMoveBar_MouseDown); this.lbMoveBar.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lbMoveBar_MouseMove); // // picboxZoomOut // this.picboxZoomOut.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxZoomOut_Leave; this.picboxZoomOut.Location = new System.Drawing.Point(12, 204); this.picboxZoomOut.Name = "picboxZoomOut"; this.picboxZoomOut.Size = new System.Drawing.Size(60, 36); this.picboxZoomOut.TabIndex = 34; this.picboxZoomOut.TabStop = false; this.picboxZoomOut.Tag = "Zoom Out"; this.picboxZoomOut.Click += new System.EventHandler(this.picboxZoomOut_Click); this.picboxZoomOut.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxZoomOut.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxZoomOut.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxZoomOut.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxZoomOut.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxZoomIn // this.picboxZoomIn.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxZoomIn_Leave; this.picboxZoomIn.Location = new System.Drawing.Point(12, 156); this.picboxZoomIn.Name = "picboxZoomIn"; this.picboxZoomIn.Size = new System.Drawing.Size(61, 36); this.picboxZoomIn.TabIndex = 32; this.picboxZoomIn.TabStop = false; this.picboxZoomIn.Tag = "Zoom In"; this.picboxZoomIn.Click += new System.EventHandler(this.picboxZoomIn_Click); this.picboxZoomIn.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxZoomIn.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxZoomIn.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxZoomIn.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxZoomIn.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxDeleteAll // this.picboxDeleteAll.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxDeleteAll_Leave; this.picboxDeleteAll.Location = new System.Drawing.Point(12, 252); this.picboxDeleteAll.Name = "picboxDeleteAll"; this.picboxDeleteAll.Size = new System.Drawing.Size(60, 36); this.picboxDeleteAll.TabIndex = 38; this.picboxDeleteAll.TabStop = false; this.picboxDeleteAll.Tag = "Delete All"; this.picboxDeleteAll.Click += new System.EventHandler(this.picboxDeleteAll_Click); this.picboxDeleteAll.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxDeleteAll.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxDeleteAll.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxDeleteAll.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxDeleteAll.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxDelete // this.picboxDelete.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxDelete_Leave; this.picboxDelete.Location = new System.Drawing.Point(12, 300); this.picboxDelete.Name = "picboxDelete"; this.picboxDelete.Size = new System.Drawing.Size(61, 36); this.picboxDelete.TabIndex = 36; this.picboxDelete.TabStop = false; this.picboxDelete.Tag = "Delete Current Image"; this.picboxDelete.Click += new System.EventHandler(this.picboxDelete_Click); this.picboxDelete.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxDelete.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxDelete.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxDelete.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxDelete.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxFirst // this.picboxFirst.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxFirst_Leave; this.picboxFirst.Location = new System.Drawing.Point(99, 645); this.picboxFirst.Name = "picboxFirst"; this.picboxFirst.Size = new System.Drawing.Size(50, 25); this.picboxFirst.TabIndex = 42; this.picboxFirst.TabStop = false; this.picboxFirst.Tag = "First Image"; this.picboxFirst.Click += new System.EventHandler(this.picboxFirst_Click); this.picboxFirst.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxFirst.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxFirst.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxFirst.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxFirst.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxLast // this.picboxLast.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxLast_Leave; this.picboxLast.Location = new System.Drawing.Point(418, 645); this.picboxLast.Name = "picboxLast"; this.picboxLast.Size = new System.Drawing.Size(50, 25); this.picboxLast.TabIndex = 43; this.picboxLast.TabStop = false; this.picboxLast.Tag = "Last Image"; this.picboxLast.Click += new System.EventHandler(this.picboxLast_Click); this.picboxLast.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxLast.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxLast.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxLast.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxLast.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxNext // this.picboxNext.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxNext_Leave; this.picboxNext.Location = new System.Drawing.Point(362, 645); this.picboxNext.Name = "picboxNext"; this.picboxNext.Size = new System.Drawing.Size(50, 25); this.picboxNext.TabIndex = 44; this.picboxNext.TabStop = false; this.picboxNext.Tag = "Next Image"; this.picboxNext.Click += new System.EventHandler(this.picboxNext_Click); this.picboxNext.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxNext.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxNext.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxNext.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxNext.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxPrevious // this.picboxPrevious.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxPrevious_Leave; this.picboxPrevious.Location = new System.Drawing.Point(155, 645); this.picboxPrevious.Name = "picboxPrevious"; this.picboxPrevious.Size = new System.Drawing.Size(50, 25); this.picboxPrevious.TabIndex = 47; this.picboxPrevious.TabStop = false; this.picboxPrevious.Tag = "Previous Image"; this.picboxPrevious.Click += new System.EventHandler(this.picboxPrevious_Click); this.picboxPrevious.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxPrevious.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxPrevious.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxPrevious.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxPrevious.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // cbxViewMode // this.cbxViewMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxViewMode.FormattingEnabled = true; this.cbxViewMode.Items.AddRange(new object[] { "1 x 1", "2 x 2", "3 x 3", "4 x 4", "5 x 5"}); this.cbxViewMode.Location = new System.Drawing.Point(474, 645); this.cbxViewMode.Name = "cbxViewMode"; this.cbxViewMode.Size = new System.Drawing.Size(75, 23); this.cbxViewMode.TabIndex = 650; this.cbxViewMode.SelectedIndexChanged += new System.EventHandler(this.cbxLayout_SelectedIndexChanged); // // picboxMin // this.picboxMin.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxMin_Leave; this.picboxMin.Location = new System.Drawing.Point(840, 10); this.picboxMin.Name = "picboxMin"; this.picboxMin.Size = new System.Drawing.Size(20, 20); this.picboxMin.TabIndex = 73; this.picboxMin.TabStop = false; this.picboxMin.Click += new System.EventHandler(this.picboxMin_Click); this.picboxMin.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxMin.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxMin.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxMin.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxClose // this.picboxClose.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxClose_Leave; this.picboxClose.Location = new System.Drawing.Point(864, 10); this.picboxClose.Name = "picboxClose"; this.picboxClose.Size = new System.Drawing.Size(20, 20); this.picboxClose.TabIndex = 74; this.picboxClose.TabStop = false; this.picboxClose.MouseClick += new System.Windows.Forms.MouseEventHandler(this.picboxClose_MouseClick); this.picboxClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxClose.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxClose.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxClose.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // lbDiv // this.lbDiv.AutoSize = true; this.lbDiv.BackColor = System.Drawing.Color.Transparent; this.lbDiv.Location = new System.Drawing.Point(279, 650); this.lbDiv.Name = "lbDiv"; this.lbDiv.Size = new System.Drawing.Size(12, 15); this.lbDiv.TabIndex = 75; this.lbDiv.Text = "/"; // // tbxCurrentImageIndex // this.tbxCurrentImageIndex.Enabled = false; this.tbxCurrentImageIndex.Location = new System.Drawing.Point(211, 647); this.tbxCurrentImageIndex.Name = "tbxCurrentImageIndex"; this.tbxCurrentImageIndex.ReadOnly = true; this.tbxCurrentImageIndex.Size = new System.Drawing.Size(61, 23); this.tbxCurrentImageIndex.TabIndex = 76; this.tbxCurrentImageIndex.Text = "0"; this.tbxCurrentImageIndex.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // tbxTotalImageNum // this.tbxTotalImageNum.Enabled = false; this.tbxTotalImageNum.Location = new System.Drawing.Point(295, 647); this.tbxTotalImageNum.Name = "tbxTotalImageNum"; this.tbxTotalImageNum.ReadOnly = true; this.tbxTotalImageNum.Size = new System.Drawing.Size(61, 23); this.tbxTotalImageNum.TabIndex = 77; this.tbxTotalImageNum.Text = "0"; // // openFileDialog // this.openFileDialog.FileName = "openFileDialog1"; // // flowLayoutPanel2 // this.flowLayoutPanel2.BackColor = System.Drawing.Color.White; this.flowLayoutPanel2.Location = new System.Drawing.Point(566, 48); this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(331, 624); this.flowLayoutPanel2.TabIndex = 84; // // panelLoad // this.panelLoad.BackColor = System.Drawing.Color.Transparent; this.panelLoad.Controls.Add(this.panel1); this.panelLoad.Controls.Add(this.picboxLoadImage); this.panelLoad.Controls.Add(this.label1); this.panelLoad.Location = new System.Drawing.Point(1, 41); this.panelLoad.Margin = new System.Windows.Forms.Padding(0); this.panelLoad.Name = "panelLoad"; this.panelLoad.Size = new System.Drawing.Size(300, 175); this.panelLoad.TabIndex = 3; this.panelLoad.Visible = false; // // panel1 // this.panel1.Controls.Add(this.label24); this.panel1.Location = new System.Drawing.Point(43, 120); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(228, 30); this.panel1.TabIndex = 3; // // label24 // this.label24.Dock = System.Windows.Forms.DockStyle.Fill; this.label24.ImageAlign = System.Drawing.ContentAlignment.TopLeft; this.label24.Location = new System.Drawing.Point(0, 0); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(228, 30); this.label24.TabIndex = 0; this.label24.Text = " Note: PDF Rasterizer add-on is used when loading PDF files."; // // picboxLoadImage // this.picboxLoadImage.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxLoadImage_Leave; this.picboxLoadImage.InitialImage = null; this.picboxLoadImage.Location = new System.Drawing.Point(60, 60); this.picboxLoadImage.Name = "picboxLoadImage"; this.picboxLoadImage.Size = new System.Drawing.Size(180, 38); this.picboxLoadImage.TabIndex = 1; this.picboxLoadImage.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(38, 22); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(249, 25); this.label1.TabIndex = 0; this.label1.Text = "Load local images or PDF files"; // // panelWebCam // this.panelWebCam.BackColor = System.Drawing.Color.Transparent; this.panelWebCam.Controls.Add(this.lblWebCamSrc); this.panelWebCam.Controls.Add(this.cbxWebCamSrc); this.panelWebCam.Controls.Add(this.lblWebCamRes); this.panelWebCam.Controls.Add(this.cbxWebCamRes); this.panelWebCam.Controls.Add(this.panelWebcamNote); this.panelWebCam.Location = new System.Drawing.Point(1, 41); this.panelWebCam.Margin = new System.Windows.Forms.Padding(0); this.panelWebCam.Name = "panelWebCam"; this.panelWebCam.Size = new System.Drawing.Size(300, 175); this.panelWebCam.TabIndex = 3; this.panelWebCam.Visible = false; // // lblWebCamSrc // this.lblWebCamSrc.AutoSize = true; this.lblWebCamSrc.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblWebCamSrc.Location = new System.Drawing.Point(38, 10); this.lblWebCamSrc.Name = "lblWebCamSrc"; this.lblWebCamSrc.Size = new System.Drawing.Size(96, 15); this.lblWebCamSrc.TabIndex = 0; this.lblWebCamSrc.Text = "Webcam Source:"; // // cbxWebCamSrc // this.cbxWebCamSrc.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxWebCamSrc.FormattingEnabled = true; this.cbxWebCamSrc.Location = new System.Drawing.Point(38, 30); this.cbxWebCamSrc.Name = "cbxWebCamSrc"; this.cbxWebCamSrc.Size = new System.Drawing.Size(216, 21); this.cbxWebCamSrc.TabIndex = 13; // // lblWebCamRes // this.lblWebCamRes.AutoSize = true; this.lblWebCamRes.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblWebCamRes.Location = new System.Drawing.Point(38, 60); this.lblWebCamRes.Name = "lblWebCamRes"; this.lblWebCamRes.Size = new System.Drawing.Size(116, 15); this.lblWebCamRes.TabIndex = 12; this.lblWebCamRes.Text = "Webcam Resolution:"; // // cbxWebCamRes // this.cbxWebCamRes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxWebCamRes.FormattingEnabled = true; this.cbxWebCamRes.Location = new System.Drawing.Point(38, 80); this.cbxWebCamRes.Name = "cbxWebCamRes"; this.cbxWebCamRes.Size = new System.Drawing.Size(216, 21); this.cbxWebCamRes.TabIndex = 13; // // panelWebcamNote // this.panelWebcamNote.Controls.Add(this.labelWebcamNote); this.panelWebcamNote.Location = new System.Drawing.Point(35, 110); this.panelWebcamNote.Name = "panelWebcamNote"; this.panelWebcamNote.Size = new System.Drawing.Size(228, 60); this.panelWebcamNote.TabIndex = 3; // // labelWebcamNote // this.labelWebcamNote.Dock = System.Windows.Forms.DockStyle.Fill; this.labelWebcamNote.ImageAlign = System.Drawing.ContentAlignment.TopLeft; this.labelWebcamNote.Location = new System.Drawing.Point(0, 0); this.labelWebcamNote.Name = "labelWebcamNote"; this.labelWebcamNote.Size = new System.Drawing.Size(228, 60); this.labelWebcamNote.TabIndex = 0; this.labelWebcamNote.Text = " Note: Please place a barcode in front of your webcam and then click \"Read Ba" + "rcode\" button. It will decode barcodes from camera stream directly."; // // panelAcquire // this.panelAcquire.BackColor = System.Drawing.Color.Transparent; this.panelAcquire.Controls.Add(this.rdbtnGray); this.panelAcquire.Controls.Add(this.cbxResolution); this.panelAcquire.Controls.Add(this.picboxScan); this.panelAcquire.Controls.Add(this.rdbtnBW); this.panelAcquire.Controls.Add(this.lbResolution); this.panelAcquire.Controls.Add(this.rdbtnColor); this.panelAcquire.Controls.Add(this.lbPixelType); this.panelAcquire.Controls.Add(this.lbSelectSource); this.panelAcquire.Controls.Add(this.cbxSource); this.panelAcquire.Location = new System.Drawing.Point(1, 41); this.panelAcquire.Margin = new System.Windows.Forms.Padding(0); this.panelAcquire.Name = "panelAcquire"; this.panelAcquire.Size = new System.Drawing.Size(300, 175); this.panelAcquire.TabIndex = 2; // // rdbtnGray // this.rdbtnGray.AutoSize = true; this.rdbtnGray.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rdbtnGray.Location = new System.Drawing.Point(165, 50); this.rdbtnGray.Name = "rdbtnGray"; this.rdbtnGray.Size = new System.Drawing.Size(49, 19); this.rdbtnGray.TabIndex = 641; this.rdbtnGray.TabStop = true; this.rdbtnGray.Text = "Gray"; this.rdbtnGray.UseVisualStyleBackColor = true; // // cbxResolution // this.cbxResolution.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxResolution.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbxResolution.FormattingEnabled = true; this.cbxResolution.Location = new System.Drawing.Point(90, 82); this.cbxResolution.Name = "cbxResolution"; this.cbxResolution.Size = new System.Drawing.Size(190, 23); this.cbxResolution.TabIndex = 643; // // picboxScan // this.picboxScan.Enabled = false; this.picboxScan.Location = new System.Drawing.Point(61, 120); this.picboxScan.Name = "picboxScan"; this.picboxScan.Size = new System.Drawing.Size(180, 38); this.picboxScan.TabIndex = 85; this.picboxScan.TabStop = false; this.picboxScan.Tag = "Scan Image"; this.picboxScan.Click += new System.EventHandler(this.picboxScan_Click); this.picboxScan.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxScan.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxScan.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxScan.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // rdbtnBW // this.rdbtnBW.AutoSize = true; this.rdbtnBW.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rdbtnBW.Location = new System.Drawing.Point(88, 50); this.rdbtnBW.Name = "rdbtnBW"; this.rdbtnBW.Size = new System.Drawing.Size(59, 19); this.rdbtnBW.TabIndex = 640; this.rdbtnBW.TabStop = true; this.rdbtnBW.Text = "B && W"; this.rdbtnBW.UseVisualStyleBackColor = true; // // lbResolution // this.lbResolution.AutoSize = true; this.lbResolution.BackColor = System.Drawing.Color.Transparent; this.lbResolution.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbResolution.Location = new System.Drawing.Point(15, 85); this.lbResolution.Name = "lbResolution"; this.lbResolution.Size = new System.Drawing.Size(69, 15); this.lbResolution.TabIndex = 83; this.lbResolution.Text = "Resolution :"; // // rdbtnColor // this.rdbtnColor.AutoSize = true; this.rdbtnColor.BackColor = System.Drawing.Color.Transparent; this.rdbtnColor.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rdbtnColor.Location = new System.Drawing.Point(232, 50); this.rdbtnColor.Name = "rdbtnColor"; this.rdbtnColor.Size = new System.Drawing.Size(54, 19); this.rdbtnColor.TabIndex = 642; this.rdbtnColor.TabStop = true; this.rdbtnColor.Text = "Color"; this.rdbtnColor.UseVisualStyleBackColor = false; // // lbPixelType // this.lbPixelType.AutoSize = true; this.lbPixelType.BackColor = System.Drawing.Color.Transparent; this.lbPixelType.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbPixelType.Location = new System.Drawing.Point(15, 50); this.lbPixelType.Name = "lbPixelType"; this.lbPixelType.Size = new System.Drawing.Size(65, 15); this.lbPixelType.TabIndex = 87; this.lbPixelType.Text = "Pixel Type :"; // // lbSelectSource // this.lbSelectSource.AutoSize = true; this.lbSelectSource.BackColor = System.Drawing.Color.Transparent; this.lbSelectSource.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbSelectSource.Location = new System.Drawing.Point(15, 15); this.lbSelectSource.Name = "lbSelectSource"; this.lbSelectSource.Size = new System.Drawing.Size(94, 15); this.lbSelectSource.TabIndex = 84; this.lbSelectSource.Text = "Scanner Source :"; // // cbxSource // this.cbxSource.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxSource.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbxSource.FormattingEnabled = true; this.cbxSource.Location = new System.Drawing.Point(120, 12); this.cbxSource.Name = "cbxSource"; this.cbxSource.Size = new System.Drawing.Size(160, 22); this.cbxSource.TabIndex = 639; // // panelReadSetting // this.panelReadSetting.BackColor = System.Drawing.Color.Transparent; this.panelReadSetting.Controls.Add(this.label6); this.panelReadSetting.Controls.Add(this.cbxBarcodeFormat); this.panelReadSetting.Location = new System.Drawing.Point(1, 41); this.panelReadSetting.Margin = new System.Windows.Forms.Padding(0); this.panelReadSetting.Name = "panelReadSetting"; this.panelReadSetting.Size = new System.Drawing.Size(300, 80); this.panelReadSetting.TabIndex = 2; this.panelReadSetting.Visible = false; // // label6 // this.label6.AutoSize = true; this.label6.BackColor = System.Drawing.Color.Transparent; this.label6.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(15, 34); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(95, 15); this.label6.TabIndex = 2; this.label6.Text = "Barcode format :"; // // cbxBarcodeFormat // this.cbxBarcodeFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxBarcodeFormat.FormattingEnabled = true; this.cbxBarcodeFormat.ItemHeight = 13; this.cbxBarcodeFormat.Location = new System.Drawing.Point(120, 30); this.cbxBarcodeFormat.Name = "cbxBarcodeFormat"; this.cbxBarcodeFormat.Size = new System.Drawing.Size(170, 21); this.cbxBarcodeFormat.TabIndex = 644; this.cbxBarcodeFormat.SelectedIndexChanged += new System.EventHandler(this.cbxBarcodeFormat_SelectedIndexChanged); // // panelReadMoreSetting // this.panelReadMoreSetting.BackColor = System.Drawing.Color.Transparent; this.panelReadMoreSetting.Location = new System.Drawing.Point(1, 41); this.panelReadMoreSetting.Margin = new System.Windows.Forms.Padding(0); this.panelReadMoreSetting.Name = "panelReadMoreSetting"; this.panelReadMoreSetting.Size = new System.Drawing.Size(300, 290); this.panelReadMoreSetting.TabIndex = 3; this.panelReadMoreSetting.Visible = false; // // panelReadBarcode // this.panelReadBarcode.BackColor = System.Drawing.Color.Transparent; this.panelReadBarcode.Controls.Add(this.picboxReadBarcode); this.panelReadBarcode.Controls.Add(this.picboxStopBarcode); this.panelReadBarcode.Location = new System.Drawing.Point(1, 41); this.panelReadBarcode.Margin = new System.Windows.Forms.Padding(0); this.panelReadBarcode.Name = "panelReadBarcode"; this.panelReadBarcode.Size = new System.Drawing.Size(300, 100); this.panelReadBarcode.TabIndex = 3; // // picboxReadBarcode // this.picboxReadBarcode.Location = new System.Drawing.Point(68, 30); this.picboxReadBarcode.Name = "picboxReadBarcode"; this.picboxReadBarcode.Size = new System.Drawing.Size(180, 38); this.picboxReadBarcode.TabIndex = 15; this.picboxReadBarcode.TabStop = false; this.picboxReadBarcode.Click += new System.EventHandler(this.picboxReadBarcode_Click); this.picboxReadBarcode.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxReadBarcode.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxReadBarcode.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxReadBarcode.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxStopBarcode // this.picboxStopBarcode.Location = new System.Drawing.Point(68, 30); this.picboxStopBarcode.Name = "picboxStopBarcode"; this.picboxStopBarcode.Size = new System.Drawing.Size(180, 38); this.picboxStopBarcode.TabIndex = 15; this.picboxStopBarcode.TabStop = false; this.picboxStopBarcode.Visible = false; this.picboxStopBarcode.Click += new System.EventHandler(this.picboxStopBarcode_Click); this.picboxStopBarcode.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxStopBarcode.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxStopBarcode.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxStopBarcode.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxFit // this.picboxFit.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxFit_Leave; this.picboxFit.Location = new System.Drawing.Point(12, 60); this.picboxFit.Name = "picboxFit"; this.picboxFit.Size = new System.Drawing.Size(61, 36); this.picboxFit.TabIndex = 88; this.picboxFit.TabStop = false; this.picboxFit.Tag = "Fit Window Size"; this.picboxFit.Click += new System.EventHandler(this.picboxFit_Click); this.picboxFit.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxFit.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxFit.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxFit.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxFit.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // picboxOriginalSize // this.picboxOriginalSize.Image = global::Barcode_Reader_Demo.Properties.Resources.picboxOriginalSize_Leave; this.picboxOriginalSize.Location = new System.Drawing.Point(12, 108); this.picboxOriginalSize.Name = "picboxOriginalSize"; this.picboxOriginalSize.Size = new System.Drawing.Size(60, 36); this.picboxOriginalSize.TabIndex = 87; this.picboxOriginalSize.TabStop = false; this.picboxOriginalSize.Tag = "Original Size"; this.picboxOriginalSize.Click += new System.EventHandler(this.picboxOriginalSize_Click); this.picboxOriginalSize.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); this.picboxOriginalSize.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); this.picboxOriginalSize.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxOriginalSize.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxOriginalSize.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); // // tbxResult // this.tbxResult.BackColor = System.Drawing.Color.White; this.tbxResult.Location = new System.Drawing.Point(1, 26); this.tbxResult.Margin = new System.Windows.Forms.Padding(0); this.tbxResult.Multiline = true; this.tbxResult.Name = "tbxResult"; this.tbxResult.ReadOnly = true; this.tbxResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.tbxResult.Size = new System.Drawing.Size(309, 570); this.tbxResult.TabIndex = 184; // // lblCloseResult // this.lblCloseResult.BackColor = System.Drawing.SystemColors.Control; this.lblCloseResult.Location = new System.Drawing.Point(290, 5); this.lblCloseResult.Name = "lblCloseResult"; this.lblCloseResult.Size = new System.Drawing.Size(16, 16); this.lblCloseResult.TabIndex = 0; this.lblCloseResult.Text = "X"; this.lblCloseResult.Click += new System.EventHandler(this.lblCloseResult_Click); this.lblCloseResult.MouseLeave += new System.EventHandler(this.lblCloseResult_MouseLeave); this.lblCloseResult.MouseHover += new System.EventHandler(this.lblCloseResult_MouseHover); // // dsViewer // this.dsViewer.Location = new System.Drawing.Point(86, 50); this.dsViewer.Name = "dsViewer"; this.dsViewer.RightToLeft = System.Windows.Forms.RightToLeft.No; this.dsViewer.SelectionRectAspectRatio = 0D; this.dsViewer.Size = new System.Drawing.Size(477, 586); this.dsViewer.TabIndex = 651; this.dsViewer.OnMouseClick += dsViewer_OnMouseClick; // // BarcodeReaderDemo // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.BackgroundImage = global::Barcode_Reader_Demo.Properties.Resources.main_bg; this.ClientSize = new System.Drawing.Size(898, 698); this.Controls.Add(this.dsViewer); this.Controls.Add(this.picboxFit); this.Controls.Add(this.picboxOriginalSize); this.Controls.Add(this.flowLayoutPanel2); this.Controls.Add(this.tbxTotalImageNum); this.Controls.Add(this.tbxCurrentImageIndex); this.Controls.Add(this.lbDiv); this.Controls.Add(this.picboxClose); this.Controls.Add(this.picboxMin); this.Controls.Add(this.cbxViewMode); this.Controls.Add(this.picboxPrevious); this.Controls.Add(this.picboxNext); this.Controls.Add(this.picboxLast); this.Controls.Add(this.picboxFirst); this.Controls.Add(this.lbMoveBar); this.Controls.Add(this.picboxDeleteAll); this.Controls.Add(this.picboxDelete); this.Controls.Add(this.picboxZoomOut); this.Controls.Add(this.picboxZoomIn); this.Controls.Add(this.picBoxWebCam); this.DoubleBuffered = true; this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Margin = new System.Windows.Forms.Padding(4); this.Name = "BarcodeReaderDemo"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Dynamsoft Barcode Reader Demo"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.BarcodeReaderDemo_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.BarcodeReaderDemo_FormClosed); this.Load += new System.EventHandler(this.DotNetTWAINDemo_Load); ((System.ComponentModel.ISupportInitialize)(this.picBoxWebCam)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxZoomOut)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxZoomIn)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxDeleteAll)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxDelete)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxFirst)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxLast)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxNext)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxPrevious)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxMin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxClose)).EndInit(); this.panelLoad.ResumeLayout(false); this.panelLoad.PerformLayout(); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.picboxLoadImage)).EndInit(); this.panelWebCam.ResumeLayout(false); this.panelWebCam.PerformLayout(); this.panelWebcamNote.ResumeLayout(false); this.panelAcquire.ResumeLayout(false); this.panelAcquire.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picboxScan)).EndInit(); this.panelReadSetting.ResumeLayout(false); this.panelReadSetting.PerformLayout(); this.panelReadMoreSetting.ResumeLayout(false); this.panelReadMoreSetting.PerformLayout(); this.panelReadBarcode.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.picboxReadBarcode)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxStopBarcode)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxFit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picboxOriginalSize)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } void dsViewer_OnMouseClick(short sImageIndex) { if(sImageIndex>=0 && sImageIndex<m_ImageCore.ImageBuffer.HowManyImagesInBuffer) { CheckImageCount(); } } #endregion private System.Windows.Forms.Label lbMoveBar; private System.Windows.Forms.PictureBox picboxZoomOut; private System.Windows.Forms.PictureBox picboxZoomIn; private System.Windows.Forms.PictureBox picboxDeleteAll; private System.Windows.Forms.PictureBox picboxDelete; private System.Windows.Forms.PictureBox picboxFirst; private System.Windows.Forms.PictureBox picboxLast; private System.Windows.Forms.PictureBox picboxNext; private System.Windows.Forms.PictureBox picboxPrevious; private System.Windows.Forms.ComboBox cbxViewMode; private System.Windows.Forms.PictureBox picboxMin; private System.Windows.Forms.PictureBox picboxClose; private System.Windows.Forms.Label lbDiv; private System.Windows.Forms.TextBox tbxCurrentImageIndex; private System.Windows.Forms.TextBox tbxTotalImageNum; //private Dynamsoft.Forms.DSViewer dsViewer; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.RadioButton rdbtnGray; private System.Windows.Forms.RadioButton rdbtnBW; private System.Windows.Forms.Label lbPixelType; private System.Windows.Forms.RadioButton rdbtnColor; private System.Windows.Forms.ComboBox cbxSource; private System.Windows.Forms.ComboBox cbxResolution; private System.Windows.Forms.PictureBox picboxScan; private System.Windows.Forms.Label lbSelectSource; private System.Windows.Forms.Label lbResolution; private System.Windows.Forms.Panel panelAcquire; private System.Windows.Forms.Panel panelLoad; private System.Windows.Forms.Panel panelWebCam; private System.Windows.Forms.Label lblWebCamSrc; private System.Windows.Forms.ComboBox cbxWebCamSrc; private System.Windows.Forms.Label lblWebCamRes; private System.Windows.Forms.ComboBox cbxWebCamRes; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox picboxLoadImage; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cbxBarcodeFormat; private System.Windows.Forms.PictureBox picboxReadBarcode; private System.Windows.Forms.PictureBox picboxStopBarcode; private System.Windows.Forms.Panel panelReadSetting; private System.Windows.Forms.Panel panelReadMoreSetting; private System.Windows.Forms.Panel panelReadBarcode; private System.Windows.Forms.TextBox tbxResult; private System.Windows.Forms.Label lblCloseResult; private System.Windows.Forms.PictureBox picboxFit; private System.Windows.Forms.PictureBox picboxOriginalSize; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label24; private System.Windows.Forms.Panel panelWebcamNote; private System.Windows.Forms.Label labelWebcamNote; private System.Windows.Forms.PictureBox picBoxWebCam; private Dynamsoft.Forms.DSViewer dsViewer; } }
#pragma warning disable CS1591 using Discord.API; using Discord.API.Voice; using Discord.Net.Converters; using Discord.Net.Udp; using Discord.Net.WebSockets; using Newtonsoft.Json; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Discord.Audio { internal class DiscordVoiceAPIClient : IDisposable { public const int MaxBitrate = 128 * 1024; public const string Mode = "xsalsa20_poly1305"; public event Func<string, string, double, Task> SentRequest { add { _sentRequestEvent.Add(value); } remove { _sentRequestEvent.Remove(value); } } private readonly AsyncEvent<Func<string, string, double, Task>> _sentRequestEvent = new AsyncEvent<Func<string, string, double, Task>>(); public event Func<VoiceOpCode, Task> SentGatewayMessage { add { _sentGatewayMessageEvent.Add(value); } remove { _sentGatewayMessageEvent.Remove(value); } } private readonly AsyncEvent<Func<VoiceOpCode, Task>> _sentGatewayMessageEvent = new AsyncEvent<Func<VoiceOpCode, Task>>(); public event Func<Task> SentDiscovery { add { _sentDiscoveryEvent.Add(value); } remove { _sentDiscoveryEvent.Remove(value); } } private readonly AsyncEvent<Func<Task>> _sentDiscoveryEvent = new AsyncEvent<Func<Task>>(); public event Func<int, Task> SentData { add { _sentDataEvent.Add(value); } remove { _sentDataEvent.Remove(value); } } private readonly AsyncEvent<Func<int, Task>> _sentDataEvent = new AsyncEvent<Func<int, Task>>(); public event Func<VoiceOpCode, object, Task> ReceivedEvent { add { _receivedEvent.Add(value); } remove { _receivedEvent.Remove(value); } } private readonly AsyncEvent<Func<VoiceOpCode, object, Task>> _receivedEvent = new AsyncEvent<Func<VoiceOpCode, object, Task>>(); public event Func<byte[], Task> ReceivedPacket { add { _receivedPacketEvent.Add(value); } remove { _receivedPacketEvent.Remove(value); } } private readonly AsyncEvent<Func<byte[], Task>> _receivedPacketEvent = new AsyncEvent<Func<byte[], Task>>(); public event Func<Exception, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } } private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>(); private readonly JsonSerializer _serializer; private readonly SemaphoreSlim _connectionLock; private readonly IUdpSocket _udp; private CancellationTokenSource _connectCancelToken; private bool _isDisposed; private ulong _nextKeepalive; public ulong GuildId { get; } internal IWebSocketClient WebSocketClient { get; } public ConnectionState ConnectionState { get; private set; } public ushort UdpPort => _udp.Port; internal DiscordVoiceAPIClient(ulong guildId, WebSocketProvider webSocketProvider, UdpSocketProvider udpSocketProvider, JsonSerializer serializer = null) { GuildId = guildId; _connectionLock = new SemaphoreSlim(1, 1); _udp = udpSocketProvider(); _udp.ReceivedDatagram += async (data, index, count) => { if (index != 0 || count != data.Length) { var newData = new byte[count]; Buffer.BlockCopy(data, index, newData, 0, count); data = newData; } await _receivedPacketEvent.InvokeAsync(data).ConfigureAwait(false); }; WebSocketClient = webSocketProvider(); //_gatewayClient.SetHeader("user-agent", DiscordConfig.UserAgent); //(Causes issues in .Net 4.6+) WebSocketClient.BinaryMessage += async (data, index, count) => { using (var compressed = new MemoryStream(data, index + 2, count - 2)) using (var decompressed = new MemoryStream()) { using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress)) zlib.CopyTo(decompressed); decompressed.Position = 0; using (var reader = new StreamReader(decompressed)) { var msg = JsonConvert.DeserializeObject<SocketFrame>(reader.ReadToEnd()); await _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload).ConfigureAwait(false); } } }; WebSocketClient.TextMessage += async text => { var msg = JsonConvert.DeserializeObject<SocketFrame>(text); await _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload).ConfigureAwait(false); }; WebSocketClient.Closed += async ex => { await DisconnectAsync().ConfigureAwait(false); await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false); }; _serializer = serializer ?? new JsonSerializer { ContractResolver = new DiscordContractResolver() }; } private void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _connectCancelToken?.Dispose(); _udp?.Dispose(); WebSocketClient?.Dispose(); _connectionLock?.Dispose(); } _isDisposed = true; } } public void Dispose() => Dispose(true); public async Task SendAsync(VoiceOpCode opCode, object payload, RequestOptions options = null) { byte[] bytes = null; payload = new SocketFrame { Operation = (int)opCode, Payload = payload }; if (payload != null) bytes = Encoding.UTF8.GetBytes(SerializeJson(payload)); await WebSocketClient.SendAsync(bytes, 0, bytes.Length, true).ConfigureAwait(false); await _sentGatewayMessageEvent.InvokeAsync(opCode).ConfigureAwait(false); } public async Task SendAsync(byte[] data, int offset, int bytes) { await _udp.SendAsync(data, offset, bytes).ConfigureAwait(false); await _sentDataEvent.InvokeAsync(bytes).ConfigureAwait(false); } //WebSocket public async Task SendHeartbeatAsync(RequestOptions options = null) { await SendAsync(VoiceOpCode.Heartbeat, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), options: options).ConfigureAwait(false); } public async Task SendIdentityAsync(ulong userId, string sessionId, string token) { await SendAsync(VoiceOpCode.Identify, new IdentifyParams { GuildId = GuildId, UserId = userId, SessionId = sessionId, Token = token }).ConfigureAwait(false); } public async Task SendSelectProtocol(string externalIp, int externalPort) { await SendAsync(VoiceOpCode.SelectProtocol, new SelectProtocolParams { Protocol = "udp", Data = new UdpProtocolInfo { Address = externalIp, Port = externalPort, Mode = Mode } }).ConfigureAwait(false); } public async Task SendSetSpeaking(bool value) { await SendAsync(VoiceOpCode.Speaking, new SpeakingParams { IsSpeaking = value, Delay = 0 }).ConfigureAwait(false); } public async Task ConnectAsync(string url) { await _connectionLock.WaitAsync().ConfigureAwait(false); try { await ConnectInternalAsync(url).ConfigureAwait(false); } finally { _connectionLock.Release(); } } private async Task ConnectInternalAsync(string url) { ConnectionState = ConnectionState.Connecting; try { _connectCancelToken?.Dispose(); _connectCancelToken = new CancellationTokenSource(); var cancelToken = _connectCancelToken.Token; WebSocketClient.SetCancelToken(cancelToken); await WebSocketClient.ConnectAsync(url).ConfigureAwait(false); _udp.SetCancelToken(cancelToken); await _udp.StartAsync().ConfigureAwait(false); ConnectionState = ConnectionState.Connected; } catch { await DisconnectInternalAsync().ConfigureAwait(false); throw; } } public async Task DisconnectAsync() { await _connectionLock.WaitAsync().ConfigureAwait(false); try { await DisconnectInternalAsync().ConfigureAwait(false); } finally { _connectionLock.Release(); } } private async Task DisconnectInternalAsync() { if (ConnectionState == ConnectionState.Disconnected) return; ConnectionState = ConnectionState.Disconnecting; try { _connectCancelToken?.Cancel(false); } catch { } //Wait for tasks to complete await _udp.StopAsync().ConfigureAwait(false); await WebSocketClient.DisconnectAsync().ConfigureAwait(false); ConnectionState = ConnectionState.Disconnected; } //Udp public async Task SendDiscoveryAsync(uint ssrc) { var packet = new byte[70]; packet[0] = (byte)(ssrc >> 24); packet[1] = (byte)(ssrc >> 16); packet[2] = (byte)(ssrc >> 8); packet[3] = (byte)(ssrc >> 0); await SendAsync(packet, 0, 70).ConfigureAwait(false); await _sentDiscoveryEvent.InvokeAsync().ConfigureAwait(false); } public async Task<ulong> SendKeepaliveAsync() { var value = _nextKeepalive++; var packet = new byte[8]; packet[0] = (byte)(value >> 0); packet[1] = (byte)(value >> 8); packet[2] = (byte)(value >> 16); packet[3] = (byte)(value >> 24); packet[4] = (byte)(value >> 32); packet[5] = (byte)(value >> 40); packet[6] = (byte)(value >> 48); packet[7] = (byte)(value >> 56); await SendAsync(packet, 0, 8).ConfigureAwait(false); return value; } public void SetUdpEndpoint(string ip, int port) { _udp.SetDestination(ip, port); } //Helpers private static double ToMilliseconds(Stopwatch stopwatch) => Math.Round((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2); private string SerializeJson(object value) { var sb = new StringBuilder(256); using (TextWriter text = new StringWriter(sb, CultureInfo.InvariantCulture)) using (JsonWriter writer = new JsonTextWriter(text)) _serializer.Serialize(writer, value); return sb.ToString(); } private T DeserializeJson<T>(Stream jsonStream) { using (TextReader text = new StreamReader(jsonStream)) using (JsonReader reader = new JsonTextReader(text)) return _serializer.Deserialize<T>(reader); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Aurora.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using LibGit2Sharp; using NUnit.Framework; namespace GitVersionCore.Tests.IntegrationTests { [TestFixture] public class FeatureBranchScenarios : TestBase { [Test] public void ShouldInheritIncrementCorrectlyWithMultiplePossibleParentsAndWeirdlyNamedDevelopBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("development"); Commands.Checkout(fixture.Repository, "development"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "development"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2"); } [Test] public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly() { var config = new Config { Branches = { { "unstable", new BranchConfig { Increment = IncrementStrategy.Minor, Regex = "unstable", SourceBranches = new List<string>(), IsSourceBranchFor = new [] { "feature" } } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("unstable"); Commands.Checkout(fixture.Repository, "unstable"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "unstable"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2", config); } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.1.0-JIRA-123.1+5"); } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMaster() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-JIRA-123.1+5"); } [Test] public void TestFeatureBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); Commands.Checkout(fixture.Repository, "feature-test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } [Test] public void TestFeaturesBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("features/test"); Commands.Checkout(fixture.Repository, "features/test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } [Test] public void WhenTwoFeatureBranchPointToTheSameCommit() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/feature1"); Commands.Checkout(fixture.Repository, "feature/feature1"); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/feature2"); Commands.Checkout(fixture.Repository, "feature/feature2"); fixture.AssertFullSemver("0.1.0-feature2.1+1"); } [Test] public void ShouldBePossibleToMergeDevelopForALongRunningBranchWhereDevelopAndMasterAreEqual() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("v1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/longrunning"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); fixture.Repository.ApplyTag("v1.1.0"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); var configuration = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; fixture.AssertFullSemver("1.2.0-longrunning.2", configuration); } [Test] public void CanUseBranchNameOffAReleaseBranch() { var config = new Config { Branches = { { "release", new BranchConfig { Tag = "build" } }, { "feature", new BranchConfig { Tag = "useBranchName" } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("release/0.3.0"); fixture.MakeATaggedCommit("v0.3.0-build.1"); fixture.MakeACommit(); fixture.BranchTo("feature/PROJ-1"); fixture.MakeACommit(); fixture.AssertFullSemver("0.3.0-PROJ-1.1+2", config); } [TestCase("alpha", "JIRA-123", "alpha")] [TestCase("useBranchName", "JIRA-123", "JIRA-123")] [TestCase("alpha.{BranchName}", "JIRA-123", "alpha.JIRA-123")] public void ShouldUseConfiguredTag(string tag, string featureName, string preReleaseTagName) { var config = new Config { Branches = { { "feature", new BranchConfig { Tag = tag } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); var featureBranchName = $"feature/{featureName}"; fixture.Repository.CreateBranch(featureBranchName); Commands.Checkout(fixture.Repository, featureBranchName); fixture.Repository.MakeCommits(5); var expectedFullSemVer = $"1.0.1-{preReleaseTagName}.1+5"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void BranchCreatedAfterFinishReleaseShouldInheritAndIncrementFromLastMasterCommitTag() { using var fixture = new BaseGitFlowRepositoryFixture("0.1.0"); //validate current version fixture.AssertFullSemver("0.2.0-alpha.1"); fixture.Repository.CreateBranch("release/0.2.0"); Commands.Checkout(fixture.Repository, "release/0.2.0"); //validate release version fixture.AssertFullSemver("0.2.0-beta.1+0"); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.ApplyTag("0.2.0"); //validate master branch version fixture.AssertFullSemver("0.2.0"); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.Branches.Remove("release/2.0.0"); fixture.Repository.MakeACommit(); //validate develop branch version after merging release 0.2.0 to master and develop (finish release) fixture.AssertFullSemver("0.3.0-alpha.1"); //create a feature branch from develop fixture.BranchTo("feature/TEST-1"); fixture.Repository.MakeACommit(); //I'm not entirely sure what the + value should be but I know the semvar major/minor/patch should be 0.3.0 fixture.AssertFullSemver("0.3.0-TEST-1.1+2"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchCreated() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+1"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+2"); } public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { TracksReleaseBranches = true, Regex = "master" } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.1+1", config); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.0.1-test.1+1", config); } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { TracksReleaseBranches = true, Regex = "master" } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.0.1+2", config); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.0.1-test.1+2", config); } } public class WhenFeatureBranchHasNoConfig { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+1"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+2"); } // ReSharper disable once MemberHidesStaticFromOuterClass public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { TracksReleaseBranches = true, Regex = "master" } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.1+1", config); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.0.1-misnamed.1+1", config); } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { TracksReleaseBranches = true, Regex = "master" } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.0.1+2", config); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.0.1-misnamed.1+2", config); } } } [Test] public void PickUpVersionFromMasterMarkedWithIsTracksReleaseBranches() { var config = new Config { VersioningMode = VersioningMode.ContinuousDelivery, Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { Tag = "pre", TracksReleaseBranches = true, } }, { "release", new BranchConfig { IsReleaseBranch = true, Tag = "rc", } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); // create a release branch and tag a release fixture.BranchTo("release/0.10.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver("0.10.0-rc.1+2", config); // switch to master and verify the version fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver("0.10.1-pre.1+1", config); // create a feature branch from master and verify the version fixture.BranchTo("MyFeatureD"); fixture.AssertFullSemver("0.10.1-MyFeatureD.1+1", config); } [Test] public void ShouldHaveAGreaterSemVerAfterDevelopIsMergedIntoFeature() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment, AssemblyVersioningScheme = AssemblyVersioningScheme.Major, AssemblyFileVersioningFormat = "{MajorMinorPatch}.{env:WeightedPreReleaseNumber ?? 0}", LegacySemVerPadding = 4, BuildMetaDataPadding = 4, CommitsSinceVersionSourcePadding = 4, CommitMessageIncrementing = CommitMessageIncrementMode.Disabled, Branches = new Dictionary<string, BranchConfig> { { "develop", new BranchConfig { PreventIncrementOfMergedBranchVersion = true } }, { "feature", new BranchConfig { Tag = "feat-{BranchName}" } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.ApplyTag("16.23.0"); fixture.MakeACommit(); fixture.BranchTo("feature/featX"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.Checkout("feature/featX"); fixture.MergeNoFF("develop"); fixture.AssertFullSemver("16.24.0-feat-featX.4", config); } } }
namespace ManagerShop.Data.DbContent.Migrations { using System; using System.Data.Entity.Migrations; public partial class Init_System_171002 : DbMigration { public override void Up() { CreateTable( "dbo.SYS_USERINFO", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), LoginAccount = c.String(maxLength: 64, unicode: false), NickName = c.String(nullable: false, maxLength: 20), PassWord = c.String(maxLength: 200), Email = c.String(maxLength: 64, unicode: false), Mobile = c.String(maxLength: 20, unicode: false), Status = c.String(maxLength: 1, unicode: false), reg_ip = c.String(maxLength: 64, unicode: false), Last_Login_Ip = c.String(maxLength: 64, unicode: false), Last_Login_Time = c.DateTime(), IsSupperManager = c.Boolean(nullable: false), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), Location = c.Int(nullable: false), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.SYS_USERAUTH", c => new { M_Index = c.Int(nullable: false, identity: true), M_Id = c.String(nullable: false, maxLength: 64, unicode: false), LoginAccount = c.String(nullable: false, maxLength: 64, unicode: false), Auth_Name = c.Int(nullable: false), Auth_Access_Token = c.String(maxLength: 4000, unicode: false), Auth_Expires = c.DateTime(), }) .PrimaryKey(t => t.M_Index) .ForeignKey("dbo.SYS_USERINFO", t => t.M_Id, cascadeDelete: true) .Index(t => t.M_Id); CreateTable( "dbo.SYS_ROLE", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), RoleName = c.String(nullable: false, maxLength: 20), Status = c.Int(nullable: false), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.SYS_MENU", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Chinese_MenuName = c.String(maxLength: 20), English_MenuName = c.String(maxLength: 20), Jap_MenuName = c.String(maxLength: 20), ParentId = c.String(maxLength: 64, unicode: false), Icon = c.String(maxLength: 50, unicode: false), Url = c.String(maxLength: 120, unicode: false), Order = c.Int(nullable: false), IsLastNode = c.Boolean(nullable: false), Status = c.String(maxLength: 1, unicode: false), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.FAC_Master_Color", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Code = c.String(maxLength: 20), English_ColorName = c.String(maxLength: 120), Japan_ColorName = c.String(maxLength: 120), Chinese_ColorName = c.String(maxLength: 120), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.FAC_Master_Company", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Code = c.String(maxLength: 20), Address = c.String(maxLength: 150), Tel = c.String(maxLength: 20), Fax = c.String(maxLength: 20), CompanyName = c.String(maxLength: 120), CompanyType = c.Int(nullable: false), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.FAC_Master_Port", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Code = c.String(maxLength: 20), PortName = c.String(maxLength: 120), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.FAC_Master_ProductName", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Code = c.String(maxLength: 20), English_ProductName = c.String(maxLength: 120), Japan_ProductName = c.String(maxLength: 120), Chinese_ProductName = c.String(maxLength: 120), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.FAC_Stock", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), StockNumber = c.Decimal(nullable: false, precision: 18, scale: 0), ProductId = c.String(nullable: false, maxLength: 64, unicode: false), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id) .ForeignKey("dbo.FAC_Product", t => t.ProductId, cascadeDelete: true) .Index(t => t.ProductId); CreateTable( "dbo.FAC_Product", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), ProductNo = c.String(maxLength: 64), JANCode = c.String(maxLength: 60), ColorId = c.String(nullable: false, maxLength: 64, unicode: false), SpecId = c.String(nullable: false, maxLength: 64, unicode: false), Weight = c.String(maxLength: 20), FullWeight = c.String(maxLength: 20), Capacity = c.String(maxLength: 20), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), ProductNameId = c.String(nullable: false, maxLength: 64, unicode: false), }) .PrimaryKey(t => t.M_Id) .ForeignKey("dbo.FAC_Master_Color", t => t.ColorId, cascadeDelete: true) .ForeignKey("dbo.FAC_Master_ProductName", t => t.ProductNameId, cascadeDelete: true) .ForeignKey("dbo.FAC_Master_Spec", t => t.SpecId, cascadeDelete: true) .Index(t => t.ColorId) .Index(t => t.SpecId) .Index(t => t.ProductNameId); CreateTable( "dbo.FAC_Master_Spec", c => new { M_Id = c.String(nullable: false, maxLength: 64, unicode: false), Code = c.String(maxLength: 20), SpecName = c.String(maxLength: 120), CreateUserId = c.String(maxLength: 64, unicode: false), CreateTime = c.DateTime(), ModifyUserId = c.String(maxLength: 64, unicode: false), ModifyTime = c.DateTime(), }) .PrimaryKey(t => t.M_Id); CreateTable( "dbo.SYS_MENUROLE", c => new { MenuId = c.String(nullable: false, maxLength: 64, unicode: false), RoleId = c.String(nullable: false, maxLength: 64, unicode: false), }) .PrimaryKey(t => new { t.MenuId, t.RoleId }) .ForeignKey("dbo.SYS_MENU", t => t.MenuId, cascadeDelete: true) .ForeignKey("dbo.SYS_ROLE", t => t.RoleId, cascadeDelete: true) .Index(t => t.MenuId) .Index(t => t.RoleId); CreateTable( "dbo.SYS_ROLEUSER", c => new { RoleId = c.String(nullable: false, maxLength: 64, unicode: false), UserId = c.String(nullable: false, maxLength: 64, unicode: false), }) .PrimaryKey(t => new { t.RoleId, t.UserId }) .ForeignKey("dbo.SYS_ROLE", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.SYS_USERINFO", t => t.UserId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); } public override void Down() { DropForeignKey("dbo.FAC_Stock", "ProductId", "dbo.FAC_Product"); DropForeignKey("dbo.FAC_Product", "SpecId", "dbo.FAC_Master_Spec"); DropForeignKey("dbo.FAC_Product", "ProductNameId", "dbo.FAC_Master_ProductName"); DropForeignKey("dbo.FAC_Product", "ColorId", "dbo.FAC_Master_Color"); DropForeignKey("dbo.SYS_ROLEUSER", "UserId", "dbo.SYS_USERINFO"); DropForeignKey("dbo.SYS_ROLEUSER", "RoleId", "dbo.SYS_ROLE"); DropForeignKey("dbo.SYS_MENUROLE", "RoleId", "dbo.SYS_ROLE"); DropForeignKey("dbo.SYS_MENUROLE", "MenuId", "dbo.SYS_MENU"); DropForeignKey("dbo.SYS_USERAUTH", "M_Id", "dbo.SYS_USERINFO"); DropIndex("dbo.SYS_ROLEUSER", new[] { "UserId" }); DropIndex("dbo.SYS_ROLEUSER", new[] { "RoleId" }); DropIndex("dbo.SYS_MENUROLE", new[] { "RoleId" }); DropIndex("dbo.SYS_MENUROLE", new[] { "MenuId" }); DropIndex("dbo.FAC_Product", new[] { "ProductNameId" }); DropIndex("dbo.FAC_Product", new[] { "SpecId" }); DropIndex("dbo.FAC_Product", new[] { "ColorId" }); DropIndex("dbo.FAC_Stock", new[] { "ProductId" }); DropIndex("dbo.SYS_USERAUTH", new[] { "M_Id" }); DropTable("dbo.SYS_ROLEUSER"); DropTable("dbo.SYS_MENUROLE"); DropTable("dbo.FAC_Master_Spec"); DropTable("dbo.FAC_Product"); DropTable("dbo.FAC_Stock"); DropTable("dbo.FAC_Master_ProductName"); DropTable("dbo.FAC_Master_Port"); DropTable("dbo.FAC_Master_Company"); DropTable("dbo.FAC_Master_Color"); DropTable("dbo.SYS_MENU"); DropTable("dbo.SYS_ROLE"); DropTable("dbo.SYS_USERAUTH"); DropTable("dbo.SYS_USERINFO"); } } }
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 SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the PhenomenonOffering class. /// </summary> [Serializable] public partial class PhenomenonOfferingCollection : ActiveList<PhenomenonOffering, PhenomenonOfferingCollection> { public PhenomenonOfferingCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PhenomenonOfferingCollection</returns> public PhenomenonOfferingCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PhenomenonOffering 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 PhenomenonOffering table. /// </summary> [Serializable] public partial class PhenomenonOffering : ActiveRecord<PhenomenonOffering>, IActiveRecord { #region .ctors and Default Settings public PhenomenonOffering() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PhenomenonOffering(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PhenomenonOffering(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PhenomenonOffering(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PhenomenonOffering", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarPhenomenonID = new TableSchema.TableColumn(schema); colvarPhenomenonID.ColumnName = "PhenomenonID"; colvarPhenomenonID.DataType = DbType.Guid; colvarPhenomenonID.MaxLength = 0; colvarPhenomenonID.AutoIncrement = false; colvarPhenomenonID.IsNullable = false; colvarPhenomenonID.IsPrimaryKey = false; colvarPhenomenonID.IsForeignKey = true; colvarPhenomenonID.IsReadOnly = false; colvarPhenomenonID.DefaultSetting = @""; colvarPhenomenonID.ForeignKeyTableName = "Phenomenon"; schema.Columns.Add(colvarPhenomenonID); TableSchema.TableColumn colvarOfferingID = new TableSchema.TableColumn(schema); colvarOfferingID.ColumnName = "OfferingID"; colvarOfferingID.DataType = DbType.Guid; colvarOfferingID.MaxLength = 0; colvarOfferingID.AutoIncrement = false; colvarOfferingID.IsNullable = false; colvarOfferingID.IsPrimaryKey = false; colvarOfferingID.IsForeignKey = true; colvarOfferingID.IsReadOnly = false; colvarOfferingID.DefaultSetting = @""; colvarOfferingID.ForeignKeyTableName = "Offering"; schema.Columns.Add(colvarOfferingID); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = true; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("PhenomenonOffering",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("PhenomenonID")] [Bindable(true)] public Guid PhenomenonID { get { return GetColumnValue<Guid>(Columns.PhenomenonID); } set { SetColumnValue(Columns.PhenomenonID, value); } } [XmlAttribute("OfferingID")] [Bindable(true)] public Guid OfferingID { get { return GetColumnValue<Guid>(Columns.OfferingID); } set { SetColumnValue(Columns.OfferingID, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid? UserId { get { return GetColumnValue<Guid?>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.DataLogCollection DataLogRecords() { return new SAEON.Observations.Data.DataLogCollection().Where(DataLog.Columns.PhenomenonOfferingID, Id).Load(); } public SAEON.Observations.Data.DataSourceTransformationCollection DataSourceTransformationRecords() { return new SAEON.Observations.Data.DataSourceTransformationCollection().Where(DataSourceTransformation.Columns.NewPhenomenonOfferingID, Id).Load(); } public SAEON.Observations.Data.DataSourceTransformationCollection DataSourceTransformationRecordsFromPhenomenonOffering() { return new SAEON.Observations.Data.DataSourceTransformationCollection().Where(DataSourceTransformation.Columns.PhenomenonOfferingID, Id).Load(); } public SAEON.Observations.Data.ImportBatchSummaryCollection ImportBatchSummaryRecords() { return new SAEON.Observations.Data.ImportBatchSummaryCollection().Where(ImportBatchSummary.Columns.PhenomenonOfferingID, Id).Load(); } public SAEON.Observations.Data.ObservationCollection ObservationRecords() { return new SAEON.Observations.Data.ObservationCollection().Where(Observation.Columns.PhenomenonOfferingID, Id).Load(); } public SAEON.Observations.Data.SchemaColumnCollection SchemaColumnRecords() { return new SAEON.Observations.Data.SchemaColumnCollection().Where(SchemaColumn.Columns.PhenomenonOfferingID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this PhenomenonOffering /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } private SAEON.Observations.Data.Offering _Offering = null; /// <summary> /// Returns a Offering ActiveRecord object related to this PhenomenonOffering /// /// </summary> public SAEON.Observations.Data.Offering Offering { // get { return SAEON.Observations.Data.Offering.FetchByID(this.OfferingID); } get { return _Offering ?? (_Offering = SAEON.Observations.Data.Offering.FetchByID(this.OfferingID)); } set { SetColumnValue("OfferingID", value.Id); } } private SAEON.Observations.Data.Phenomenon _Phenomenon = null; /// <summary> /// Returns a Phenomenon ActiveRecord object related to this PhenomenonOffering /// /// </summary> public SAEON.Observations.Data.Phenomenon Phenomenon { // get { return SAEON.Observations.Data.Phenomenon.FetchByID(this.PhenomenonID); } get { return _Phenomenon ?? (_Phenomenon = SAEON.Observations.Data.Phenomenon.FetchByID(this.PhenomenonID)); } set { SetColumnValue("PhenomenonID", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,Guid varPhenomenonID,Guid varOfferingID,Guid? varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { PhenomenonOffering item = new PhenomenonOffering(); item.Id = varId; item.PhenomenonID = varPhenomenonID; item.OfferingID = varOfferingID; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,Guid varPhenomenonID,Guid varOfferingID,Guid? varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { PhenomenonOffering item = new PhenomenonOffering(); item.Id = varId; item.PhenomenonID = varPhenomenonID; item.OfferingID = varOfferingID; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn PhenomenonIDColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn OfferingIDColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string PhenomenonID = @"PhenomenonID"; public static string OfferingID = @"OfferingID"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using Hotcakes.Commerce.Membership; using Hotcakes.Commerce.Security; using Hotcakes.Commerce.Utilities; using Hotcakes.Modules.Core.Admin.AppCode; namespace Hotcakes.Modules.Core.Admin.Configuration { partial class Fraud : BaseAdminPage { private FraudRuleRepository repository; protected override void OnLoad(EventArgs e) { base.OnLoad(e); repository = new FraudRuleRepository(HccApp.CurrentRequestContext); if (!Page.IsPostBack) { LoadLists(); } } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); PageTitle = Localization.GetString("FraudScreening"); CurrentTab = AdminTabType.Configuration; ValidateCurrentUserHasPermission(SystemPermissions.SettingsView); } private void LoadLists() { var rules = repository.FindForStore(HccApp.CurrentStore.Id); var emailRules = new SortableCollection<FraudRule>(); var domainRules = new SortableCollection<FraudRule>(); var ipRules = new SortableCollection<FraudRule>(); var PHrules = new SortableCollection<FraudRule>(); var CCrules = new SortableCollection<FraudRule>(); for (var i = 0; i <= rules.Count - 1; i++) { switch (rules[i].RuleType) { case FraudRuleType.DomainName: domainRules.Add(rules[i]); break; case FraudRuleType.EmailAddress: emailRules.Add(rules[i]); break; case FraudRuleType.IPAddress: ipRules.Add(rules[i]); break; case FraudRuleType.PhoneNumber: PHrules.Add(rules[i]); break; case FraudRuleType.CreditCardNumber: CCrules.Add(rules[i]); break; } } emailRules.Sort("RuleValue"); domainRules.Sort("RuleValue"); ipRules.Sort("RuleValue"); PHrules.Sort("RuleValue"); CCrules.Sort("RuleValue"); lstEmail.DataSource = emailRules; lstEmail.DataTextField = "RuleValue"; lstEmail.DataValueField = "Bvin"; lstEmail.DataBind(); lstDomain.DataTextField = "RuleValue"; lstDomain.DataValueField = "Bvin"; lstDomain.DataSource = domainRules; lstDomain.DataBind(); lstIP.DataTextField = "RuleValue"; lstIP.DataValueField = "Bvin"; lstIP.DataSource = ipRules; lstIP.DataBind(); lstPhoneNumber.DataTextField = "RuleValue"; lstPhoneNumber.DataValueField = "Bvin"; lstPhoneNumber.DataSource = PHrules; lstPhoneNumber.DataBind(); lstCreditCard.DataTextField = "RuleValue"; lstCreditCard.DataValueField = "Bvin"; lstCreditCard.DataSource = CCrules; lstCreditCard.DataBind(); EmailField.Text = string.Empty; DomainField.Text = string.Empty; IPField.Text = string.Empty; PhoneNumberField.Text = string.Empty; CreditCardField.Text = string.Empty; } // Email Address protected void btnNewEmail_Click(object sender, EventArgs e) { if (EmailField.Text.Trim().Length > 0) { var r = new FraudRule(); r.RuleType = FraudRuleType.EmailAddress; r.RuleValue = EmailField.Text.Trim().ToLower(); repository.Create(r); } LoadLists(); } protected void btnDeleteEmail_Click(object sender, EventArgs e) { for (var i = 0; i <= lstEmail.Items.Count - 1; i++) { if (lstEmail.Items[i].Selected) { DeleteRule(lstEmail.Items[i].Value); } } LoadLists(); } // IP Address protected void btnNewIP_Click(object sender, EventArgs e) { if (IPField.Text.Trim().Length > 0) { var r = new FraudRule(); r.RuleType = FraudRuleType.IPAddress; r.RuleValue = IPField.Text.Trim().ToLower(); repository.Create(r); } LoadLists(); } protected void btnDeleteIP_Click(object sender, EventArgs e) { for (var i = 0; i <= lstIP.Items.Count - 1; i++) { if (lstIP.Items[i].Selected) { DeleteRule(lstIP.Items[i].Value); } } LoadLists(); } // Domain Name protected void btnNewDomain_Click(object sender, EventArgs e) { if (DomainField.Text.Trim().Length > 0) { var r = new FraudRule(); r.RuleType = FraudRuleType.DomainName; r.RuleValue = DomainField.Text.Trim().ToLower(); repository.Create(r); } LoadLists(); } protected void btnDeleteDomain_Click(object sender, EventArgs e) { for (var i = 0; i <= lstDomain.Items.Count - 1; i++) { if (lstDomain.Items[i].Selected) { DeleteRule(lstDomain.Items[i].Value); } } LoadLists(); } // Phone Number protected void btnNewPhoneNumber_Click(object sender, EventArgs e) { if (PhoneNumberField.Text.Trim().Length > 0) { var r = new FraudRule(); r.RuleType = FraudRuleType.PhoneNumber; r.RuleValue = PhoneNumberField.Text.Trim().ToLower(); repository.Create(r); } LoadLists(); } protected void btnDeletePhoneNumber_Click(object sender, EventArgs e) { for (var i = 0; i <= lstPhoneNumber.Items.Count - 1; i++) { if (lstPhoneNumber.Items[i].Selected) { DeleteRule(lstPhoneNumber.Items[i].Value); } } LoadLists(); } // Credit Card Number protected void btnNewCCNumber_Click(object sender, EventArgs e) { if (CreditCardField.Text.Trim().Length > 0) { var r = new FraudRule(); r.RuleType = FraudRuleType.CreditCardNumber; r.RuleValue = CreditCardField.Text.Trim().ToLower(); repository.Create(r); } LoadLists(); } protected void btnDeleteCCNumber_Click(object sender, EventArgs e) { for (var i = 0; i <= lstCreditCard.Items.Count - 1; i++) { if (lstCreditCard.Items[i].Selected) { DeleteRule(lstCreditCard.Items[i].Value); } } LoadLists(); } private void DeleteRule(string bvin) { repository.Delete(bvin); } } }
using System; using System.Collections.Generic; using System.Net; using UltimateTeam.Toolkit.Constants; using UltimateTeam.Toolkit.Extensions; using UltimateTeam.Toolkit.Models; using UltimateTeam.Toolkit.Parameters; using UltimateTeam.Toolkit.Requests; using UltimateTeam.Toolkit.Services; namespace UltimateTeam.Toolkit.Factories { public class FutRequestFactories { private readonly Resources _webResources = new Resources(AppVersion.WebApp); private readonly Resources _mobileResources = new Resources(AppVersion.CompanionApp); private Resources _resources; private string _phishingToken; private string _sessionId; private string _nucleusId; private string _personaId; private IHttpClient _httpClient; private Func<LoginDetails, ITwoFactorCodeProvider, IFutRequest<LoginResponse>> _loginRequestFactory; private Func<SearchParameters, IFutRequest<AuctionResponse>> _searchRequestFactory; private Func<AuctionInfo, uint, IFutRequest<AuctionResponse>> _placeBidRequestFactory; private Func<long, IFutRequest<Item>> _itemRequestFactory; private Func<AuctionInfo, IFutRequest<byte[]>> _playerImageRequestFactory; private Func<AuctionInfo, IFutRequest<byte[]>> _clubImageRequestFactory; private Func<Item, IFutRequest<byte[]>> _nationImageRequestFactory; private Func<IEnumerable<long>, IFutRequest<AuctionResponse>> _tradeStatusRequestFactory; private Func<IFutRequest<CreditsResponse>> _creditsRequestFactory; private Func<IFutRequest<AuctionResponse>> _tradePileRequestFactory; private Func<IFutRequest<WatchlistResponse>> _watchlistRequestFactory; private Func<IFutRequest<ClubItemResponse>> _clubItemRequestFactory; private Func<IFutRequest<SquadListResponse>> _squadListRequestFactory; private Func<IFutRequest<PurchasedItemsResponse>> _purchaseditemsRequestFactory; private Func<AuctionDetails, IFutRequest<ListAuctionResponse>> _listAuctionRequestFactory; private Func<IEnumerable<AuctionInfo>, IFutRequest<byte>> _addToWatchlistRequestFactory; private Func<IEnumerable<AuctionInfo>, IFutRequest<byte>> _removeFromWatchlistRequestFactory; private Func<AuctionInfo, IFutRequest<byte>> _removeFromTradePileRequestFactory; private Func<ushort, IFutRequest<SquadDetailsResponse>> _squadDetailsRequestFactory; private Func<ItemData, IFutRequest<SendItemToTradePileResponse>> _sendItemToTradePileRequestFactory; private Func<ItemData, IFutRequest<SendItemToClubResponse>> _sendItemToClubRequestFactory; private Func<IEnumerable<long>, IFutRequest<QuickSellResponse>> _quickSellRequestFactory; private Func<IFutRequest<PileSizeResponse>> _pileSizeRequestFactory; private Func<IFutRequest<ConsumablesResponse>> _consumablesRequestFactory; private Func<IFutRequest<RelistResponse>> _reListRequestFactory; private Func<IFutRequest<ListGiftsResponse>> _giftListRequestFactory; private Func<int, IFutRequest<byte>> _giftRequestFactory; private Func<long, IFutRequest<DefinitionResponse>> _definitionRequestFactory; private Func<IEnumerable<long>, IFutRequest<List<PriceRange>>> _getpriceRangesFactory; private Func<IFutRequest<CaptchaResponse>> _getCaptchaFactory; private Func<IFutRequest<byte>> _removeSoldItemsFromTradepileRequestFactory; private Func<int, IFutRequest<byte>> _validateCaptchaFactory; private Func<IFutRequest<StoreResponse>> _getPackDetailsFactory; private Func<PackDetails, IFutRequest<PurchasedPackResponse>> _buyPackFactory; public FutRequestFactories() { CookieContainer = new CookieContainer(); } public FutRequestFactories(CookieContainer cookieContainer) { CookieContainer = cookieContainer; } public CookieContainer CookieContainer { get; } public string PhishingToken { get { return _phishingToken; } set { value.ThrowIfInvalidArgument(); _phishingToken = value; } } public string SessionId { get { return _sessionId; } set { value.ThrowIfInvalidArgument(); _sessionId = value; } } public string NucleusId { get { return _nucleusId; } set { value.ThrowIfInvalidArgument(); _nucleusId = value; } } public string PersonaId { get { return _personaId; } set { value.ThrowIfInvalidArgument(); _personaId = value; } } public AppVersion AppVersion { get; set; } internal IHttpClient HttpClient { get { var httpClient = _httpClient ?? (_httpClient = new HttpClientWrapper()); httpClient.ClearRequestHeaders(); return httpClient; } set { value.ThrowIfNullArgument(); _httpClient = value; } } public Func<LoginDetails, ITwoFactorCodeProvider, IFutRequest<LoginResponse>> LoginRequestFactory { get { return _loginRequestFactory ?? (_loginRequestFactory = (details, twoFactorCodeProvider) => { AppVersion = details.AppVersion; if (details.Platform == Platform.Xbox360 || details.Platform == Platform.XboxOne) { _webResources.FutHome = Resources.FutHomeXbox; _mobileResources.FutHome = Resources.FutHomeXbox; _mobileResources.Validate = Resources.ValidateXbox; _mobileResources.Auth = Resources.AuthXbox; _mobileResources.AccountInfo = Resources.AccountInfoXbox; } if (details.AppVersion == AppVersion.WebApp) { var loginRequest = new LoginRequest(details, twoFactorCodeProvider) { HttpClient = HttpClient, Resources = _webResources }; _resources = _webResources; loginRequest.SetCookieContainer(CookieContainer); return loginRequest; } else if (details.AppVersion == AppVersion.CompanionApp) { var loginRequest = new LoginRequestMobile(details, twoFactorCodeProvider) { HttpClient = HttpClient, Resources = _mobileResources }; _resources = _mobileResources; loginRequest.SetCookieContainer(CookieContainer); return loginRequest; } else { var loginRequest = new LoginRequest(details, twoFactorCodeProvider) { HttpClient = HttpClient, Resources = _webResources }; _resources = _webResources; loginRequest.SetCookieContainer(CookieContainer); return loginRequest; } }); } set { value.ThrowIfNullArgument(); _loginRequestFactory = value; } } private T SetSharedRequestProperties<T>(T request) where T : FutRequestBase { request.PhishingToken = PhishingToken; request.SessionId = SessionId; request.HttpClient = HttpClient; request.Resources = _resources; request.NucleusId = _nucleusId; request.AppVersion = AppVersion; return request; } public Func<SearchParameters, IFutRequest<AuctionResponse>> SearchRequestFactory { get { return _searchRequestFactory ?? (_searchRequestFactory = parameters => SetSharedRequestProperties(new SearchRequest(parameters))); } set { value.ThrowIfNullArgument(); _searchRequestFactory = value; } } public Func<AuctionInfo, uint, IFutRequest<AuctionResponse>> PlaceBidRequestFactory { get { return _placeBidRequestFactory ?? (_placeBidRequestFactory = (info, amount) => SetSharedRequestProperties(new PlaceBidRequest(info, amount))); } set { value.ThrowIfNullArgument(); _placeBidRequestFactory = value; } } public Func<long, IFutRequest<Item>> ItemRequestFactory { get { return _itemRequestFactory ?? (_itemRequestFactory = baseId => SetSharedRequestProperties(new ItemRequest(baseId))); } set { value.ThrowIfNullArgument(); _itemRequestFactory = value; } } public Func<AuctionInfo, IFutRequest<byte[]>> PlayerImageRequestFactory { get { return _playerImageRequestFactory ?? (_playerImageRequestFactory = info => SetSharedRequestProperties(new PlayerImageRequest(info))); } set { value.ThrowIfNullArgument(); _playerImageRequestFactory = value; } } public Func<AuctionInfo, IFutRequest<byte[]>> ClubImageRequestFactory { get { return _clubImageRequestFactory ?? (_clubImageRequestFactory = info => SetSharedRequestProperties(new ClubImageRequest(info))); } set { value.ThrowIfNullArgument(); _clubImageRequestFactory = value; } } public Func<Item, IFutRequest<byte[]>> NationImageRequestFactory { get { return _nationImageRequestFactory ?? (_nationImageRequestFactory = info => SetSharedRequestProperties(new NationImageRequest(info))); } set { value.ThrowIfNullArgument(); _nationImageRequestFactory = value; } } public Func<IEnumerable<long>, IFutRequest<AuctionResponse>> TradeStatusRequestFactory { get { return _tradeStatusRequestFactory ?? (_tradeStatusRequestFactory = tradeIds => SetSharedRequestProperties(new TradeStatusRequest(tradeIds))); } set { value.ThrowIfNullArgument(); _tradeStatusRequestFactory = value; } } public Func<IFutRequest<CreditsResponse>> CreditsRequestFactory { get { return _creditsRequestFactory ?? (_creditsRequestFactory = () => SetSharedRequestProperties(new CreditsRequest())); } set { value.ThrowIfNullArgument(); _creditsRequestFactory = value; } } public Func<IFutRequest<AuctionResponse>> TradePileRequestFactory { get { return _tradePileRequestFactory ?? (_tradePileRequestFactory = () => SetSharedRequestProperties(new TradePileRequest())); } set { value.ThrowIfNullArgument(); _tradePileRequestFactory = value; } } public Func<IFutRequest<WatchlistResponse>> WatchlistRequestFactory { get { return _watchlistRequestFactory ?? (_watchlistRequestFactory = () => SetSharedRequestProperties(new WatchlistRequest())); } set { value.ThrowIfNullArgument(); _watchlistRequestFactory = value; } } public Func<IFutRequest<ClubItemResponse>> ClubItemRequestFactory { get { return _clubItemRequestFactory ?? (_clubItemRequestFactory = () => SetSharedRequestProperties(new ClubItemRequest())); } set { value.ThrowIfNullArgument(); _clubItemRequestFactory = value; } } public Func<IFutRequest<SquadListResponse>> SquadListRequestFactory { get { return _squadListRequestFactory ?? (_squadListRequestFactory = () => SetSharedRequestProperties(new SquadListRequest())); } set { value.ThrowIfNullArgument(); _squadListRequestFactory = value; } } public Func<IFutRequest<PurchasedItemsResponse>> PurchasedItemsRequestFactory { get { return _purchaseditemsRequestFactory ?? (_purchaseditemsRequestFactory = () => SetSharedRequestProperties(new PurchasedItemsRequest())); } set { value.ThrowIfNullArgument(); _purchaseditemsRequestFactory = value; } } public Func<AuctionDetails, IFutRequest<ListAuctionResponse>> ListAuctionFactory { get { return _listAuctionRequestFactory ?? (_listAuctionRequestFactory = details => SetSharedRequestProperties(new ListAuctionRequest(details))); } set { value.ThrowIfNullArgument(); _listAuctionRequestFactory = value; } } public Func<IEnumerable<AuctionInfo>, IFutRequest<byte>> AddToWatchlistRequestFactory { get { return _addToWatchlistRequestFactory ?? (_addToWatchlistRequestFactory = info => SetSharedRequestProperties(new AddToWatchlistRequest(info))); } set { value.ThrowIfNullArgument(); _addToWatchlistRequestFactory = value; } } public Func<IEnumerable<AuctionInfo>, IFutRequest<byte>> RemoveFromWatchlistRequestFactory { get { return _removeFromWatchlistRequestFactory ?? (_removeFromWatchlistRequestFactory = info => SetSharedRequestProperties(new RemoveFromWatchlistRequest(info))); } set { value.ThrowIfNullArgument(); _removeFromWatchlistRequestFactory = value; } } public Func<AuctionInfo, IFutRequest<byte>> RemoveFromTradePileRequestFactory { get { return _removeFromTradePileRequestFactory ?? (_removeFromTradePileRequestFactory = info => SetSharedRequestProperties(new RemoveFromTradePileRequest(info))); } set { value.ThrowIfNullArgument(); _removeFromTradePileRequestFactory = value; } } public Func<ushort, IFutRequest<SquadDetailsResponse>> SquadDetailsRequestFactory { get { return _squadDetailsRequestFactory ?? (_squadDetailsRequestFactory = squadId => SetSharedRequestProperties(new SquadDetailsRequest(squadId, _personaId))); } set { value.ThrowIfNullArgument(); _squadDetailsRequestFactory = value; } } public Func<ItemData, IFutRequest<SendItemToClubResponse>> SendItemToClubRequestFactory { get { return _sendItemToClubRequestFactory ?? (_sendItemToClubRequestFactory = itemData => SetSharedRequestProperties(new SendItemToClubRequest(itemData))); } set { value.ThrowIfNullArgument(); _sendItemToClubRequestFactory = value; } } public Func<ItemData, IFutRequest<SendItemToTradePileResponse>> SendItemToTradePileRequestFactory { get { return _sendItemToTradePileRequestFactory ?? (_sendItemToTradePileRequestFactory = itemData => SetSharedRequestProperties(new SendItemToTradePileRequest(itemData))); } set { value.ThrowIfNullArgument(); _sendItemToTradePileRequestFactory = value; } } public Func<IEnumerable<long>, IFutRequest<QuickSellResponse>> QuickSellRequestFactory { get { return _quickSellRequestFactory ?? (_quickSellRequestFactory = itemId => SetSharedRequestProperties(new QuickSellRequest(itemId))); } set { value.ThrowIfNullArgument(); _quickSellRequestFactory = value; } } public Func<IFutRequest<PileSizeResponse>> PileSizeRequestFactory { get { return _pileSizeRequestFactory ?? (_pileSizeRequestFactory = () => SetSharedRequestProperties(new PileSizeRequest())); } set { value.ThrowIfNullArgument(); _pileSizeRequestFactory = value; } } public Func<IFutRequest<ConsumablesResponse>> ConsumablesRequestFactory { get { return _consumablesRequestFactory ?? (_consumablesRequestFactory = () => SetSharedRequestProperties(new ConsumablesRequest())); } set { value.ThrowIfNullArgument(); _consumablesRequestFactory = value; } } public Func<long, IFutRequest<DefinitionResponse>> DefinitionRequestFactory { get { return _definitionRequestFactory ?? (_definitionRequestFactory = baseId => SetSharedRequestProperties(new DefinitionRequest(baseId))); } set { value.ThrowIfNullArgument(); _definitionRequestFactory = value; } } public Func<IFutRequest<RelistResponse>> ReListRequestFactory { get { return _reListRequestFactory ?? (_reListRequestFactory = () => SetSharedRequestProperties(new ReListRequest())); } set { value.ThrowIfNullArgument(); _reListRequestFactory = value; } } public Func<IFutRequest<ListGiftsResponse>> GiftListRequestFactory { get { return _giftListRequestFactory ?? (_giftListRequestFactory = () => SetSharedRequestProperties(new ListGiftsRequest())); } set { value.ThrowIfNullArgument(); _giftListRequestFactory = value; } } public Func<int, IFutRequest<byte>> GiftRequestFactory { get { return _giftRequestFactory ?? (_giftRequestFactory = giftId => SetSharedRequestProperties(new GiftRequest(giftId))); } set { value.ThrowIfNullArgument(); _giftRequestFactory = value; } } public Func<IEnumerable<long>, IFutRequest<List<PriceRange>>> GetPriceRangesFactory { get { return _getpriceRangesFactory ?? (_getpriceRangesFactory = itemIds => SetSharedRequestProperties(new PriceRangesRequest(itemIds))); } set { value.ThrowIfNullArgument(); _getpriceRangesFactory = value; } } public Func<int, IFutRequest<byte>> ValidateCaptchaFactory { get { return _validateCaptchaFactory ?? (_validateCaptchaFactory = answer => SetSharedRequestProperties(new ValidateCaptcha(answer))); } set { value.ThrowIfNullArgument(); _validateCaptchaFactory = value; } } public Func<IFutRequest<CaptchaResponse>> GetCaptchaFactory { get { return _getCaptchaFactory ?? (_getCaptchaFactory = () => SetSharedRequestProperties(new CaptchaRequest())); } set { value.ThrowIfNullArgument(); _getCaptchaFactory = value; } } public Func<IFutRequest<byte>> RemoveSoldItemsFromTradePileRequestFactory { get { return _removeSoldItemsFromTradepileRequestFactory ?? (_removeSoldItemsFromTradepileRequestFactory = () => SetSharedRequestProperties(new RemoveSoldItemsFromTradePileRequest())); } set { value.ThrowIfNullArgument(); _removeSoldItemsFromTradepileRequestFactory = value; } } public Func<IFutRequest<StoreResponse>> GetPackDetailsFactory { get { return _getPackDetailsFactory ?? (_getPackDetailsFactory = () => SetSharedRequestProperties(new StoreRequest())); } set { value.ThrowIfNullArgument(); _getPackDetailsFactory = value; } } public Func<PackDetails, IFutRequest<PurchasedPackResponse>> BuyPackRequestFactory { get { return _buyPackFactory ?? (_buyPackFactory = packDetails => SetSharedRequestProperties(new PackRequest(packDetails))); } set { value.ThrowIfNullArgument(); _buyPackFactory = value; } } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Reflection; using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2; namespace UnityEngine.AssetBundles.GraphTool { /// <summary> /// IPrefabBuilder is an interface to create Prefab AssetReference from incoming asset group. /// Subclass of IPrefabBuilder must have CUstomPrefabBuilder attribute. /// </summary> public interface IPrefabBuilder { /** * * @result Name of prefab file if prefab can be created. null if not. */ /// <summary> /// Determines whether this instance can create prefab with the specified groupKey objects. /// </summary> /// <returns><c>true</c> if this instance can create prefab the specified groupKey objects; otherwise, <c>false</c>.</returns> /// <param name="groupKey">Group key.</param> /// <param name="objects">Objects.</param> string CanCreatePrefab (string groupKey, List<UnityEngine.Object> objects); /// <summary> /// Creates the prefab. /// </summary> /// <returns>The prefab.</returns> /// <param name="groupKey">Group key.</param> /// <param name="objects">Objects.</param> UnityEngine.GameObject CreatePrefab (string groupKey, List<UnityEngine.Object> objects); /// <summary> /// Draw Inspector GUI for this PrefabBuilder. /// </summary> /// <param name="onValueChanged">On value changed.</param> void OnInspectorGUI (Action onValueChanged); } /// <summary> /// Custom prefab builder attribute. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class CustomPrefabBuilder : Attribute { private string m_name; private string m_version; private int m_assetThreshold; private const int kDEFAULT_ASSET_THRES = 10; /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return m_name; } } /// <summary> /// Gets the version. /// </summary> /// <value>The version.</value> public string Version { get { return m_version; } } /// <summary> /// Gets the asset threshold. /// </summary> /// <value>The asset threshold.</value> public int AssetThreshold { get { return m_assetThreshold; } } public CustomPrefabBuilder (string name) { m_name = name; m_version = string.Empty; m_assetThreshold = kDEFAULT_ASSET_THRES; } public CustomPrefabBuilder (string name, string version) { m_name = name; m_version = version; m_assetThreshold = kDEFAULT_ASSET_THRES; } public CustomPrefabBuilder (string name, string version, int itemThreashold) { m_name = name; m_version = version; m_assetThreshold = itemThreashold; } } public class PrefabBuilderUtility { private static Dictionary<string, string> s_attributeAssemblyQualifiedNameMap; public static Dictionary<string, string> GetAttributeAssemblyQualifiedNameMap () { if(s_attributeAssemblyQualifiedNameMap == null) { // attribute name or class name : class name s_attributeAssemblyQualifiedNameMap = new Dictionary<string, string>(); var allBuilders = new List<Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var builders = assembly.GetTypes() .Where(t => !t.IsInterface) .Where(t => typeof(IPrefabBuilder).IsAssignableFrom(t)); allBuilders.AddRange (builders); } foreach (var type in allBuilders) { // set attribute-name as key of dict if atribute is exist. CustomPrefabBuilder attr = type.GetCustomAttributes(typeof(CustomPrefabBuilder), true).FirstOrDefault() as CustomPrefabBuilder; var typename = type.AssemblyQualifiedName; if (attr != null) { if (!s_attributeAssemblyQualifiedNameMap.ContainsKey(attr.Name)) { s_attributeAssemblyQualifiedNameMap[attr.Name] = typename; } } else { s_attributeAssemblyQualifiedNameMap[typename] = typename; } } } return s_attributeAssemblyQualifiedNameMap; } public static string GetPrefabBuilderGUIName(IPrefabBuilder builder) { CustomPrefabBuilder attr = builder.GetType().GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder; return attr.Name; } public static bool HasValidCustomPrefabBuilderAttribute(Type t) { CustomPrefabBuilder attr = t.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder; return attr != null && !string.IsNullOrEmpty(attr.Name); } public static string GetPrefabBuilderGUIName(string className) { if(className != null) { var type = Type.GetType(className); if(type != null) { CustomPrefabBuilder attr = type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder; if(attr != null) { return attr.Name; } } } return string.Empty; } public static string GetPrefabBuilderVersion(string className) { var type = Type.GetType(className); if(type != null) { CustomPrefabBuilder attr = type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder; if(attr != null) { return attr.Version; } } return string.Empty; } public static int GetPrefabBuilderAssetThreshold(string className) { var type = Type.GetType(className); if(type != null) { CustomPrefabBuilder attr = type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder; if(attr != null) { return attr.AssetThreshold; } } return 0; } public static string GUINameToAssemblyQualifiedName(string guiName) { var map = GetAttributeAssemblyQualifiedNameMap(); if(map.ContainsKey(guiName)) { return map[guiName]; } return null; } public static IPrefabBuilder CreatePrefabBuilder(string guiName) { var className = GUINameToAssemblyQualifiedName(guiName); if(className != null) { var type = Type.GetType(className); if (type == null) { return null; } return (IPrefabBuilder) type.Assembly.CreateInstance(type.FullName); } return null; } public static IPrefabBuilder CreatePrefabBuilderByAssemblyQualifiedName(string assemblyQualifiedName) { if(assemblyQualifiedName == null) { return null; } Type t = Type.GetType(assemblyQualifiedName); if(t == null) { return null; } if(!HasValidCustomPrefabBuilderAttribute(t)) { return null; } return (IPrefabBuilder) t.Assembly.CreateInstance(t.FullName); } } }
using System; using System.Linq; using UIKit; using CoreGraphics; using CoreAnimation; namespace BLKFlexibleHeightBarDemo { public class BLKFlexibleHeightBar : UIView { protected nfloat _progress; protected nfloat _maximumBarHeight; protected nfloat _minimumBarHeight; protected BLKFlexibleHeightBarBehaviorDefiner _behaviorDefiner; public BLKFlexibleHeightBar () : base () { CommonInit (); } public BLKFlexibleHeightBar (CGRect frame) : base (frame) { CommonInit (); } public override void AwakeFromNib () { base.AwakeFromNib (); CommonInit (); _maximumBarHeight = Bounds.GetMaxY (); } void CommonInit () { _progress = 0.0f; _maximumBarHeight = 44.0f; _minimumBarHeight = 20.0f; } public nfloat Progress { get { return _progress; } set { SetProgress (value); } } public BLKFlexibleHeightBarBehaviorDefiner BehaviorDefiner { get { return _behaviorDefiner; } set { _behaviorDefiner = value; _behaviorDefiner.FlexibleHeightBar = this; } } public nfloat MaximumBarHeight { get { return _maximumBarHeight; } set { _maximumBarHeight = (nfloat)Math.Max (value, 0.0f); } } public nfloat MinimumBarHeight { get { return _minimumBarHeight; } set { _minimumBarHeight = (nfloat)Math.Max (value, 0.0f); ; } } public override void LayoutSubviews () { base.LayoutSubviews (); // Update height var barFrame = Frame; var newHeight = InterpolateFromValue (_maximumBarHeight, _minimumBarHeight, _progress); Frame = new CGRect (barFrame.X, barFrame.Y, barFrame.Width, newHeight); if (_behaviorDefiner != null && _behaviorDefiner.IsElasticMaximumHeightAtTop) { _progress = (nfloat)Math.Max (_progress, 0.0f); } // Update subviews using the appropriate layout attributes for the current progress foreach (var subview in Subviews.Cast<IBLKFlexibleHeightBarSubview> ()) { for (int i = 0; i < subview.NumberOfLayoutAttributes; i++) { var floorProgressPosition = subview.ProgressAtIndex (i); if (i + 1 < subview.NumberOfLayoutAttributes) { var ceilingProgressPosition = subview.ProgressAtIndex (i + 1); if (_progress >= floorProgressPosition && _progress < ceilingProgressPosition) { var floorLayoutAttributes = subview.LayoutAttributesAtIndex (i); var ceilingLayoutAttributes = subview.LayoutAttributesAtIndex (i + 1); ApplyAttributes (floorLayoutAttributes, ceilingLayoutAttributes, subview as UIView, floorProgressPosition, ceilingProgressPosition); } } else { if (_progress >= floorProgressPosition) { var floorLayoutAttributes = subview.LayoutAttributesAtIndex (i); ApplyAttributes (floorLayoutAttributes, floorLayoutAttributes, subview as UIView, floorProgressPosition, 1.0f); } } } } } void ApplyAttributes (BLKFlexibleHeightBarSubviewLayoutAttributes floorLayoutAttributes, BLKFlexibleHeightBarSubviewLayoutAttributes ceilingLayoutAttributes, UIView subview, nfloat floorProgress, nfloat ceilingProgress) { var numerator = _progress - floorProgress; nfloat denominator; if (ceilingProgress == floorProgress) { denominator = ceilingProgress; } else { denominator = ceilingProgress - floorProgress; } var relativeProgress = numerator / denominator; // Interpolate CA3DTransform CATransform3D transform3D; transform3D.m11 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m11, ceilingLayoutAttributes.Transform3D.m11, relativeProgress); transform3D.m12 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m12, ceilingLayoutAttributes.Transform3D.m12, relativeProgress); transform3D.m13 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m13, ceilingLayoutAttributes.Transform3D.m13, relativeProgress); transform3D.m14 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m14, ceilingLayoutAttributes.Transform3D.m14, relativeProgress); transform3D.m21 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m21, ceilingLayoutAttributes.Transform3D.m21, relativeProgress); transform3D.m22 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m22, ceilingLayoutAttributes.Transform3D.m22, relativeProgress); transform3D.m23 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m23, ceilingLayoutAttributes.Transform3D.m23, relativeProgress); transform3D.m24 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m24, ceilingLayoutAttributes.Transform3D.m24, relativeProgress); transform3D.m31 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m31, ceilingLayoutAttributes.Transform3D.m31, relativeProgress); transform3D.m32 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m32, ceilingLayoutAttributes.Transform3D.m32, relativeProgress); transform3D.m33 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m33, ceilingLayoutAttributes.Transform3D.m33, relativeProgress); transform3D.m34 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m34, ceilingLayoutAttributes.Transform3D.m34, relativeProgress); transform3D.m41 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m41, ceilingLayoutAttributes.Transform3D.m41, relativeProgress); transform3D.m42 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m42, ceilingLayoutAttributes.Transform3D.m42, relativeProgress); transform3D.m43 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m43, ceilingLayoutAttributes.Transform3D.m43, relativeProgress); transform3D.m44 = InterpolateFromValue (floorLayoutAttributes.Transform3D.m44, ceilingLayoutAttributes.Transform3D.m44, relativeProgress); // Interpolate frame CGRect frame; if (floorLayoutAttributes.Frame != (null) && ceilingLayoutAttributes.Frame == (null)) { frame = floorLayoutAttributes.Frame; } else if (floorLayoutAttributes.Frame == null && ceilingLayoutAttributes.Frame == null) { frame = subview.Frame; } else { var x = InterpolateFromValue (floorLayoutAttributes.Frame.GetMinX (), ceilingLayoutAttributes.Frame.GetMinX (), relativeProgress); var y = InterpolateFromValue (floorLayoutAttributes.Frame.GetMinY (), ceilingLayoutAttributes.Frame.GetMinY (), relativeProgress); var width = InterpolateFromValue (floorLayoutAttributes.Frame.Width, ceilingLayoutAttributes.Frame.Width, relativeProgress); var height = InterpolateFromValue (floorLayoutAttributes.Frame.Height, ceilingLayoutAttributes.Frame.Height, relativeProgress); frame = new CGRect (x, y, width, height); } // Interpolate center CGPoint center; { var x = InterpolateFromValue (floorLayoutAttributes.Center.X, ceilingLayoutAttributes.Center.X, relativeProgress); var y = InterpolateFromValue (floorLayoutAttributes.Center.Y, ceilingLayoutAttributes.Center.Y, relativeProgress); center = new CGPoint (x, y); } // Interpolate bounds CGRect bounds; { var x = InterpolateFromValue (floorLayoutAttributes.Bounds.GetMinX (), ceilingLayoutAttributes.Bounds.GetMinX (), relativeProgress); var y = InterpolateFromValue (floorLayoutAttributes.Bounds.GetMinY (), ceilingLayoutAttributes.Bounds.GetMinY (), relativeProgress); var width = InterpolateFromValue (floorLayoutAttributes.Bounds.Width, ceilingLayoutAttributes.Bounds.Width, relativeProgress); var height = InterpolateFromValue (floorLayoutAttributes.Bounds.Height, ceilingLayoutAttributes.Bounds.Height, relativeProgress); bounds = new CGRect (x, y, width, height); } // Interpolate alpha var alpha = InterpolateFromValue (floorLayoutAttributes.Alpha, ceilingLayoutAttributes.Alpha, relativeProgress); // Apply updated attributes subview.Layer.Transform = transform3D; if (transform3D.IsIdentity) { subview.Frame = frame; } subview.Center = center; subview.Bounds = bounds; subview.Alpha = alpha; subview.Layer.ZPosition = floorLayoutAttributes.ZIndex; subview.Hidden = floorLayoutAttributes.Hidden; } nfloat InterpolateFromValue (nfloat fromValue, nfloat toValue, nfloat progress) { return fromValue - ((fromValue - toValue) * progress); } void SetProgress (nfloat progress) { _progress = (nfloat)Math.Min (progress, 1.0f); if ((_behaviorDefiner != null && !_behaviorDefiner.IsElasticMaximumHeightAtTop) || _behaviorDefiner == null) { _progress = (nfloat)Math.Max (_progress, 0.0f); } } } }
using System; using System.IO; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using swf = System.Windows.Forms; using sd = System.Drawing; using sdi = System.Drawing.Imaging; using OpenTK; using OpenTK.Graphics.OpenGL; using BizHawk.Bizware.BizwareGL; //TODO - maybe a layer to cache Graphics parameters (notably, filtering) ? namespace BizHawk.Bizware.BizwareGL.Drivers.GdiPlus { public class IGL_GdiPlus : IGL { //rendering state RenderTarget _CurrRenderTarget; public IGL_GdiPlus() { MyBufferedGraphicsContext = new BufferedGraphicsContext(); } void IDisposable.Dispose() { } public void Clear(OpenTK.Graphics.OpenGL.ClearBufferMask mask) { var g = GetCurrentGraphics(); if((mask & ClearBufferMask.ColorBufferBit) != 0) { g.Clear(_currentClearColor); } } public string API { get { return "GDIPLUS"; } } public IBlendState CreateBlendState(BlendingFactorSrc colorSource, BlendEquationMode colorEquation, BlendingFactorDest colorDest, BlendingFactorSrc alphaSource, BlendEquationMode alphaEquation, BlendingFactorDest alphaDest) { return null; } private sd.Color _currentClearColor = Color.Transparent; public void SetClearColor(sd.Color color) { _currentClearColor = color; } public unsafe void BindArrayData(void* pData) { } public void FreeTexture(Texture2d tex) { var tw = tex.Opaque as TextureWrapper; tw.Dispose(); } public Shader CreateFragmentShader(bool cg, string source, string entry, bool required) { return null; } public Shader CreateVertexShader(bool cg, string source, string entry, bool required) { return null; } public void FreeShader(IntPtr shader) { } public void SetBlendState(IBlendState rsBlend) { //TODO for real } class MyBlendState : IBlendState { } static MyBlendState _rsBlendNoneVerbatim = new MyBlendState(), _rsBlendNoneOpaque = new MyBlendState(), _rsBlendNormal = new MyBlendState(); public IBlendState BlendNoneCopy { get { return _rsBlendNoneVerbatim; } } public IBlendState BlendNoneOpaque { get { return _rsBlendNoneOpaque; } } public IBlendState BlendNormal { get { return _rsBlendNormal; } } public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) { return null; } public void FreePipeline(Pipeline pipeline) {} public VertexLayout CreateVertexLayout() { return new VertexLayout(this, new IntPtr(0)); } public void SetTextureWrapMode(Texture2d tex, bool clamp) { } public void DrawArrays(PrimitiveType mode, int first, int count) { } public void BindPipeline(Pipeline pipeline) { } public void Internal_FreeShader(Shader shader) { } public void SetPipelineUniform(PipelineUniform uniform, bool value) { } public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4 mat, bool transpose) { } public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4 mat, bool transpose) { } public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) { } public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) { } public void SetPipelineUniform(PipelineUniform uniform, float value) { } public unsafe void SetPipelineUniform(PipelineUniform uniform, Vector4[] values) { } public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex) { } public void TexParameter2d(Texture2d tex, TextureParameterName pname, int param) { var tw = tex.Opaque as TextureWrapper; if (pname == TextureParameterName.TextureMinFilter) tw.MinFilter = (TextureMinFilter)param; if (pname == TextureParameterName.TextureMagFilter) tw.MagFilter = (TextureMagFilter)param; } public Texture2d LoadTexture(sd.Bitmap bitmap) { var sdbmp = (sd.Bitmap)bitmap.Clone(); TextureWrapper tw = new TextureWrapper(); tw.SDBitmap = sdbmp; return new Texture2d(this, tw, bitmap.Width, bitmap.Height); } public Texture2d LoadTexture(Stream stream) { using (var bmp = new BitmapBuffer(stream, new BitmapLoadOptions())) return (this as IGL).LoadTexture(bmp); } public Texture2d CreateTexture(int width, int height) { return null; } public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) { //TODO - need to rip the texturedata. we had code for that somewhere... return null; } public void LoadTextureData(Texture2d tex, BitmapBuffer bmp) { var tw = tex.Opaque as TextureWrapper; bmp.ToSysdrawingBitmap(tw.SDBitmap); } public Texture2d LoadTexture(BitmapBuffer bmp) { //definitely needed (by TextureFrugalizer at least) var sdbmp = bmp.ToSysdrawingBitmap(); var tw = new TextureWrapper(); tw.SDBitmap = sdbmp; return new Texture2d(this, tw, bmp.Width, bmp.Height); } public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex) { var tw = tex.Opaque as TextureWrapper; var blow = new BitmapLoadOptions() { AllowWrap = false //must be an independent resource }; var bb = new BitmapBuffer(tw.SDBitmap,blow); return bb; } public Texture2d LoadTexture(string path) { //todo //using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) // return (this as IGL).LoadTexture(fs); return null; } public Matrix4 CreateGuiProjectionMatrix(int w, int h) { return CreateGuiProjectionMatrix(new sd.Size(w, h)); } public Matrix4 CreateGuiViewMatrix(int w, int h, bool autoflip) { return CreateGuiViewMatrix(new sd.Size(w, h), autoflip); } public Matrix4 CreateGuiProjectionMatrix(sd.Size dims) { //see CreateGuiViewMatrix for more return Matrix4.Identity; } public Matrix4 CreateGuiViewMatrix(sd.Size dims, bool autoflip) { //on account of gdi+ working internally with a default view exactly like we want, we don't need to setup a new one here //furthermore, we _cant_, without inverting the GuiView and GuiProjection before drawing, to completely undo it //this might be feasible, but its kind of slow and annoying and worse, seemingly numerically unstable //if (autoflip && _CurrRenderTarget != null) //{ // Matrix4 ret = Matrix4.Identity; // ret.M22 = -1; // ret.M42 = dims.Height; // return ret; //} //else return Matrix4.Identity; } public void SetViewport(int x, int y, int width, int height) { } public void SetViewport(int width, int height) { } public void SetViewport(sd.Size size) { SetViewport(size.Width, size.Height); } public void SetViewport(swf.Control control) { } public void BeginControl(GLControlWrapper_GdiPlus control) { CurrentControl = control; } public void EndControl(GLControlWrapper_GdiPlus control) { CurrentControl = null; } public void SwapControl(GLControlWrapper_GdiPlus control) { } public class RenderTargetWrapper { public RenderTargetWrapper(IGL_GdiPlus gdi) { Gdi = gdi; } public void Dispose() { } IGL_GdiPlus Gdi; /// <summary> /// the control associated with this render target (if any) /// </summary> public GLControlWrapper_GdiPlus Control; /// <summary> /// the offscreen render target, if that's what this is representing /// </summary> public RenderTarget Target; public BufferedGraphics MyBufferedGraphics; public Graphics refGraphics; //?? hacky? public void CreateGraphics() { Rectangle r; if (Control != null) { r = Control.ClientRectangle; refGraphics = Control.CreateGraphics(); } else { var tw = Target.Texture2d.Opaque as TextureWrapper; r = Target.Texture2d.Rectangle; refGraphics = Graphics.FromImage(tw.SDBitmap); } if (MyBufferedGraphics != null) MyBufferedGraphics.Dispose(); MyBufferedGraphics = Gdi.MyBufferedGraphicsContext.Allocate(refGraphics, r); //MyBufferedGraphics.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed; ////not sure about this stuff... ////it will wreck alpha blending, for one thing //MyBufferedGraphics.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; //MyBufferedGraphics.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; } } public void BeginScene() { } public void EndScene() { //maybe an inconsistent semantic with other implementations.. //but accomplishes the needed goal of getting the current RT to render BindRenderTarget(null); } public IGraphicsControl Internal_CreateGraphicsControl() { var ret = new GLControlWrapper_GdiPlus(this); //create a render target for this control RenderTargetWrapper rtw = new RenderTargetWrapper(this); rtw.Control = ret; ret.RenderTargetWrapper = rtw; return ret; } public void FreeRenderTarget(RenderTarget rt) { var rtw = rt.Opaque as RenderTargetWrapper; rtw.Dispose(); } public unsafe RenderTarget CreateRenderTarget(int w, int h) { TextureWrapper tw = new TextureWrapper(); tw.SDBitmap = new Bitmap(w,h, sdi.PixelFormat.Format32bppArgb); var tex = new Texture2d(this, tw, w, h); RenderTargetWrapper rtw = new RenderTargetWrapper(this); var rt = new RenderTarget(this, rtw, tex); rtw.Target = rt; return rt; } public void BindRenderTarget(RenderTarget rt) { if (_CurrentOffscreenGraphics != null) { _CurrentOffscreenGraphics.Dispose(); _CurrentOffscreenGraphics = null; } _CurrRenderTarget = rt; if (CurrentRenderTargetWrapper != null) { if (CurrentRenderTargetWrapper == CurrentControl.RenderTargetWrapper) { //dont do anything til swapbuffers } else { //CurrentRenderTargetWrapper.MyBufferedGraphics.Render(); } } if (rt == null) { //null means to use the default RT for the current control CurrentRenderTargetWrapper = CurrentControl.RenderTargetWrapper; } else { var tw = rt.Texture2d.Opaque as TextureWrapper; CurrentRenderTargetWrapper = rt.Opaque as RenderTargetWrapper; _CurrentOffscreenGraphics = Graphics.FromImage(tw.SDBitmap); //if (CurrentRenderTargetWrapper.MyBufferedGraphics == null) // CurrentRenderTargetWrapper.CreateGraphics(); } } Graphics _CurrentOffscreenGraphics; public Graphics GetCurrentGraphics() { if (_CurrentOffscreenGraphics != null) return _CurrentOffscreenGraphics; var rtw = CurrentRenderTargetWrapper; return rtw.MyBufferedGraphics.Graphics; } public GLControlWrapper_GdiPlus CurrentControl; public RenderTargetWrapper CurrentRenderTargetWrapper; public BufferedGraphicsContext MyBufferedGraphicsContext; public class TextureWrapper : IDisposable { public sd.Bitmap SDBitmap; public TextureMinFilter MinFilter = TextureMinFilter.Nearest; public TextureMagFilter MagFilter = TextureMagFilter.Nearest; public void Dispose() { if (SDBitmap != null) { SDBitmap.Dispose(); SDBitmap = null; } } } } //class IGL_GdiPlus }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Help; using System.IO; using System.Globalization; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements the Update-Help cmdlet /// </summary> [Cmdlet(VerbsData.Update, "Help", DefaultParameterSetName = PathParameterSetName, SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210614")] public sealed class UpdateHelpCommand : UpdatableHelpCommandBase { #region Constructor /// <summary> /// Class constructor /// </summary> public UpdateHelpCommand() : base(UpdatableHelpCommandType.UpdateHelpCommand) { } #endregion private bool _alreadyCheckedOncePerDayPerModule = false; #region Parameters /// <summary> /// Specifies the modules to update /// </summary> [Parameter(Position = 0, ParameterSetName = PathParameterSetName, ValueFromPipelineByPropertyName = true)] [Parameter(Position = 0, ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [Alias("Name")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Module { get { return _module; } set { _module = value; } } private string[] _module; /// <summary> /// Specifies the Module Specifications to update /// </summary> [Parameter(ParameterSetName = PathParameterSetName, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public ModuleSpecification[] FullyQualifiedModule { get; set; } /// <summary> /// Specifies the paths to update from /// </summary> [Parameter(Position = 1, ParameterSetName = PathParameterSetName)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] SourcePath { get { return _path; } set { _path = value; } } private string[] _path; /// <summary> /// Specifies the literal path to save updates to /// </summary> [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Scans paths recursively /// </summary> [Parameter] public SwitchParameter Recurse { get { return _recurse; } set { _recurse = value; } } private bool _recurse; #endregion private bool _isInitialized = false; #region Implementation /// <summary> /// Begin processing /// </summary> protected override void BeginProcessing() { // Disable Get-Help prompt UpdatableHelpSystem.SetDisablePromptToUpdateHelp(); if (_path == null) { // Pull default source path from GP string defaultSourcePath = _helpSystem.GetDefaultSourcePath(); if (defaultSourcePath != null) { _path = new string[1] { defaultSourcePath }; } } } /// <summary> /// Main cmdlet logic /// </summary> protected override void ProcessRecord() { try { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. if (Module != null && FullyQualifiedModule != null) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } if (!_isInitialized) { if (_path == null && Recurse.IsPresent) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); } _isInitialized = true; } base.Process(_module, FullyQualifiedModule); // Reset the per-runspace help cache foreach (HelpProvider provider in Context.HelpSystem.HelpProviders) { if (_stopping) { break; } provider.Reset(); } } finally { ProgressRecord progress = new ProgressRecord(activityId, HelpDisplayStrings.UpdateProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling); progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } } /// <summary> /// Process a single module with a given culture /// </summary> /// <param name="module">module to process</param> /// <param name="culture">culture to use</param> /// <returns>true if the module has been processed, false if not</returns> internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture) { UpdatableHelpInfo currentHelpInfo = null; UpdatableHelpInfo newHelpInfo = null; string helpInfoUri = null; // reading the xml file even if force is specified // Reason: we need the current version for ShouldProcess string xml = UpdatableHelpSystem.LoadStringFromPath(this, SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()), null); if (xml != null) { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, currentCulture: null, pathOverride: null, verbose: false, shouldResolveUri: false, // ignore validation exception if _force is true ignoreValidationException: _force); } // Don't update too frequently if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force)) { return true; } _alreadyCheckedOncePerDayPerModule = true; if (_path != null) { UpdatableHelpSystemDrive helpInfoDrive = null; try { Collection<string> resolvedPaths = new Collection<string>(); // Search for the HelpInfo XML foreach (string path in _path) { if (String.IsNullOrEmpty(path)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty)); WriteError(e.ErrorRecord); return false; } try { string sourcePath = path; if (_credential != null) { UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, path, _credential); sourcePath = drive.DriveName; } // Expand wildcard characters foreach (string tempPath in ResolvePath(sourcePath, _recurse, _isLiteralPath)) { resolvedPaths.Add(tempPath); } } catch (System.Management.Automation.DriveNotFoundException e) { ThrowPathMustBeValidContainersException(path, e); } catch (ItemNotFoundException e) { ThrowPathMustBeValidContainersException(path, e); } } if (resolvedPaths.Count == 0) { return true; } // Everything in resolvedPaths is a container foreach (string resolvedPath in resolvedPaths) { string literalPath = SessionState.Path.Combine(resolvedPath, module.GetHelpInfoName()); xml = UpdatableHelpSystem.LoadStringFromPath(this, literalPath, _credential); if (xml != null) { newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath, verbose: false, shouldResolveUri: true, ignoreValidationException: false); helpInfoUri = resolvedPath; break; } } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, e); } finally { if (helpInfoDrive != null) { helpInfoDrive.Dispose(); } } } else { // Form the actual HelpInfo.xml uri helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri; string uri = helpInfoUri + module.GetHelpInfoName(); newHelpInfo = _helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, uri, module.ModuleName, module.ModuleGuid, culture); } if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, null); } bool installed = false; foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) { Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0", newHelpInfo.GetCultureVersion(contentUri.Culture), contentUri.Culture); if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help")) { continue; } if (Utils.IsUnderProductFolder(module.ModuleBase) && (!Utils.IsAdministrator())) { string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation); ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation", message, ErrorCategory.InvalidOperation, null, null)); return false; } if (!IsUpdateNecessary(module, _force ? null : currentHelpInfo, newHelpInfo, contentUri.Culture, _force)) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture))); installed = true; continue; } else { try { Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null"); string helpContentUri = contentUri.ResolvedUri; string xsdPath = SessionState.Path.Combine(Utils.GetApplicationBase(Context.ShellID), "Schemas\\PSMaml\\maml.xsd"); // TODO: Edit the maml XSDs and change this // Gather destination paths Collection<string> destPaths = new Collection<string>(); destPaths.Add(module.ModuleBase); #if !CORECLR // Side-By-Side directories are not present in OneCore environments. if (IsSystemModule(module.ModuleName) && ClrFacade.Is64BitOperatingSystem()) { string path = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64"); destPaths.Add(path); } #endif Collection<string> filesInstalled; if (Directory.Exists(helpContentUri)) { if (_credential != null) { string helpContentName = module.GetHelpContentName(contentUri.Culture); string tempContentPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); try { using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, helpContentUri, _credential)) { if (!Directory.Exists(tempContentPath)) { Directory.CreateDirectory(tempContentPath); } InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, helpContentName) }, Path.Combine(tempContentPath, helpContentName), false, CopyContainers.CopyTargetContainer, true, true); // Local _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, tempContentPath, destPaths, module.GetHelpContentName(contentUri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), contentUri.Culture, xsdPath, out filesInstalled); } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound), ErrorCategory.ResourceUnavailable, null, e); } } else { _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, helpContentUri, destPaths, module.GetHelpContentName(contentUri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), contentUri.Culture, xsdPath, out filesInstalled); } } else { // Remote // Download and install help content if (!_helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, destPaths, module.GetHelpContentName(contentUri.Culture), contentUri.Culture, helpContentUri, xsdPath, out filesInstalled)) { installed = false; continue; } } _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture), module.ModuleBase, module.GetHelpInfoName(), _force); foreach (string fileInstalled in filesInstalled) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, fileInstalled), contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture))); } LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted)); installed = true; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); ProcessException(module.ModuleName, contentUri.Culture.Name, e); } } } return installed; } /// <summary> /// Throws PathMustBeValidContainers exception /// </summary> /// <param name="path"></param> /// <param name="e"></param> private void ThrowPathMustBeValidContainersException(string path, Exception e) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, null, e); } #endregion } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. namespace Mosa.FileSystem.VFS { /// <summary> /// Implements path resolution functionality for the Mosa.VFS.VirtualFileSystem. /// </summary> internal class PathResolver { #region Constants // FIXME: Make this configurable - do we have some sort of configuration provider? /// <summary> /// Controls the maximum number of symbolic links to follow while resolving a directory path. /// </summary> private static readonly int MAX_SYMLINKS_TO_FOLLOW = 8; // <summary> // Array to split paths properly for the local system. // </summary> //private static readonly char[] splitChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; #endregion Constants #region Data members /// <summary> /// Reference to the root directory of the system. /// </summary> private DirectoryEntry rootDirectory; /// <summary> /// Reference to the current directory of the system. /// </summary> private DirectoryEntry currentDirectory; /// <summary> /// Remaining lookup depth for symbolic links. /// </summary> private int depth; #endregion Data members #region Construction private PathResolver(DirectoryEntry rootDirectory, DirectoryEntry currentDirectory) { this.rootDirectory = rootDirectory; this.currentDirectory = currentDirectory; depth = PathResolver.MAX_SYMLINKS_TO_FOLLOW; } #endregion Construction #region Static methods /// <summary> /// Performs a standard path lookup. /// </summary> /// <param name="rootDirectory">The root directory.</param> /// <param name="path">The path to resolve.</param> /// <returns> /// The directory entry of the resolved path. /// </returns> /// <remarks> /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal /// process. For example a network file system node may throw an exception, if the server is unreachable. /// </remarks> public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path) { // FIXME: Remove the root argument. The file system root should be unique for a process as part of a security model similar to jails, e.g. give apps from // untrusted sources their private file system regions. // FIXME: Get the root from the thread execution block DirectoryEntry current = rootDirectory; PathResolver resolver = new PathResolver(rootDirectory, current); return resolver.Resolve(ref path, PathResolutionFlags.None); } /// <summary> /// Performs a path lookup obeying to the passed flags. /// </summary> /// <param name="rootDirectory">The root directory.</param> /// <param name="path">The path to resolve.</param> /// <param name="flags">Controls aspects of the path lookup process.</param> /// <returns> /// The directory entry of the resolved path. /// </returns> /// <remarks> /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal /// process. For example a network file system node may throw an exception, if the server is unreachable. /// </remarks> public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path, PathResolutionFlags flags) { // FIXME: Get the root from the thread execution block DirectoryEntry current = rootDirectory; PathResolver resolver = new PathResolver(rootDirectory, current); return resolver.Resolve(ref path, flags); } #endregion Static methods #region Methods /// <summary> /// Performs an iterative lookup of the given path starting from the root and obeying to the specified flags. /// </summary> /// <param name="path">The path to lookup. This can be a relative or absolute path. Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar are valid delimiters.</param> /// <param name="flags">The lookup flags, which control the lookup process.</param> /// <returns> /// The directory entry of the resolved path. /// </returns> /// <remarks> /// This call may result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal /// process. For example a network file system node may throw an exception, if the server is unreachable. /// </remarks> private DirectoryEntry Resolve(ref string path, PathResolutionFlags flags) { // DirectoryNode entry found by stepping through the path DirectoryEntry entry = null; // Split the given path to its components PathSplitter dirs = new PathSplitter(path); // Determine the number of path components int max = dirs.Length; // Current path component string item; // Loop index int index = 0; // Perform an access check on the root directory AccessCheck.Perform(currentDirectory, AccessMode.Traverse, AccessCheckFlags.None); // Do not resolve the last name, if we want the parent directory. if (PathResolutionFlags.RetrieveParent == (flags & PathResolutionFlags.RetrieveParent)) { path = dirs[dirs.Length - 1]; max--; } // Check if this is an absolute path? if (dirs[0].Length == 0) { // Yes, replace the current directory currentDirectory = rootDirectory; index++; } // Iterate over the remaining path components while ((currentDirectory != null) && (index < max)) { item = dirs[index]; entry = null; if (currentDirectory.Node.NodeType == VfsNodeType.SymbolicLink) { SymbolicLinkNode link = (SymbolicLinkNode)currentDirectory.Node; if (0 != depth--) { // The symlink stores a relative path, use it for a current relative lookup. string target = link.Target; // Build a new flags set for symlink lookups, as we do not want all of them. PathResolutionFlags symflags = (flags & PathResolutionFlags.SymLinkLookupSafe); entry = Resolve(ref target, symflags); } else { if (PathResolutionFlags.DoNotThrowNotFoundException != (PathResolutionFlags.DoNotThrowNotFoundException & flags)) { // FIXME: Provide a MUI resource string for the exception #if VFS_EXCEPTIONS throw new PathTooLongException(); #endif // #if !VFS_EXCEPTIONS } } } else { // Pass the lookup to the DirectoryEntry (and ultimately to the inode itself.) entry = currentDirectory.Lookup(item); // If lookup in the directory entry failed, ask the real INode to perform the lookup. if (entry == null) { IVfsNode node = currentDirectory.Node.Lookup(item); if (node != null) { entry = DirectoryEntry.Allocate(currentDirectory, item, node); } } } // Increment the path component index index++; // Check if we have a new path component? if ((entry == null) && (PathResolutionFlags.DoNotThrowNotFoundException != (PathResolutionFlags.DoNotThrowNotFoundException & flags))) { // FIXME: Move exception messages to MUI resources #if VFS_EXCEPTIONS if (index == max) throw new FileNotFoundException(@"Failed to resolve the path.", path); else throw new DirectoryNotFoundException(@"Failed to resolve the path."); #endif // #if VFS_EXCEPTIONS } // Set the current resolution directory currentDirectory = entry; // Check if the caller has traverse access to the directory AccessCheck.Perform(currentDirectory, AccessMode.Traverse, AccessCheckFlags.None); } return currentDirectory; } #endregion Methods } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using System.Configuration; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using Sip.Server; using Sip.Server.Configuration; using Sip.Server.Users; using Sip.Server.Accounts; using Sip.Server.WcfService; using Sip.Message; using Http.Message; using SocketServers; using Server.Http; using Server.Restapi; using Server.Authorization.Sip; using Server.Xcap; using Server.Configuration; namespace Sip.Server { class Server : IDisposable { #if !DEBUG private readonly CrashHandler crashHandler; #endif private readonly TransportLayer transportLayer; private readonly TransactionLayer transactionLayer; private readonly LocationService locationService; private readonly WCFService wcfService; private readonly ConfigurationMonitor configurationMonitor; private readonly TrunkManager trunkManager; private readonly SipAuthorizationManager authorization; private readonly Userz userz; private readonly AdUsers adUsers; private readonly Mras.Mras1 mras; private readonly HttpFileServer httpServer; private readonly Accountx accounts; private readonly RestapiService restapi; private readonly ProxyServerTU proxyServerTU; public Server() { #if !DEBUG crashHandler = new CrashHandler(); #endif HttpMessage.BufferManager = SipMessage.BufferManager = new BufferManagerProxy(); LoadConfiguration(); var configuration = SipServerConfigurationSection.GetSection(); if (configuration.AddToWindowsFirewall) AddFirewallException(); if (BufferManager.IsInitialized() == false) BufferManager.Initialize(Math.Min((int)(GetTotalMemoryInBytes() / (1024 * 1024) / 2), 2048)); if (Directory.Exists(configuration.AccountsPath) == false) Directory.CreateDirectory(configuration.AccountsPath); var initializer = new Initializer(ConfigurationMonitor_Changed); initializer.GetResults( out transportLayer, out transactionLayer, out locationService, out wcfService, out configurationMonitor, out trunkManager, out authorization, out userz, out adUsers, out mras, out httpServer, out accounts, out restapi, out proxyServerTU); if (configuration.IsActiveDirectoryEnabled) { accounts.ForEach((account) => { SetSpn(@"sip/" + account.DomainName); }); } RestapiUriParser.LoadTables(configuration.ExePath); XcapUriParser.LoadTables(configuration.ExePath); Http.Message.HttpMessageReader.InitializeAsync( (ms1) => { Sip.Message.SipMessageReader.InitializeAsync( (ms2) => { Tracer.WriteImportant(@"JIT-compilation Http.Message.dll " + (ms1 / 1000).ToString() + ", Sip.Message.dll: " + (ms2 / 1000).ToString() + " seconds."); try { transportLayer.Start(); Tracer.WriteImportant(@"Server started."); } catch (Exception ex) { Tracer.WriteException(@"Failed to start Servers Manager.", ex); } Initializer.ConfigureVoipProviders(trunkManager, configuration); }); }); } public void Dispose() { Dispose( configurationMonitor, accounts, userz, wcfService, locationService, transportLayer, httpServer); } public void Dispose(params IDisposable[] disposables) { foreach (var obj in disposables) try { obj.Dispose(); } catch { } } #region LoadConfiguration, ConfigurationMonitor_Changed private void LoadConfiguration() { var errors = SipServerConfigurationSection.LoadSection(); if (errors.Count > 0) { // log errors! try { var name = SipServerConfigurationSection.GetSection().FilePath; var oldName = name + ".old"; File.Delete(oldName); File.Move(name, oldName); File.Delete(name); var errors2 = SipServerConfigurationSection.LoadSection(); if (errors2.Count > 0) throw errors2[0]; } catch (Exception ex) { throw new InvalidProgramException(@"Can not restore .config file", ex); } } } private void ConfigurationMonitor_Changed(object sender, EventArgs e) { var errors = SipServerConfigurationSection.LoadSection(); if (errors.Count > 0) { // log errors! } else { var configuration = SipServerConfigurationSection.GetSection(); Tracer.Configure(configuration.TracingPath, configuration.IsTracingEnabled); wcfService.AdministratorPassword = configuration.AdministratorPassword; restapi.AdministratorPassword = configuration.AdministratorPassword; if (adUsers != null) adUsers.Group = configuration.ActiveDirectoryGroup; authorization.IsEnabled = configuration.IsAuthorizationEnabled; trunkManager.Clear(); Initializer.ConfigureVoipProviders(trunkManager, configuration); Initializer.ConfigureMras(mras, configuration); httpServer.WwwPath = configuration.WwwPath; transportLayer.ChangeSettings(configuration.WebSocketResponseFrame); proxyServerTU.IsOfficeSIPFiletransferEnabled = configuration.IsOfficeSIPFiletransferEnabled; } } #endregion #region SetSpn private void SetSpn(string spn) { try { using (var entry = UserPrincipal.Current.GetUnderlyingObject() as DirectoryEntry) { var servicePrincipalNames = entry.Properties["servicePrincipalName"]; if (servicePrincipalNames.IndexOf(spn) < 0) { servicePrincipalNames.Add(spn); entry.CommitChanges(); } } } catch { } } #endregion #region AddFirewallException, GetAssemblyTitle private static void AddFirewallException() { try { using (var p = new Process()) { p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = "netsh"; var assembly = System.Reflection.Assembly.GetExecutingAssembly(); p.StartInfo.Arguments = string.Format("firewall add allowedprogram \"{0}\" \"{1}\" ENABLE", assembly.Location, GetAssemblyTitle(assembly)); p.Start(); p.WaitForExit(5000); } } catch { } } private static string GetAssemblyTitle(System.Reflection.Assembly assembly) { var attributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), false); if (attributes != null && attributes.Length > 0) { var attribute = attributes[0] as System.Reflection.AssemblyTitleAttribute; if (attribute != null) return attribute.Title; } throw new InvalidProgramException(@"Can not retrive Title, assembly attribute"); } #endregion #region GetTotalMemoryInBytes private static ulong GetTotalMemoryInBytes() { try { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; } catch { return 1024 * 1024 * 1024; } } #endregion } }
// <copyright file="IFFChunk.cs" company=""> // TODO: Update copyright text. // </copyright> using System; using System.Collections.Generic; using System.IO; using System.Linq; using DjvuNet.DataChunks.Directory; using DjvuNet.DataChunks.Enums; namespace DjvuNet.DataChunks { /// <summary> /// TODO: Update summary. /// </summary> public abstract class IFFChunk { #region Protected Properties #region Reader private DjvuReader _reader; /// <summary> /// Gets the reader for the chunk data /// </summary> //[DataMember] protected DjvuReader Reader { get { return _reader; } private set { //if (ValidateReader(value) == false) return; if (Reader != value) { _reader = value; } } } #endregion Reader #endregion Protected Properties #region Public Properties #region ChunkType /// <summary> /// Gets the chunk type /// </summary> public abstract ChunkTypes ChunkType { get; } #endregion ChunkType #region Parent private IFFChunk _parent; /// <summary> /// Gets the parent for the IFF chunk /// </summary> public IFFChunk Parent { get { return _parent; } private set { if (Parent != value) { _parent = value; } } } #endregion Parent #region Length private int _length; /// <summary> /// Gets the length of the chunk data /// </summary> public int Length { get { return _length; } protected set { if (Length != value) { _length = value; } } } #endregion Length #region ChunkID private string _chunkID; /// <summary> /// Gets the chunk identifier /// </summary> public string ChunkID { get { return _chunkID; } private set { if (ChunkID != value) { _chunkID = value; } } } #endregion ChunkID #region Offset private long _offset; /// <summary> /// Gets the offset to the start of the chunk data /// </summary> public long Offset { get { return _offset; } protected set { if (Offset != value) { _offset = value; } } } #endregion Offset #region Name /// <summary> /// Gets the name of the chunk /// </summary> //[DataMember] public string Name { get { return ChunkType.ToString().ToUpper().Replace("_", ":"); } } #endregion Name #region IsSubFormChunk /// <summary> /// True if the chunk is a sub form chunk, false otherwise /// </summary> public bool IsSubFormChunk { get { return ChunkType == ChunkTypes.Form_Djvu || ChunkType == ChunkTypes.Form_Djvi || ChunkType == ChunkTypes.Form_Thum || ChunkType == ChunkTypes.Form_Djvm; } } #endregion IsSubFormChunk #region Document private DjvuDocument _document; /// <summary> /// Gets the root Djvu document for the form /// </summary> public DjvuDocument Document { get { return _document; } private set { if (Document != value) { _document = value; } } } #endregion Document #endregion Public Properties #region Constructors /// <summary> /// Initializes the IFFChunk /// </summary> /// <param name="reader"></param> /// <param name="parent"></param> public IFFChunk(DjvuReader reader, IFFChunk parent, DjvuDocument document) { _reader = reader; _parent = parent; _document = document; // Move back 4 to compensate for the chunk type already read _offset = reader.Position - 4; ReadChunkHeader(reader); ReadChunkData(reader); } #endregion Constructors #region Public Methods public DjvuReader GetReader() { return Reader; } /// <summary> /// Builds the appropriate chunk for the ID /// </summary> /// <returns></returns> public static IFFChunk BuildIFFChunk(DjvuReader reader, DjvuDocument rootDocument, IFFChunk parent, ChunkTypes chunkType) { IFFChunk result = null; if (chunkType == ChunkTypes.Form) result = new FormChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Form_Djvm) result = new DjvmChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Form_Djvu) result = new DjvuChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Form_Djvi) result = new DjviChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Form_Thum) result = new ThumChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Dirm) result = new DirmChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Navm) result = new NavmChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Anta) result = new AntaChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Antz) result = new AntzChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Txta) result = new TxtaChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Txtz) result = new TxtzChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Djbz) result = new DjbzChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Sjbz) result = new SjbzChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.FG44) result = new FG44Chunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.BG44) result = new BG44Chunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.TH44) result = new TH44Chunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.WMRM) result = new WmrmChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.FGbz) result = new FGbzChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Info) result = new InfoChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Incl) result = new InclChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.BGjp) result = new BGjpChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.FGjp) result = new FGjpChunk(reader, parent, rootDocument); else if (chunkType == ChunkTypes.Smmr) result = new SmmrChunk(reader, parent, rootDocument); else result = new UnknownChunk(reader, parent, rootDocument); //Console.WriteLine(result); return result; } /// <summary> /// Gets the chunk type based on the ID /// </summary> /// <param name="ID"></param> /// <returns></returns> public static ChunkTypes GetChunkType(string ID) { string lowerID = ID.ToLower(); var values = Enum.GetValues(typeof(ChunkTypes)).Cast<ChunkTypes>(); foreach (ChunkTypes value in values) { if (value.ToString().ToLower().Replace("form_", "") == lowerID) { return value; } } return ChunkTypes.Unknown; //throw new Exception("Unknown chunk type: " + ID); } /// <summary> /// Gets all the children items of the given type /// </summary> /// <typeparam name="TItem"></typeparam> /// <returns></returns> public TItem[] GetChildrenItems<TItem>() where TItem : IFFChunk { return GetChildrenItems<TItem>(this); } /// <summary> /// Gets the string representation of the item /// </summary> /// <returns></returns> public override string ToString() { return string.Format("N:{0}; O:{1};", Name, Offset); } #endregion Public Methods #region Protected Methods /// <summary> /// Reads the data for the chunk /// </summary> /// <param name="reader"></param> protected abstract void ReadChunkData(DjvuReader reader); #endregion Protected Methods #region Private Methods /// <summary> /// Gets all the children items of the given type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="page"></param> /// <returns></returns> private T[] GetChildrenItems<T>(IFFChunk page) where T : IFFChunk { // Check if this is a thumbnail if (page is T) { return new T[] { (T)page }; } // No items if not form if (page is FormChunk == false) { return new T[0]; } List<T> results = new List<T>(); FormChunk form = (FormChunk)page; foreach (IFFChunk chunk in form.Children) { results.AddRange(GetChildrenItems<T>(chunk)); } return results.ToArray(); } /// <summary> /// Reads in the chunk data /// </summary> /// <param name="reader"></param> private void ReadChunkHeader(DjvuReader reader) { ChunkID = reader.ReadUTF8String(4); if (IsSubFormChunk == false) { Length = reader.ReadInt32MSB(); } } #endregion Private Methods } }