context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.Modules;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.TypeParsing;
using System.Reflection.Runtime.CustomAttributes;
using System.Collections.Generic;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
using System.Security;
namespace System.Reflection.Runtime.Assemblies
{
//
// The runtime's implementation of an Assembly.
//
internal abstract partial class RuntimeAssembly : Assembly, IEquatable<RuntimeAssembly>
{
public bool Equals(RuntimeAssembly other)
{
if (other == null)
return false;
return this.Equals((object)other);
}
public sealed override String FullName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Assembly_FullName(this);
#endif
return GetName().FullName;
}
}
public sealed override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public abstract override Module ManifestModule { get; }
public sealed override IEnumerable<Module> Modules
{
get
{
yield return ManifestModule;
}
}
public sealed override Type GetType(String name, bool throwOnError, bool ignoreCase)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Assembly_GetType(this, name);
#endif
if (name == null)
throw new ArgumentNullException();
if (name.Length == 0)
throw new ArgumentException();
TypeName typeName = TypeParser.ParseAssemblyQualifiedTypeName(name, throwOnError: throwOnError);
if (typeName == null)
return null;
if (typeName is AssemblyQualifiedTypeName)
{
if (throwOnError)
throw new ArgumentException(SR.Argument_AssemblyGetTypeCannotSpecifyAssembly); // Cannot specify an assembly qualifier in a typename passed to Assembly.GetType()
else
return null;
}
CoreAssemblyResolver coreAssemblyResolver = RuntimeAssembly.GetRuntimeAssemblyIfExists;
CoreTypeResolver coreTypeResolver =
delegate (Assembly containingAssemblyIfAny, string coreTypeName)
{
if (containingAssemblyIfAny == null)
return GetTypeCore(coreTypeName, ignoreCase: ignoreCase);
else
return containingAssemblyIfAny.GetTypeCore(coreTypeName, ignoreCase: ignoreCase);
};
GetTypeOptions getTypeOptions = new GetTypeOptions(coreAssemblyResolver, coreTypeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase);
return typeName.ResolveType(this, getTypeOptions);
}
#pragma warning disable 0067 // Silence warning about ModuleResolve not being used.
public sealed override event ModuleResolveEventHandler ModuleResolve;
#pragma warning restore 0067
public sealed override bool ReflectionOnly
{
get
{
return false; // ReflectionOnly loading not supported.
}
}
internal abstract RuntimeAssemblyName RuntimeAssemblyName { get; }
public sealed override AssemblyName GetName()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Assembly_GetName(this);
#endif
return RuntimeAssemblyName.ToAssemblyName();
}
public sealed override Type[] GetForwardedTypes()
{
List<Type> types = new List<Type>();
List<Exception> exceptions = null;
foreach (TypeForwardInfo typeForwardInfo in TypeForwardInfos)
{
string fullTypeName = typeForwardInfo.NamespaceName.Length == 0 ? typeForwardInfo.TypeName : typeForwardInfo.NamespaceName + "." + typeForwardInfo.TypeName;
RuntimeAssemblyName redirectedAssemblyName = typeForwardInfo.RedirectedAssemblyName;
Type type = null;
RuntimeAssembly redirectedAssembly;
Exception exception = RuntimeAssembly.TryGetRuntimeAssembly(redirectedAssemblyName, out redirectedAssembly);
if (exception == null)
{
type = redirectedAssembly.GetTypeCore(fullTypeName, ignoreCase: false); // GetTypeCore() will follow any further type-forwards if needed.
if (type == null)
exception = Helpers.CreateTypeLoadException(fullTypeName.EscapeTypeNameIdentifier(), redirectedAssembly);
}
Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null.
if (type != null)
{
types.Add(type);
AddPublicNestedTypes(type, types);
}
else
{
if (exceptions == null)
{
exceptions = new List<Exception>();
}
exceptions.Add(exception);
}
}
if (exceptions != null)
{
int numTypes = types.Count;
int numExceptions = exceptions.Count;
types.AddRange(new Type[numExceptions]); // add one null Type for each exception.
exceptions.InsertRange(0, new Exception[numTypes]); // align the Exceptions with the null Types.
throw new ReflectionTypeLoadException(types.ToArray(), exceptions.ToArray());
}
return types.ToArray();
}
/// <summary>
/// Intentionally excludes forwards to nested types.
/// </summary>
protected abstract IEnumerable<TypeForwardInfo> TypeForwardInfos { get; }
private static void AddPublicNestedTypes(Type type, List<Type> types)
{
foreach (Type nestedType in type.GetNestedTypes(BindingFlags.Public))
{
types.Add(nestedType);
AddPublicNestedTypes(nestedType, types);
}
}
/// <summary>
/// Helper routine for the more general Type.GetType() family of apis.
///
/// Resolves top-level named types only. No nested types. No constructed types.
///
/// Returns null if the type does not exist. Throws for all other error cases.
/// </summary>
internal RuntimeTypeInfo GetTypeCore(string fullName, bool ignoreCase)
{
if (ignoreCase)
return GetTypeCoreCaseInsensitive(fullName);
else
return GetTypeCoreCaseSensitive(fullName);
}
// Types that derive from RuntimeAssembly must implement the following public surface area members
public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; }
public abstract override IEnumerable<TypeInfo> DefinedTypes { get; }
public abstract override MethodInfo EntryPoint { get; }
public abstract override IEnumerable<Type> ExportedTypes { get; }
public abstract override ManifestResourceInfo GetManifestResourceInfo(String resourceName);
public abstract override String[] GetManifestResourceNames();
public abstract override Stream GetManifestResourceStream(String name);
public abstract override string ImageRuntimeVersion { get; }
public abstract override bool Equals(Object obj);
public abstract override int GetHashCode();
/// <summary>
/// Ensures a module is loaded and that its module constructor is executed. If the module is fully
/// loaded and its constructor already ran, we do not run it again.
/// </summary>
internal abstract void RunModuleConstructor();
/// <summary>
/// Perform a lookup for a type based on a name. Overriders are expected to
/// have a non-cached implementation, as the result is expected to be cached by
/// callers of this method. Should be implemented by every format specific
/// RuntimeAssembly implementor
/// </summary>
internal abstract RuntimeTypeInfo UncachedGetTypeCoreCaseSensitive(string fullName);
/// <summary>
/// Perform a lookup for a type based on a name. Overriders may or may not
/// have a cached implementation, as the result is not expected to be cached by
/// callers of this method, but it is also a rarely used api. Should be
/// implemented by every format specific RuntimeAssembly implementor
/// </summary>
internal abstract RuntimeTypeInfo GetTypeCoreCaseInsensitive(string fullName);
internal RuntimeTypeInfo GetTypeCoreCaseSensitive(string fullName)
{
return this.CaseSensitiveTypeTable.GetOrAdd(fullName);
}
private CaseSensitiveTypeCache CaseSensitiveTypeTable
{
get
{
return _lazyCaseSensitiveTypeTable ?? (_lazyCaseSensitiveTypeTable = new CaseSensitiveTypeCache(this));
}
}
public sealed override bool GlobalAssemblyCache
{
get
{
return false;
}
}
public sealed override long HostContext
{
get
{
return 0;
}
}
public sealed override Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore)
{
throw new PlatformNotSupportedException();
}
public sealed override FileStream GetFile(string name)
{
throw new PlatformNotSupportedException();
}
public sealed override FileStream[] GetFiles(bool getResourceModules)
{
throw new PlatformNotSupportedException();
}
public sealed override SecurityRuleSet SecurityRuleSet
{
get
{
return SecurityRuleSet.None;
}
}
/// <summary>
/// Returns a *freshly allocated* array of loaded Assemblies.
/// </summary>
internal static Assembly[] GetLoadedAssemblies()
{
// Important: The result of this method is the return value of the AppDomain.GetAssemblies() api so
// so it must return a freshly allocated array on each call.
AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder;
IList<AssemblyBindResult> bindResults = binder.GetLoadedAssemblies();
Assembly[] results = new Assembly[bindResults.Count];
for (int i = 0; i < bindResults.Count; i++)
{
Assembly assembly = GetRuntimeAssembly(bindResults[i]);
results[i] = assembly;
}
return results;
}
private volatile CaseSensitiveTypeCache _lazyCaseSensitiveTypeTable;
private sealed class CaseSensitiveTypeCache : ConcurrentUnifier<string, RuntimeTypeInfo>
{
public CaseSensitiveTypeCache(RuntimeAssembly runtimeAssembly)
{
_runtimeAssembly = runtimeAssembly;
}
protected sealed override RuntimeTypeInfo Factory(string key)
{
return _runtimeAssembly.UncachedGetTypeCoreCaseSensitive(key);
}
private readonly RuntimeAssembly _runtimeAssembly;
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
namespace CodeCave.NetworkAgilityPack.Socks
{
/// <summary>
/// Implements a specific version of the SOCKS protocol. This is an abstract class; it must be inherited.
/// </summary>
internal abstract class SocksProtocol : IDisposable
{
#region Variables
/// <summary>Holds the value of the Server property.</summary>
protected Socket server;
/// <summary>Holds the address of the method to call when the SOCKS protocol has been completed.</summary>
protected HandShakeComplete handShakeComplete;
#endregion Variables
#region Constructors
/// <summary>
/// Initializes a new instance of the SocksHandler class.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use when authenticating with the server.</param>
/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
protected SocksProtocol(Socket server, string user)
{
Server = server;
Username = user;
}
/// <summary>
/// Finalizes an instance of the <see cref="SocksProtocol"/> class.
/// </summary>
~SocksProtocol()
{
Dispose(false);
}
#endregion Constructors
#region Abstract members
/// <summary>
/// Starts negotiating with a SOCKS proxy server.
/// </summary>
/// <param name="host">The remote server to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
public abstract void Negotiate(string host, int port);
/// <summary>
/// Starts negotiating with a SOCKS proxy server.
/// </summary>
/// <param name="remoteEndPoint">The remote endpoint to connect to.</param>
public abstract void Negotiate(IPEndPoint remoteEndPoint);
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="remoteEndPoint">An IPEndPoint that represents the remote device. </param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public abstract AsyncSocksResult BeginNegotiate(IPEndPoint remoteEndPoint, HandShakeComplete callback, IPEndPoint proxyEndPoint);
/// <summary>
/// Starts negotiating asynchronously with a SOCKS proxy server.
/// </summary>
/// <param name="host">The remote server to connect to.</param>
/// <param name="port">The remote port to connect to.</param>
/// <param name="callback">The method to call when the connection has been established.</param>
/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
public abstract AsyncSocksResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint);
#endregion Abstract members
#region Methods
/// <summary>
/// Converts a port number to an array of bytes.
/// </summary>
/// <param name="port">The port to convert.</param>
/// <returns>An array of two bytes that represents the specified port.</returns>
protected byte[] PortToBytes(int port)
{
byte [] ret = new byte[2];
ret[0] = (byte)(port / 256);
ret[1] = (byte)(port % 256);
return ret;
}
/// <summary>
/// Converts an IP address to an array of bytes.
/// </summary>
/// <param name="address">The IP address to convert.</param>
/// <returns>An array of four bytes that represents the specified IP address.</returns>
protected byte[] AddressToBytes(long address)
{
byte [] ret = new byte[4];
ret[0] = (byte)(address % 256);
ret[1] = (byte)((address / 256) % 256);
ret[2] = (byte)((address / 65536) % 256);
ret[3] = (byte)(address / 16777216);
return ret;
}
/// <summary>
/// Reads a specified number of bytes from the Server socket.
/// </summary>
/// <param name="count">The number of bytes to return.</param>
/// <returns>An array of bytes.</returns>
/// <exception cref="ArgumentException">The number of bytes to read is invalid.</exception>
/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
protected byte[] ReadBytes(int count)
{
if (count <= 0) throw new ArgumentException();
const int MAX_TIMES_0_RECEIVED_BYTES = 32;
var buffer = new byte[count];
var received = 0;
var counter = MAX_TIMES_0_RECEIVED_BYTES;
while (received != count && counter != 0)
{
counter = (received == 0) ? counter - 1 : MAX_TIMES_0_RECEIVED_BYTES; // TODO add a real timeout
received += Server.Receive(buffer, received, count - received, SocketFlags.None);
}
return buffer;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
public void Dispose(bool disposing)
{
if (!disposing)
return;
server?.Disconnect(false);
server?.Close();
server?.Dispose();
}
#endregion Methods
#region Properties
/// <summary>
/// Gets or sets the socket connection with the proxy server.
/// </summary>
/// <value>A Socket object that represents the connection with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
protected Socket Server
{
get { return server; }
set
{
if (value == null) throw new ArgumentNullException();
server = value;
}
}
/// <summary>
/// Gets the username.
/// </summary>
/// <value>
/// The username.
/// </value>
public string Username { get; private set; }
/// <summary>
/// Gets or sets a byte buffer.
/// </summary>
/// <value>An array of bytes.</value>
protected byte[] Buffer { get; set; }
/// <summary>
/// Gets or sets the number of bytes that have been received from the remote proxy server.
/// </summary>
/// <value>An integer that holds the number of bytes that have been received from the remote proxy server.</value>
protected int Received { get; set; }
/// <summary>
/// Gets or sets the return value of the BeginConnect call.
/// </summary>
/// <value>An IAsyncProxyResult object that is the return value of the BeginConnect call.</value>
protected AsyncSocksResult AsyncResult { get; set; }
#endregion Properties
}
/// <summary>
/// References the callback method to be called when the protocol negotiation is completed.
/// </summary>
public delegate void HandShakeComplete(Exception error);
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Edge.File.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* 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>
/// The metrics associated with a VM
/// First published in XenServer 4.0.
/// </summary>
public partial class VM_metrics : XenObject<VM_metrics>
{
public VM_metrics()
{
}
public VM_metrics(string uuid,
long memory_actual,
long VCPUs_number,
Dictionary<long, double> VCPUs_utilisation,
Dictionary<long, long> VCPUs_CPU,
Dictionary<string, string> VCPUs_params,
Dictionary<long, string[]> VCPUs_flags,
string[] state,
DateTime start_time,
DateTime install_time,
DateTime last_updated,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.memory_actual = memory_actual;
this.VCPUs_number = VCPUs_number;
this.VCPUs_utilisation = VCPUs_utilisation;
this.VCPUs_CPU = VCPUs_CPU;
this.VCPUs_params = VCPUs_params;
this.VCPUs_flags = VCPUs_flags;
this.state = state;
this.start_time = start_time;
this.install_time = install_time;
this.last_updated = last_updated;
this.other_config = other_config;
}
/// <summary>
/// Creates a new VM_metrics from a Proxy_VM_metrics.
/// </summary>
/// <param name="proxy"></param>
public VM_metrics(Proxy_VM_metrics proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VM_metrics update)
{
uuid = update.uuid;
memory_actual = update.memory_actual;
VCPUs_number = update.VCPUs_number;
VCPUs_utilisation = update.VCPUs_utilisation;
VCPUs_CPU = update.VCPUs_CPU;
VCPUs_params = update.VCPUs_params;
VCPUs_flags = update.VCPUs_flags;
state = update.state;
start_time = update.start_time;
install_time = update.install_time;
last_updated = update.last_updated;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_VM_metrics proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
memory_actual = proxy.memory_actual == null ? 0 : long.Parse((string)proxy.memory_actual);
VCPUs_number = proxy.VCPUs_number == null ? 0 : long.Parse((string)proxy.VCPUs_number);
VCPUs_utilisation = proxy.VCPUs_utilisation == null ? null : Maps.convert_from_proxy_long_double(proxy.VCPUs_utilisation);
VCPUs_CPU = proxy.VCPUs_CPU == null ? null : Maps.convert_from_proxy_long_long(proxy.VCPUs_CPU);
VCPUs_params = proxy.VCPUs_params == null ? null : Maps.convert_from_proxy_string_string(proxy.VCPUs_params);
VCPUs_flags = proxy.VCPUs_flags == null ? null : Maps.convert_from_proxy_long_string_array(proxy.VCPUs_flags);
state = proxy.state == null ? new string[] {} : (string [])proxy.state;
start_time = proxy.start_time;
install_time = proxy.install_time;
last_updated = proxy.last_updated;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_VM_metrics ToProxy()
{
Proxy_VM_metrics result_ = new Proxy_VM_metrics();
result_.uuid = (uuid != null) ? uuid : "";
result_.memory_actual = memory_actual.ToString();
result_.VCPUs_number = VCPUs_number.ToString();
result_.VCPUs_utilisation = Maps.convert_to_proxy_long_double(VCPUs_utilisation);
result_.VCPUs_CPU = Maps.convert_to_proxy_long_long(VCPUs_CPU);
result_.VCPUs_params = Maps.convert_to_proxy_string_string(VCPUs_params);
result_.VCPUs_flags = Maps.convert_to_proxy_long_string_array(VCPUs_flags);
result_.state = state;
result_.start_time = start_time;
result_.install_time = install_time;
result_.last_updated = last_updated;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new VM_metrics from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VM_metrics(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
memory_actual = Marshalling.ParseLong(table, "memory_actual");
VCPUs_number = Marshalling.ParseLong(table, "VCPUs_number");
VCPUs_utilisation = Maps.convert_from_proxy_long_double(Marshalling.ParseHashTable(table, "VCPUs_utilisation"));
VCPUs_CPU = Maps.convert_from_proxy_long_long(Marshalling.ParseHashTable(table, "VCPUs_CPU"));
VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "VCPUs_params"));
VCPUs_flags = Maps.convert_from_proxy_long_string_array(Marshalling.ParseHashTable(table, "VCPUs_flags"));
state = Marshalling.ParseStringArray(table, "state");
start_time = Marshalling.ParseDateTime(table, "start_time");
install_time = Marshalling.ParseDateTime(table, "install_time");
last_updated = Marshalling.ParseDateTime(table, "last_updated");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(VM_metrics other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._memory_actual, other._memory_actual) &&
Helper.AreEqual2(this._VCPUs_number, other._VCPUs_number) &&
Helper.AreEqual2(this._VCPUs_utilisation, other._VCPUs_utilisation) &&
Helper.AreEqual2(this._VCPUs_CPU, other._VCPUs_CPU) &&
Helper.AreEqual2(this._VCPUs_params, other._VCPUs_params) &&
Helper.AreEqual2(this._VCPUs_flags, other._VCPUs_flags) &&
Helper.AreEqual2(this._state, other._state) &&
Helper.AreEqual2(this._start_time, other._start_time) &&
Helper.AreEqual2(this._install_time, other._install_time) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, VM_metrics server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VM_metrics.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static VM_metrics get_record(Session session, string _vm_metrics)
{
return new VM_metrics((Proxy_VM_metrics)session.proxy.vm_metrics_get_record(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get a reference to the VM_metrics instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_metrics> get_by_uuid(Session session, string _uuid)
{
return XenRef<VM_metrics>.Create(session.proxy.vm_metrics_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static string get_uuid(Session session, string _vm_metrics)
{
return (string)session.proxy.vm_metrics_get_uuid(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse();
}
/// <summary>
/// Get the memory/actual field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static long get_memory_actual(Session session, string _vm_metrics)
{
return long.Parse((string)session.proxy.vm_metrics_get_memory_actual(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the VCPUs/number field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static long get_VCPUs_number(Session session, string _vm_metrics)
{
return long.Parse((string)session.proxy.vm_metrics_get_vcpus_number(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the VCPUs/utilisation field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, double> get_VCPUs_utilisation(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_double(session.proxy.vm_metrics_get_vcpus_utilisation(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the VCPUs/CPU field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, long> get_VCPUs_CPU(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_long(session.proxy.vm_metrics_get_vcpus_cpu(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the VCPUs/params field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<string, string> get_VCPUs_params(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_vcpus_params(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the VCPUs/flags field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, string[]> get_VCPUs_flags(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_string_array(session.proxy.vm_metrics_get_vcpus_flags(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Get the state field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static string[] get_state(Session session, string _vm_metrics)
{
return (string [])session.proxy.vm_metrics_get_state(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse();
}
/// <summary>
/// Get the start_time field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_start_time(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_start_time(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse();
}
/// <summary>
/// Get the install_time field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_install_time(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_install_time(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse();
}
/// <summary>
/// Get the last_updated field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_last_updated(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_last_updated(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse();
}
/// <summary>
/// Get the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<string, string> get_other_config(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_other_config(session.uuid, (_vm_metrics != null) ? _vm_metrics : "").parse());
}
/// <summary>
/// Set the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vm_metrics, Dictionary<string, string> _other_config)
{
session.proxy.vm_metrics_set_other_config(session.uuid, (_vm_metrics != null) ? _vm_metrics : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vm_metrics, string _key, string _value)
{
session.proxy.vm_metrics_add_to_other_config(session.uuid, (_vm_metrics != null) ? _vm_metrics : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VM_metrics. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vm_metrics, string _key)
{
session.proxy.vm_metrics_remove_from_other_config(session.uuid, (_vm_metrics != null) ? _vm_metrics : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Return a list of all the VM_metrics instances known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_metrics>> get_all(Session session)
{
return XenRef<VM_metrics>.Create(session.proxy.vm_metrics_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VM_metrics Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_metrics>, VM_metrics> get_all_records(Session session)
{
return XenRef<VM_metrics>.Create<Proxy_VM_metrics>(session.proxy.vm_metrics_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Guest's actual memory (bytes)
/// </summary>
public virtual long memory_actual
{
get { return _memory_actual; }
set
{
if (!Helper.AreEqual(value, _memory_actual))
{
_memory_actual = value;
Changed = true;
NotifyPropertyChanged("memory_actual");
}
}
}
private long _memory_actual;
/// <summary>
/// Current number of VCPUs
/// </summary>
public virtual long VCPUs_number
{
get { return _VCPUs_number; }
set
{
if (!Helper.AreEqual(value, _VCPUs_number))
{
_VCPUs_number = value;
Changed = true;
NotifyPropertyChanged("VCPUs_number");
}
}
}
private long _VCPUs_number;
/// <summary>
/// Utilisation for all of guest's current VCPUs
/// </summary>
public virtual Dictionary<long, double> VCPUs_utilisation
{
get { return _VCPUs_utilisation; }
set
{
if (!Helper.AreEqual(value, _VCPUs_utilisation))
{
_VCPUs_utilisation = value;
Changed = true;
NotifyPropertyChanged("VCPUs_utilisation");
}
}
}
private Dictionary<long, double> _VCPUs_utilisation;
/// <summary>
/// VCPU to PCPU map
/// </summary>
public virtual Dictionary<long, long> VCPUs_CPU
{
get { return _VCPUs_CPU; }
set
{
if (!Helper.AreEqual(value, _VCPUs_CPU))
{
_VCPUs_CPU = value;
Changed = true;
NotifyPropertyChanged("VCPUs_CPU");
}
}
}
private Dictionary<long, long> _VCPUs_CPU;
/// <summary>
/// The live equivalent to VM.VCPUs_params
/// </summary>
public virtual Dictionary<string, string> VCPUs_params
{
get { return _VCPUs_params; }
set
{
if (!Helper.AreEqual(value, _VCPUs_params))
{
_VCPUs_params = value;
Changed = true;
NotifyPropertyChanged("VCPUs_params");
}
}
}
private Dictionary<string, string> _VCPUs_params;
/// <summary>
/// CPU flags (blocked,online,running)
/// </summary>
public virtual Dictionary<long, string[]> VCPUs_flags
{
get { return _VCPUs_flags; }
set
{
if (!Helper.AreEqual(value, _VCPUs_flags))
{
_VCPUs_flags = value;
Changed = true;
NotifyPropertyChanged("VCPUs_flags");
}
}
}
private Dictionary<long, string[]> _VCPUs_flags;
/// <summary>
/// The state of the guest, eg blocked, dying etc
/// </summary>
public virtual string[] state
{
get { return _state; }
set
{
if (!Helper.AreEqual(value, _state))
{
_state = value;
Changed = true;
NotifyPropertyChanged("state");
}
}
}
private string[] _state;
/// <summary>
/// Time at which this VM was last booted
/// </summary>
public virtual DateTime start_time
{
get { return _start_time; }
set
{
if (!Helper.AreEqual(value, _start_time))
{
_start_time = value;
Changed = true;
NotifyPropertyChanged("start_time");
}
}
}
private DateTime _start_time;
/// <summary>
/// Time at which the VM was installed
/// </summary>
public virtual DateTime install_time
{
get { return _install_time; }
set
{
if (!Helper.AreEqual(value, _install_time))
{
_install_time = value;
Changed = true;
NotifyPropertyChanged("install_time");
}
}
}
private DateTime _install_time;
/// <summary>
/// Time at which this information was last updated
/// </summary>
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
Changed = true;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
///////////////////////////////////////////////////////////////////////////////
// Copyright 2013 JASDev International
//
// 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.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using JDI.Common;
using JDI.Common.Extensions;
using JDI.Common.Logger;
using JDI.Common.Net;
using JDI.Common.Security;
using JDI.Common.Utils;
namespace JDI.WebSocket.Client
{
public class WebSocketClient : IDisposable
{
#region Constructors and IDisposable
/// <summary>
/// Provides a client for connecting to WebSocket services.
/// </summary>
/// <param name="logSourceID">Identifier to be used when calling the Logger service.</param>
/// <param name="options">Collection of WebSocket options.</param>
public WebSocketClient(string logSourceID, WSOptions options = null)
{
this.loggerID = logSourceID;
this.options = options;
if (this.options == null)
this.options = new WSOptions();
this.origin = this.options.Origin;
this.subProtocol = this.options.SubProtocol;
this.extensions = this.options.Extensions;
this.activityTimerEnabled = this.options.ActivityTimerEnabled;
this.sendFramesMasked = this.options.MaskingEnabled;
this.waitHandshakeTimeout = this.options.HandshakeTimeout;
this.waitCloseMsgTimeout = this.options.CloseMsgTimeout;
this.waitReceiveTimeout = this.options.ReceiveTimeout;
this.waitActivityTimeout = this.options.ActivityTimeout;
this.waitPingRespTimeout = this.options.PingRespTimeout;
this.activityTimer = new TimerEx();
this.state = WebSocketState.Initialized;
this.eventLock = new object();
this.sendLock = new object();
this.isDisposed = false;
this.receiveBuffer = new byte[this.options.MaxReceiveFrameLength];
this.lastRcvdFrame = null;
this.sendQueue = new WSFrameQueue(this.options.MaxSendQueueSize);
// start state machine
try
{
this.runThreadLoop = true;
this.runStateMachine = new AutoResetEvent(false);
this.stateMachineThread = new Thread(new ThreadStart(this.WSStateMachine));
this.stateMachineThread.Start();
}
catch (Exception ex)
{
Logger.WriteError(this.loggerID, ex.Message, ex.StackTrace);
}
}
~WebSocketClient()
{
Dispose( false );
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (this.isDisposed)
return;
if (disposing)
{
// disconnect
this.Disconnect();
DateTime timeoutTime = DateTime.Now.AddSeconds(20);
while (this.state != WebSocketState.Disconnected && DateTime.Now < timeoutTime)
Thread.Sleep(500);
// kill thread
this.runThreadLoop = false;
this.runStateMachine.Set();
this.stateMachineThread.Join(1000);
// clear the message queue
if (this.sendQueue != null)
this.sendQueue.Clear();
// kill timer
if (this.activityTimer != null)
this.activityTimer.Dispose();
// cleanup streams
if (this.socketStream != null)
this.socketStream.Close();
// cleanup sockets
if (this.socket != null)
this.socket.Close();
}
// set everything to null
this.eventLock = null;
this.sendLock = null;
this.activityTimer = null;
this.sendQueue = null;
this.socket = null;
this.socketStream = null;
this.receiveBuffer = null;
this.lastRcvdFrame = null;
this.serverUri = null;
this.loggerID = null;
this.origin = null;
this.subProtocol = null;
this.extensions = null;
this.securityKey = null;
this.options = null;
// make sure we don't dispose again
this.isDisposed = true;
}
#endregion
#region Properties
/// <summary>
/// Get the log source ID.
/// </summary>
public string LoggerID
{
get { return this.loggerID; }
}
/// <summary>
/// Get the header Origin value.
/// </summary>
public string Origin
{
get { return this.origin; }
}
/// <summary>
/// Gets the negotiated websocket sub-protocol.
/// </summary>
public string SubProtocol
{
get
{
if (this.State == WebSocketState.Connected)
return this.subProtocol;
return "";
}
}
/// <summary>
/// Gets a comma-delimited list of the negotiated websocket extensions.
/// </summary>
public string Extensions
{
get
{
if (this.State == WebSocketState.Connected)
return this.extensions;
return "";
}
}
/// <summary>
/// Gets the websocket protocol version in use.
/// </summary>
public string Version
{
get { return WSConst.ProtocolVersion; }
}
/// <summary>
/// Get the current state of the websocket client.
/// </summary>
public WebSocketState State
{
get { return this.state; }
}
#endregion
#region Events
/// <summary>
/// Event that fires when the WebSocket connection state has changed.
/// </summary>
public event WSDelegates.ConnectionChangedEventHandler ConnectionChanged;
/// <summary>
/// Event that fires when a text frame is received from the server.
/// </summary>
public event WSDelegates.TextMessageReceivedEventHandler TextMessageReceived;
/// <summary>
/// Event that fires when a data message is received from the server.
/// </summary>
public event WSDelegates.DataMessageReceivedEventHandler DataMessageReceived;
/// <summary>
/// Event that fires when an error occurs.
/// </summary>
public event WSDelegates.ErrorEventHandler Error;
#endregion
#region Event Invoke Methods
protected void OnConnectionStateChanged()
{
WSDelegates.ConnectionChangedEventHandler handler = null;
lock (this.eventLock)
{
handler = this.ConnectionChanged;
}
if (handler != null)
{
handler(this.state);
}
}
protected void OnTextReceived(string payload)
{
WSDelegates.TextMessageReceivedEventHandler handler = null;
lock (this.eventLock)
{
handler = this.TextMessageReceived;
}
if (handler != null)
{
handler(payload);
}
}
protected void OnDataReceived(byte[] payload)
{
WSDelegates.DataMessageReceivedEventHandler handler = null;
lock (this.eventLock)
{
handler = this.DataMessageReceived;
}
if (handler != null)
{
handler(payload);
}
}
protected void OnError(WSErrorCode errorCode, string message, string stackTrace = null)
{
Logger.WriteError(this.loggerID, string.Concat("Error: (", errorCode.ToString(), ")", message), stackTrace);
WSDelegates.ErrorEventHandler handler = null;
lock (this.eventLock)
{
handler = this.Error;
}
if (handler != null)
{
handler(message, stackTrace);
}
}
#endregion
#region Methods
/// <summary>
/// Connect - Begins the asynchronous (non-blocking) connection process.
/// </summary>
/// <param name="serverUrl">Url of server to connect to.</param>
public void Connect(string serverUrl)
{
if (this.State == WebSocketState.Initialized || this.State == WebSocketState.Disconnected)
{
try
{
this.serverUri = new UriEx(serverUrl);
IPHostEntry hostEntry = Dns.GetHostEntry(this.serverUri.Host);
IPAddress ipAddress = hostEntry.AddressList[0];
this.serverEndpoint = new IPEndPoint(ipAddress, this.serverUri.Port);
// start the connection process
Logger.WriteDebug(this.loggerID, "Connecting to " + serverUrl + " ...");
this.state = WebSocketState.Connecting;
this.subState = SubState.OpenTcpConnection;
this.runStateMachine.Set();
}
catch (Exception ex)
{
this.OnError(WSErrorCode.NativeError, ex.Message, ex.StackTrace);
}
}
}
/// <summary>
/// Disconnect - Begins the asynchronous (non-blocking) disconnection process.
/// </summary>
public void Disconnect()
{
this.Disconnect((int)WSConst.CloseStatusCode.Normal, "Bye!");
}
/// <summary>
/// Disconnect - Begins the asynchronous (non-blocking) disconnection process.
/// </summary>
/// <param name="statusCode">WebSocket close status code (from RFC6455)</param>
/// <param name="reason">Optional reason text.</param>
public void Disconnect(UInt16 statusCode, string reason = null)
{
if (this.state == WebSocketState.Initialized)
{
this.state = WebSocketState.Disconnected;
this.subState = SubState.Disconnected;
}
else if (this.state == WebSocketState.Connecting || this.state == WebSocketState.Connected)
{
Logger.WriteDebug(this.loggerID, "Disconnecting...");
this.closeStatus = statusCode;
this.closeReason = reason;
this.state = WebSocketState.Disconnecting;
this.subState = SubState.SendCloseFrame;
}
}
/// <summary>
/// SendText - Begins the asynchronous (non-blocking) send process.
/// </summary>
/// <param name="text">Text data to send.</param>
public void SendText(string text)
{
if (this.state == WebSocketState.Connected)
{
this.EnqueueMessage(WSFrameType.Text, this.options.MaskingEnabled, text);
}
}
/// <summary>
/// SendData - Begins the asynchronous (non-blocking) send process.
/// </summary>
/// <param name="data">Binary data to send.</param>
public void SendData(byte[] data)
{
if (this.state == WebSocketState.Connected)
{
this.EnqueueMessage(WSFrameType.Binary, this.options.MaskingEnabled, data);
}
}
#endregion
#region State Machine Methods
#region The Main State Machine
protected void WSStateMachine()
{
while (this.runThreadLoop)
{
try
{
switch (this.state)
{
case WebSocketState.Initialized:
// idle
this.runStateMachine.WaitOne(); // wait to be signalled
break;
case WebSocketState.Connecting:
// attempt to connect to server
this.OnConnectionStateChanged();
this.smConnect();
break;
case WebSocketState.Connected:
// receive and parse incoming data
this.OnConnectionStateChanged();
this.smReceive();
break;
case WebSocketState.Disconnecting:
// disconnect from server
this.OnConnectionStateChanged();
this.smDisconnect();
break;
case WebSocketState.Disconnected:
// idle
this.OnConnectionStateChanged();
this.runStateMachine.WaitOne(); // wait to be signalled
break;
default:
// shouldn't get here
throw new NotSupportedException("ReadyState " + this.State.ToString() + " is invalid.");
}
}
catch (Exception ex)
{
if (this.socketStream != null)
{
this.socketStream.Close();
this.socketStream = null;
}
if (this.socket != null)
{
this.socket.Close();
this.socket = null;
}
this.OnError(WSErrorCode.NativeError, ex.Message, ex.StackTrace);
this.state = WebSocketState.Disconnected;
this.subState = SubState.Disconnected;
}
}
}
#endregion
#region smConnect methods
protected void smConnect()
{
while (this.state == WebSocketState.Connecting)
{
switch (this.subState)
{
case SubState.OpenTcpConnection:
// open tcp connection
this.smOpenTcpConnection();
break;
case SubState.SendHandshake:
// send handshake
this.smSendHandshake();
break;
case SubState.WaitForHandshake:
// wait for handshake response
this.smWaitForHandshake();
break;
case SubState.ProcessHandshake:
// process handshake response
this.smProcessHandshake();
break;
case SubState.Connected:
// connection successful
this.smConnected();
return;
case SubState.Failed:
// connection failed
this.smConnectFailed();
return;
}
}
}
protected void smOpenTcpConnection()
{
// create and init socket
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
this.socket.SendTimeout = WSConst.SendTimeout;
this.socket.ReceiveTimeout = WSConst.ReceiveTimeout;
// connect to server
this.socket.Connect(this.serverEndpoint);
// get data stream
if (this.serverUri.Scheme == WSConst.SchemeWSS)
{
this.socketStream = new SslStreamEx(this.socket);
((SslStreamEx)this.socketStream).AuthenticateAsClient(this.serverUri.Host);
}
else
{
this.socketStream = new NetworkStream(this.socket, true);
}
// go to next state
this.subState = SubState.SendHandshake;
}
protected void smSendHandshake()
{
/* Implements RFC6455 websocket specification
*
* GET <target path> HTTP/1.1\r\n
* Host: <target web address>\r\n
* Upgrade: websocket\r\n
* Connection: upgrade\r\n
* Origin: <optional name of origin>\r\n
* Sec-WebSocket-Version: 13\r\n
* Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
* Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
* Sec-WebSocket-Key: <generated key>\r\n
* \r\n
*
*/
// create security key
this.securityKey = this.GetSecurityKey();
// create headers
StringBuilder sb = new StringBuilder();
sb.Append(string.Concat("GET ", this.serverUri.GetPathAndQuery(), " HTTP/1.1", WSConst.HeaderEOL));
sb.Append(string.Concat("Host: ", this.serverUri.Host, WSConst.HeaderEOL));
sb.Append(string.Concat("Upgrade: webSocket", WSConst.HeaderEOL));
sb.Append(string.Concat("Connection: upgrade", WSConst.HeaderEOL));
if (this.origin.Length > 0)
{
sb.Append(string.Concat("Origin: ", this.origin, WSConst.HeaderEOL));
}
if (this.extensions.Length > 0)
{
sb.Append(string.Concat("Sec-WebSocket-Extensions: ", this.extensions, WSConst.HeaderEOL));
}
if (this.subProtocol.Length > 0)
{
sb.Append(string.Concat("Sec-WebSocket-Protocol: ", this.subProtocol, WSConst.HeaderEOL));
}
sb.Append(string.Concat("Sec-WebSocket-Version: ", WSConst.ProtocolVersion, WSConst.HeaderEOL));
sb.Append(string.Concat("Sec-WebSocket-Key: ", this.securityKey, WSConst.HeaderEOL));
sb.Append(WSConst.HeaderEOL);
string headers = sb.ToString();
// send headers
byte[] headerBytes = headers.ToByteArray();
this.socketStream.Write(headerBytes, 0, headerBytes.Length);
Logger.WriteDebug(this.loggerID, string.Concat("Handshake sent: ", headers));
// go to next state
this.subState = SubState.WaitForHandshake;
}
protected void smWaitForHandshake()
{
/* Implements RFC6455 websocket specification
*
* HTTP/1.1 101 Switching Protocols\r\n
* Upgrade: websocket\r\n
* Connection: upgrade\r\n
* Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
* Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
* Sec-WebSocket-Accept: <response key>\r\n
* <other headers, cookies, etc>
* \r\n
*
*/
int bytesRead = 0;
this.bytesInBuffer = 0;
this.posHeaderEOF = 0;
this.bytesInBuffer = 0;
// TODO - modify to extract individual headers as they arrive in the buffer
if (this.socket.Poll(this.waitHandshakeTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
{
do
{
bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
if (bytesRead > 0)
{
this.bytesInBuffer += bytesRead;
this.posHeaderEOF = this.receiveBuffer.IndexOf(WSConst.HeaderEOF);
if (posHeaderEOF >= 0)
{
this.LogBufferContent("Handshake received: ", this.receiveBuffer, 0, this.bytesInBuffer);
this.subState = SubState.ProcessHandshake;
return;
}
}
}
while (this.socket.Available > 0 && this.bytesInBuffer < this.receiveBuffer.Length);
}
Logger.WriteError(this.loggerID, "Handshake not received.");
this.subState = SubState.Failed;
}
protected void smProcessHandshake()
{
/* Implements RFC6455 websocket specification
*
* HTTP/1.1 101 Switching Protocols\r\n
* Upgrade: websocket\r\n
* Connection: upgrade\r\n
* Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
* Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
* Sec-WebSocket-Accept: <response key>\r\n
* \r\n
*
*/
// get response headers
ArrayList headers = this.receiveBuffer.Split(WSConst.HeaderEOL, 0, this.posHeaderEOF + WSConst.HeaderEOF.Length, false);
// for debugging
// this.socketBuffer = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: upgrade\r\nSec-WebSocket-Extensions: ext1, ext3\r\nSec-WebSocket-Protocol: prot2!#%'-_@~$*+.^|\r\nSec-WebSocket-Accept: Kfh9QIsMVZcl6xEPYxPHzW8SZ8w=\r\n\r\n" + "\x81\x53{\"event\":\"pusher:connection_established\",\"data\":\"{\\\"socket_id\\\":\\\"23086.813011\\\"}\"}");
// this.bytesInBuffer = this.socketBuffer.Length;
// this.posHeaderEOF = this.socketBuffer.IndexOf(WSConstants.HeaderEOF);
// ArrayList headers = this.socketBuffer.Split(WSConstants.HeaderEOL, 0, this.posHeaderEOF + WSConstants.HeaderEOF.Length, false);
// remove headers from socket buffer
if (this.posHeaderEOF >= 0)
{
this.posHeaderEOF += WSConst.HeaderEOF.Length;
Array.Copy(this.receiveBuffer, this.posHeaderEOF, this.receiveBuffer, 0, this.bytesInBuffer - this.posHeaderEOF);
this.bytesInBuffer = this.bytesInBuffer - this.posHeaderEOF;
}
// log response headers
if (Logger.GetLogLevel() == LogLevel.Debug)
{
for (int i = 0; i < headers.Count; i++)
{
Logger.WriteDebug(this.loggerID, string.Concat("Handshake header: ", headers[i]));
}
}
// validate response headers
Regex regex = null;
string header = "";
bool isDone = false;
bool responseIsValid = false;
int headerIndex = 0;
int step = 0;
while (!isDone)
{
Continue:
step++;
switch (step)
{
case 1:
// check for response code 101
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"http/\d+\.\d+\s+101", RegexOptions.IgnoreCase);
if (regex.IsMatch(header))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
else
{
// TODO - process other response codes per RFC2616
}
}
break;
case 2:
// check for 'upgrade: websocket'
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"upgrade:\s+websocket", RegexOptions.IgnoreCase);
if (regex.IsMatch(header))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
}
break;
case 3:
// check for 'connection: upgrade'
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"connection:\s+upgrade", RegexOptions.IgnoreCase);
if (regex.IsMatch(header))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
}
break;
case 4:
// check that 'sec-websocket-extensions:' list is valid
// TODO - validate extensions header
goto Continue;
/*
if (this.extensionList.Length == 0)
{
goto Continue;
}
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"(sec-websocket-extensions):\s+(.+)", RegexOptions.IgnoreCase);
Match match = regex.Match(header);
if (match.Success && this.IsValidExtensionsResponse(match.Groups[2].Value))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
}
break;
*/
case 5:
// check that 'sec-websocket-protocol:' list is valid
if (this.subProtocol.Length == 0)
{
goto Continue;
}
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"sec-websocket-protocol:\s+([A-Za-z0-9!#%'-_@~\$\*\+\.\^\|]+$)", RegexOptions.IgnoreCase);
Match match = regex.Match(header);
if (match.Success && this.IsValidProtocolResponse(match.Groups[1].Value))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
}
break;
case 6:
// check that 'sec-websocket-accept: secKey' is valid
for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
{
header = ((string)headers[headerIndex]);
regex = new Regex(@"sec-websocket-accept:\s+([A-Za-z0-9+/=]+)", RegexOptions.IgnoreCase);
Match match = regex.Match(header);
if (match.Success && this.IsValidSecurityResponse(match.Groups[1].Value))
{
headers.RemoveAt(headerIndex);
goto Continue;
}
}
break;
case 7:
// TODO - check for cookie header
goto Continue;
case 8:
// done
responseIsValid = true;
break;
}
// stop looping
isDone = true;
}
// TODO - cleanup headers list
headers.Clear();
headers = null;
if (!responseIsValid)
{
Logger.WriteError(this.loggerID, "Handshake response is invalid");
this.subState = SubState.Failed;
return;
}
// go to next state
this.subState = SubState.Connected;
}
protected void smConnected()
{
Logger.WriteDebug(this.loggerID, "Connected");
this.state = WebSocketState.Connected;
this.subState = SubState.Connected;
}
protected void smConnectFailed()
{
if (this.socketStream != null)
{
this.socketStream.Close();
this.socketStream = null;
}
if (this.socket != null)
{
this.socket.Close();
this.socket = null;
}
this.state = WebSocketState.Disconnected;
this.subState = SubState.Disconnected;
}
#endregion
#region smReceive methods
protected void smReceive()
{
int bytesRead = 0;
this.lastRcvdFrame = null;
// start activity timer
if (this.activityTimerEnabled)
{
this.activityTimer.Start(this.waitActivityTimeout, ActivityTimerState.WaitingForMessage);
}
while (this.State == WebSocketState.Connected)
{
// process data in buffer
if (this.bytesInBuffer > 0)
{
if (WSFrame.TryParse(this.receiveBuffer, 0, this.bytesInBuffer, this.options.MaxReceiveFrameLength, out this.lastRcvdFrame) == true)
{
// restart activity timer
if (this.activityTimerEnabled)
{
this.activityTimer.Restart(ActivityTimerState.WaitingForMessage);
}
// remove data-frame from buffer
Array.Copy(this.receiveBuffer, this.lastRcvdFrame.FrameData.Length, this.receiveBuffer, 0, this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length);
this.bytesInBuffer = this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length;
// take action based on opcode
switch (this.lastRcvdFrame.OpCode)
{
case WSFrameType.Continuation:
// TODO - implement continuation frames
break;
case WSFrameType.Text:
this.LogBufferContent("Text frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
this.OnTextReceived(this.lastRcvdFrame.PayloadText);
break;
case WSFrameType.Binary:
this.LogBufferContent("Data frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
this.OnDataReceived(this.lastRcvdFrame.PayloadBytes);
break;
case WSFrameType.Close:
this.LogBufferContent("Close frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
// based on RFC6455 we must stop sending and receiving messages after Close response is sent
this.activityTimer.Stop();
this.state = WebSocketState.Disconnecting;
this.subState = SubState.CloseTcpConnection;
this.smSendCloseResponse();
return;
case WSFrameType.Ping:
this.LogBufferContent("Ping frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
this.smSendPongMessage();
break;
case WSFrameType.Pong:
this.LogBufferContent("Pong frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
// no need to do anything
break;
default:
this.LogBufferContent("Unknown frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
break;
}
}
}
// send queued messages
if (this.DequeueAndSendMessages() && this.activityTimerEnabled)
{
this.activityTimer.Restart(ActivityTimerState.MessageSent);
}
// get more data
if (this.socket.Poll(this.waitReceiveTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
{
bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
this.bytesInBuffer += bytesRead;
continue;
}
// check activity timer
if (this.activityTimer.HasTimedOut)
{
switch ((ActivityTimerState)this.activityTimer.State)
{
case ActivityTimerState.MessageSent:
case ActivityTimerState.WaitingForMessage:
this.smSendPingMessage();
activityTimer.Restart(ActivityTimerState.WaitingForPingResponse);
break;
case ActivityTimerState.WaitingForPingResponse:
Logger.WriteError(this.loggerID, string.Concat("Ping response timed out."));
activityTimer.Stop();
this.state = WebSocketState.Disconnecting;
this.subState = SubState.CloseTcpConnection;
break;
}
}
}
}
protected void smSendPingMessage()
{
WSFrame wsFrame = WSFrame.CreateFrame(WSFrameType.Ping, this.options.MaskingEnabled, "Hello");
this.LogBufferContent("Sending ping frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
}
protected void smSendPongMessage()
{
WSFrame wsFrame = WSFrame.CreateFrame(WSFrameType.Pong, this.options.MaskingEnabled, "Hello");
this.LogBufferContent("Sending pong frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
}
#endregion
#region smDisconnect methods
protected void smDisconnect()
{
while (this.state == WebSocketState.Disconnecting)
{
switch (this.subState)
{
case SubState.SendCloseFrame:
// send close frame
this.smSendCloseFrame();
break;
case SubState.WaitForCloseResponse:
// wait for close response
this.smWaitCloseResponse();
break;
case SubState.CloseTcpConnection:
// close tcp connection
this.smCloseTcpConnection();
break;
case SubState.Disconnected:
// disconnection successful
this.smDisconnected();
return;
case SubState.Failed:
// disconnection failed
this.smDisconnectFailed();
return;
default:
// shouldn't get here
throw new NotSupportedException("ConnectionState " + this.subState.ToString() + " is invalid.");
}
}
}
protected void smSendCloseFrame()
{
WSFrame wsFrame = WSFrame.CreateFrame(WSFrameType.Close, this.options.MaskingEnabled, ArrayUtil.Concat(this.closeStatus, this.closeReason));
this.LogBufferContent("Sending close frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.subState = SubState.WaitForCloseResponse;
}
protected void smSendCloseResponse()
{
byte[] payLoad = null;
if (this.lastRcvdFrame.OpCode == WSFrameType.Close && this.lastRcvdFrame.PayloadLength > 0)
{
// reply with the same status code and reason
payLoad = this.lastRcvdFrame.PayloadBytes;
}
WSFrame wsFrame = WSFrame.CreateFrame(WSFrameType.Close, this.options.MaskingEnabled, payLoad);
this.LogBufferContent("Sending close frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
}
protected void smWaitCloseResponse()
{
int bytesRead = 0;
this.posHeaderEOF = 0;
this.bytesInBuffer = 0;
if (this.socket.Poll(this.waitCloseMsgTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
{
do
{
bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
if (bytesRead > 0)
{
this.bytesInBuffer += bytesRead;
if (WSFrame.TryParse(this.receiveBuffer, 0, this.bytesInBuffer, this.options.MaxReceiveFrameLength, out this.lastRcvdFrame) == true)
{
// remove data-frame from buffer
Array.Copy(this.receiveBuffer, this.lastRcvdFrame.FrameData.Length, this.receiveBuffer, 0, this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length);
this.bytesInBuffer = this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length;
// check for close frame
if (this.lastRcvdFrame.OpCode == WSFrameType.Close)
{
this.LogBufferContent("Close frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
this.subState = SubState.CloseTcpConnection;
return;
}
this.LogBufferContent("Data frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
}
}
}
while (this.socket.Available > 0 && this.bytesInBuffer < this.receiveBuffer.Length);
}
Logger.WriteError(this.loggerID, "Close frame not received.");
this.subState = SubState.Failed;
}
protected void smCloseTcpConnection()
{
if (this.socketStream != null)
{
this.socketStream.Close();
this.socketStream = null;
}
if (this.socket != null)
{
this.socket.Close();
this.socket = null;
}
this.subState = SubState.Disconnected;
}
protected void smDisconnected()
{
this.state = WebSocketState.Disconnected;
this.subState = SubState.Disconnected;
}
protected void smDisconnectFailed()
{
if (this.socketStream != null)
{
this.socketStream.Close();
this.socketStream = null;
}
if (this.socket != null)
{
this.socket.Close();
this.socket = null;
}
this.state = WebSocketState.Disconnected;
this.subState = SubState.Disconnected;
}
#endregion
#endregion
#region Private and Protected Methods
protected string GetSecurityKey()
{
byte[] secBytes = CryptoUtils.GetRandomBytes(16);
return ConvertEx.ToBase64String(secBytes);
}
protected bool IsValidExtensionsResponse(string responseExtensionList)
{
// TODO - implementation extensions validation
return false;
/*
// multiple extensions are allowed per RFC6455
string[] responseExtensions = responseExtensionList.Split(',');
string[] requestedExtensions = this.extensionList.Split(',');
this.extensionList = "";
for (int i=0; i < requestedExtensions.Length; i++)
{
requestedExtensions[i] = requestedExtensions[i].Trim().ToLower();
for (int j=0; j < responseExtensions.Length; j++)
{
responseExtensions[j] = responseExtensions[j].Trim().ToLower();
if (responseExtensions[j] == requestedExtensions[i])
{
if (this.extensionList.Length > 0)
this.extensionList = string.Concat(this.extensionList, ",", requestedExtensions[i]);
else
this.extensionList = requestedExtensions[i];
break;
}
}
}
return this.extensionList.Length > 0;
*/
}
protected bool IsValidProtocolResponse(string responseProtocol)
{
// only one protocol is allowed per RFC6455
responseProtocol = responseProtocol.Trim().ToLower();
string[] requestedProtocols = this.subProtocol.Split(',');
this.subProtocol = "";
for (int i = 0; i < requestedProtocols.Length; i++)
{
if (responseProtocol == requestedProtocols[i].Trim().ToLower())
{
this.subProtocol = requestedProtocols[i];
break;
}
}
return this.subProtocol.Length > 0;
}
protected bool IsValidSecurityResponse(string responseSecKey)
{
// build expected secKey
byte[] tempbytes = Encoding.UTF8.GetBytes(string.Concat(this.securityKey, WSConst.HeaderSecurityGUID));
string expectedSecKey = ConvertEx.ToBase64String(CryptoUtils.ComputeSha1Hash(tempbytes));
Logger.WriteDebug(this.loggerID, "Expected sec key: " + expectedSecKey);
Logger.WriteDebug(this.loggerID, "Response sec key: " + responseSecKey);
if (expectedSecKey == responseSecKey)
return true;
return false;
}
protected void EnqueueMessage(WSFrameType opCode, bool isMasked, string payLoad, bool highPriority = false)
{
WSFrame wsFrame = WSFrame.CreateFrame(opCode, isMasked, payLoad);
if (highPriority)
this.sendQueue.Poke(wsFrame);
else
this.sendQueue.Enqueue(wsFrame);
}
protected void EnqueueMessage(WSFrameType opCode, bool isMasked, byte[] payLoad, bool highPriority = false)
{
WSFrame wsFrame = WSFrame.CreateFrame(opCode, isMasked, payLoad);
if (highPriority)
this.sendQueue.Poke(wsFrame);
else
this.sendQueue.Enqueue(wsFrame);
}
protected bool DequeueAndSendMessages()
{
bool messagesSent = this.sendQueue.Count > 0;
lock (this.sendLock)
{
while (this.sendQueue.Count > 0)
{
WSFrame wsFrame = this.sendQueue.Dequeue();
this.LogBufferContent("Sending data frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
}
}
return messagesSent;
}
protected void LogBufferContent(string prefix, byte[] buffer, int startIndex, int length)
{
if (Logger.GetLogLevel() == LogLevel.Debug)
Logger.WriteDebug(this.loggerID, string.Concat(prefix, buffer.ToHex(startIndex, length)));
}
#endregion
#region Member Fields
protected object eventLock;
protected object sendLock;
protected bool isDisposed;
protected bool runThreadLoop;
protected AutoResetEvent runStateMachine;
protected Thread stateMachineThread;
protected string loggerID;
protected string origin;
protected string subProtocol;
protected string extensions;
protected WebSocketState state;
protected SubState subState;
protected WSOptions options;
protected string securityKey;
protected bool activityTimerEnabled;
protected bool sendFramesMasked;
protected TimerEx activityTimer;
protected int waitHandshakeTimeout; // timeout in seconds to wait for handshake response
protected int waitCloseMsgTimeout; // timeout in seconds to wait for close response
protected int waitReceiveTimeout; // timeout in seconds to wait for receive data
protected int waitActivityTimeout; // timeout in seconds to wait for receive data
protected int waitPingRespTimeout; // timeout in seconds to wait for receive data
protected UriEx serverUri;
protected EndPoint serverEndpoint;
protected Socket socket;
protected Stream socketStream;
private WSFrame lastRcvdFrame;
protected UInt16 closeStatus;
protected string closeReason;
protected byte[] receiveBuffer;
protected int bytesInBuffer;
protected int posHeaderEOF;
private WSFrameQueue sendQueue;
protected enum SubState
{
Initialized,
OpenTcpConnection,
SendHandshake,
WaitForHandshake,
ProcessHandshake,
Connected,
SendCloseFrame,
WaitForCloseResponse,
CloseTcpConnection,
Disconnected,
Failed
}
protected enum ActivityTimerState
{
MessageSent,
WaitingForMessage,
WaitingForPingResponse
}
#endregion
}
}
| |
using Anycmd.Xacml.Policy;
using Anycmd.Xacml.Policy.TargetItems;
using System;
using ctx = Anycmd.Xacml.Context;
namespace Anycmd.Xacml.Runtime
{
/// <summary>
/// Mantains the value resulted of the evaluation of the variable definition.
/// </summary>
public class VariableDefinition : IEvaluable
{
#region Private members
/// <summary>
/// References the variable definition element in the policy document.
/// </summary>
private readonly VariableDefinitionElement _variableDefinition;
/// <summary>
/// The value resulted from the evaluation.
/// </summary>
private EvaluationValue _value;
/// <summary>
/// Whether the variable have been evaluated.
/// </summary>
private bool _isEvaluated;
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="variableDefinition">The variable definition in the policy document.</param>
public VariableDefinition(VariableDefinitionElement variableDefinition)
{
_variableDefinition = variableDefinition;
}
#endregion
#region IEvaluable Members
/// <summary>
/// Evaluates the variable into a value.
/// </summary>
/// <param name="context">The contex of the evaluation.</param>
/// <returns>The value of the function.</returns>
public EvaluationValue Evaluate(EvaluationContext context)
{
if (context == null) throw new ArgumentNullException("context");
context.Trace("Evaluating variable");
context.AddIndent();
try
{
if (_variableDefinition.Expression is ApplyElement)
{
context.Trace("Apply within condition.");
// There is a nested apply un this policy a new Apply will be created and also
// evaluated. It's return value will be used as the processed argument.
Apply childApply = new Apply((ApplyElement)_variableDefinition.Expression);
// Evaluate the Apply
_value = childApply.Evaluate(context);
context.TraceContextValues();
return _value;
}
else if (_variableDefinition.Expression is FunctionElement)
{
throw new NotImplementedException("FunctionElement"); //TODO:
}
else if (_variableDefinition.Expression is VariableReferenceElement)
{
var variableRef = _variableDefinition.Expression as VariableReferenceElement;
var variableDef = context.CurrentPolicy.VariableDefinition[variableRef.VariableId] as VariableDefinition;
context.TraceContextValues();
if (!variableDef.IsEvaluated)
{
return variableDef.Evaluate(context);
}
else
{
return variableDef.Value;
}
}
else if (_variableDefinition.Expression is AttributeValueElementReadWrite)
{
// The AttributeValue does not need to be processed
context.Trace("Attribute value {0}", _variableDefinition.Expression.ToString());
var att = (AttributeValueElementReadWrite)_variableDefinition.Expression;
var attributeValue = new AttributeValueElement(att.DataType, att.Contents, att.SchemaVersion);
_value = new EvaluationValue(
attributeValue.GetTypedValue(attributeValue.GetType(context), 0),
attributeValue.GetType(context));
return _value;
}
else if (_variableDefinition.Expression is AttributeDesignatorBase)
{
// Resolve the AttributeDesignator using the EvaluationEngine public methods.
context.Trace("Processing attribute designator: {0}", _variableDefinition.Expression.ToString());
var attrDes = (AttributeDesignatorBase)_variableDefinition.Expression;
BagValue bag = EvaluationEngine.Resolve(context, attrDes);
// If the attribute was not resolved by the EvaluationEngine search the
// attribute in the context document, also using the EvaluationEngine public
// methods.
if (bag.BagSize == 0)
{
if (_variableDefinition.Expression is SubjectAttributeDesignatorElement)
{
ctx.AttributeElement attrib = EvaluationEngine.GetAttribute(context, attrDes);
if (attrib != null)
{
context.Trace("Adding subject attribute designator: {0}", attrib.ToString());
bag.Add(attrib);
}
}
else if (_variableDefinition.Expression is ResourceAttributeDesignatorElement)
{
ctx.AttributeElement attrib = EvaluationEngine.GetAttribute(context, attrDes);
if (attrib != null)
{
context.Trace("Adding resource attribute designator {0}", attrib.ToString());
bag.Add(attrib);
}
}
else if (_variableDefinition.Expression is ActionAttributeDesignatorElement)
{
ctx.AttributeElement attrib = EvaluationEngine.GetAttribute(context, attrDes);
if (attrib != null)
{
context.Trace("Adding action attribute designator {0}", attrib.ToString());
bag.Add(attrib);
}
}
else if (_variableDefinition.Expression is EnvironmentAttributeDesignatorElement)
{
ctx.AttributeElement attrib = EvaluationEngine.GetAttribute(context, attrDes);
if (attrib != null)
{
context.Trace("Adding environment attribute designator {0}", attrib.ToString());
bag.Add(attrib);
}
}
}
// If the argument was not found and the attribute must be present this is
// a MissingAttribute situation so set the flag. Otherwise add the attribute
// to the processed arguments.
if (bag.BagSize == 0 && attrDes.MustBePresent)
{
context.Trace("Attribute is missing");
context.IsMissingAttribute = true;
context.AddMissingAttribute(attrDes);
_value = EvaluationValue.Indeterminate;
}
else
{
_value = new EvaluationValue(bag, bag.GetType(context));
}
return _value;
}
else if (_variableDefinition.Expression is AttributeSelectorElement)
{
// Resolve the XPath query using the EvaluationEngine public methods.
context.Trace("Attribute selector");
try
{
var attributeSelector = (AttributeSelectorElement)_variableDefinition.Expression;
BagValue bag = EvaluationEngine.Resolve(context, attributeSelector);
if (bag.Elements.Count == 0 && attributeSelector.MustBePresent)
{
context.Trace("Attribute is missing");
context.IsMissingAttribute = true;
context.AddMissingAttribute(attributeSelector);
_value = EvaluationValue.Indeterminate;
}
else
{
_value = new EvaluationValue(bag, bag.GetType(context));
}
}
catch (EvaluationException e)
{
context.Trace("ERR: {0}", e.Message);
context.ProcessingError = true;
_value = EvaluationValue.Indeterminate;
}
return _value;
}
throw new NotSupportedException("internal error");
}
finally
{
_isEvaluated = true;
context.RemoveIndent();
}
}
#endregion
#region Public properties
/// <summary>
/// The value of the variable.
/// </summary>
public EvaluationValue Value
{
get
{
if (!_isEvaluated)
{
throw new EvaluationException("Te variable must be evaluated.");
}
return _value;
}
}
/// <summary>
/// Whether the variable have been evaluated.
/// </summary>
public bool IsEvaluated
{
get { return _isEvaluated; }
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Configuration;
using MySql.Data.MySqlClient;
using EmergeTk;
using EmergeTk.Model;
using System.IO;
namespace emergetool
{
public class DatabaseSynchronizer
{
// EmergeTk.EmergeTkLog log = EmergeTk.EmergeTkLogManager.GetLogger(typeof(DatabaseSynchronizer));
public IDataProvider provider;
/// <summary>
/// whether or not to print extra messages about the program's output
/// </summary>
private bool verbose;
public bool Verbose {
set { verbose = value; }
}
/// <summary>
/// whether or not to ignore types in the EmergeTk namespace
/// </summary>
private bool ignoreEmergeTk;
public bool IgnoreEmergeTk {
set { ignoreEmergeTk = value; }
}
/// <summary>
/// list of types that are derived from AbstractRecord
/// </summary>
private List<Type> TypeList
{
get
{
var derivedTypes = TypeLoader.GetTypesOfBaseType( typeof(AbstractRecord) );
List<Type> typeList = new List<Type>();
foreach ( Type t in derivedTypes ) {
string assemblyName = t.Assembly.FullName;
if ( ! t.IsAbstract && (! ignoreEmergeTk || (ignoreEmergeTk && ! assemblyName.Contains("EmergeTk"))) )
typeList.Add( t );
}
return typeList;
}
}
private List<string> dllList;
private ColumnInfo[] relationTableColumns;
/// <summary>
/// constructor
/// </summary>
public DatabaseSynchronizer() {
provider = DataProvider.DefaultProvider;
verbose = false;
ignoreEmergeTk = true;
dllList = new List<String>();
relationTableColumns = ColumnInfoManager.GetRelationTableColumns();
}
/// <summary>
/// try loading the given assembly into the current environment; if it fails throws exception
/// </summary>
/// <param name="assemblyName">
/// A <see cref="System.String"/>
/// the name of the assembly to be loaded
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if there are problems with loading the given assembly
/// </exception>
public void LoadAssembly(string assemblyName)
{
try {
System.Reflection.Assembly.LoadFile(assemblyName);
dllList.Add(assemblyName);
}
catch
{
throw new ArgumentException("problems loading assembly " + assemblyName);
}
}
public void SetConnectionString(string cString) {
//provider.SetConnectionString(cString);
throw new NotImplementedException ();
}
/// <summary>
/// loops through the TypeList (see above) and determines if a table exists in the
/// database for it, returning SQL add table statements that would fix any missing tables.
/// if the type is generic, no analysis is done
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// SQL statements to add databases to fix synchronization issues
/// </returns>
public string GenerateCreateTableStatements()
{
string result = printVerbose("");
result += printVerbose( "GENERATING CREATE TABLE STATEMENTS FOR THE FOLLOWING DLL(S): " );
foreach (string s in dllList) result += printVerbose(s);
result += printVerbose("");
if (ignoreEmergeTk) {
result += printVerbose( "IGNORING EmergeTk NAMESPACE" );
result += printVerbose( "" );
}
foreach ( Type t in TypeList )
{
string tName;
if ( ! t.IsGenericType ) {
//TODO: this is a bug -- on creating an instance of static objects that save to
// the database immediately, we get phantom tables in the database we
// are analyzing
tName = ( Activator.CreateInstance( t ) as AbstractRecord ).ModelName;
if ( ! provider.TableExistsNoCache( tName ) )
result += provider.GenerateAddTableStatement( t ) + "\n";
// check for relational tables
ColumnInfo[] ci = ColumnInfoManager.RequestColumns( t );
foreach ( ColumnInfo c in ci )
{
if ( AbstractRecord.TypeIsRecordList( c.Type ) )
{
string relationTable = tName + "_" + c.Name;
if ( ! provider.TableExistsNoCache( relationTable ) )
result += provider.GenerateAddChildTableStatement( relationTable, c.IsDerived ) + "\n";
}
}
}
else
result += printVerbose( "skipping generic type " + t.Name );
}
return result;
}
/// <summary>
/// loops through the TypeList, and if a table exists for that type, checks that the
/// columns are correct based on the OR/M. returns SQL statements to add and remove
/// columns appropriately
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// SQL statements to add and remove columns from tables that are out of sync with the OR/M
/// </returns>
public string GenerateAlterColumnStatements()
{
string result = printVerbose("");
result += printVerbose( "GENERATING ALTER TABLE STATEMENTS FOR THE FOLLOWING DLL(S): " );
foreach (string s in dllList) result += printVerbose(s);
result += printVerbose("");
if (ignoreEmergeTk) {
result += printVerbose( "IGNORING EmergeTk NAMESPACE" );
result += printVerbose( "" );
}
foreach ( Type t in TypeList )
{
result += GenerateAlterSingleTableStatement( t );
}
return result;
}
/// <summary>
/// checks the given type's associated table in the database and generates SQL statements
/// to add, remove, and modify any columns to fix synchronization issues. if the type has
/// no table, or is generic, the columns are not analyzed
/// </summary>
/// <param name="t">
/// A <see cref="Type"/>
/// the type that is associated with the table to check
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// SQL statements to fix any synchronization issues
/// </returns>
public string GenerateAlterSingleTableStatement( Type t )
{
string tableName;
if ( ! t.IsGenericType )
//TODO: this is an unsolvable bug -- on creating an instance of objects that save to
// the database immediately, we get phantom tables in the database we
// are analyzing
tableName = ( Activator.CreateInstance( t ) as AbstractRecord ).ModelName;
else
return printVerbose( "skipping generic type " + t.Name );
string result = printVerbose( "analyzing type " + t.Name + " with table name '" + tableName + "'");
ColumnInfo[] expectedColumns = ColumnInfoManager.RequestColumns( t );
IEnumerable<ColumnInfo> initAddColumns = new List<ColumnInfo>();
if ( ! provider.TableExistsNoCache( tableName ) )
{
result += printVerbose( "table " + tableName + " does not exist: skipping column analysis" );
}
else
{
result += CheckIdColumn( tableName );
DataTable actualColumnsTable = provider.GetColumnTable( tableName );
List<ColumnInfo> actualColumns = new List<ColumnInfo>();
// this is essentially an except( actual, expected ) with some extra logic to check that types match
foreach ( DataRow r in actualColumnsTable.Rows )
{
// don't look at identity column here
if ( ! (r[0] as string).Equals( provider.GetIdentityColumn() ) )
{
MethodInfo mi = typeof(ColumnInfoManager).GetMethod("RequestColumn", new Type[] { typeof( string ) } );
mi = mi.MakeGenericMethod( t );
ColumnInfo col = mi.Invoke(null, new object[] { r[0] }) as ColumnInfo;
if (col == null) // doesn't exist in the expected columns
{
result += provider.GenerateRemoveColStatement( r[0] as string, tableName ) + "\n";
//removeColumns.Add( r[0] as string );
continue;
}
actualColumns.Add( col );
if ( ! provider.GetSqlTypeFromType( col, tableName ).Equals( (r[1]) ) ) {// check that types match
result += provider.GenerateFixColTypeStatement( col, tableName ) + "\n";
}
}
}
initAddColumns = Enumerable.Except( expectedColumns, actualColumns );
}
// check relation tables, and build the addColumns list from initAddColumns
foreach ( ColumnInfo c in expectedColumns )
{
if ( (! AbstractRecord.TypeIsRecordList( c.Type ) ) && initAddColumns.Contains( c ) )
result += provider.GenerateAddColStatement( c, tableName ) + "\n";
else if ( AbstractRecord.TypeIsRecordList( c.Type ) )
{
string relationTable = tableName + "_" + c.Name;
if (DataProvider.LowerCaseTableNames) relationTable = relationTable.ToLower();
result += CheckRelationTable( relationTable, c );
}
}
return result;
}
/// <summary>
/// check that the given relation table exists and matches the correct format for relation tables
/// and returns alter statements to fix/add the table if needed
/// </summary>
/// <param name="table">
/// A <see cref="System.String"/>
/// the name of the relation table to analyze
/// </param>
/// <param name="c">
/// A <see cref="ColumnInfo"/>
/// the ColumnInfo from the parent type that is attached to this relation table
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// the alter statements that would fix any problems with the table
/// </returns>
private string CheckRelationTable( string table, ColumnInfo c )
{
string result = printVerbose("analyzing relation table " + table);
if ( ! provider.TableExistsNoCache ( table ) )
{
result += printVerbose("table " + table + " does not exist: skipping column analysis");
}
else // check that the relation table is set up properly
{
DataTable relationDT = provider.GetColumnTable( table );
foreach ( DataRow r in relationDT.Rows )
{
bool found = false;
foreach ( ColumnInfo col in relationTableColumns )
{
if ( col.Name.ToLower().Equals( (r[0] as string).ToLower() ) ) // not case sensitivity
{
found = true;
break;
}
}
if ( ! found )
result += provider.GenerateRemoveColStatement( r[0] as string, table ) + "\n";
}
foreach ( ColumnInfo col in relationTableColumns )
{
bool found = false;
foreach ( DataRow r in relationDT.Rows )
{
if ( col.Name.ToLower().Equals( (r[0] as string).ToLower() ) )
{
found = true;
if ( ! provider.GetSqlTypeFromType( col, table ).ToLower().Equals( (r[1] as string).ToLower() ) )
result += provider.GenerateFixColTypeStatement( col, table ) + "\n";
break;
}
}
if ( ! found )
result += provider.GenerateAddColStatement( col, table ) + "\n";
}
}
return result;
}
/// <summary>
/// check that the IdColumn of the given table exists and is correctly set up
/// </summary>
/// <param name="table">
/// A <see cref="System.String"/>
/// the name of the table to analyze
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// the alter statements that would fix any problems with the IdColumn of the table
/// </returns>
private string CheckIdColumn( string table )
{
string result = provider.CheckIdColumn( table );
if (result.Equals(""))
return "";
else
return result + "\n";
}
/// <summary>
/// if verbose printout is true, returns the given message lead by a
/// comment character; returns the empty string otherwise
/// </summary>
/// <param name="message">
/// A <see cref="System.String"/>
/// the message to print
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string printVerbose(string message)
{
if (verbose)
return provider.GetCommentCharacter() + " " + message + "\n";
else
return "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Security;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#else
internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#endif
{
private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack();
private XmlSerializableWriter _xmlSerializableWriter;
private const int depthToCheckCyclicReference = 512;
private ObjectToIdCache _serializedObjects;
private bool _isGetOnlyCollection;
private readonly bool _unsafeTypeForwardingEnabled;
protected bool serializeReadOnlyTypes;
protected bool preserveObjectReferences;
internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
{
return new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract
, dataContractResolver
);
}
protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver)
: base(serializer, rootTypeDataContract, resolver)
{
this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
#if USE_REFEMIT || NET_NATIVE
internal ObjectToIdCache SerializedObjects
#else
protected ObjectToIdCache SerializedObjects
#endif
{
get
{
if (_serializedObjects == null)
_serializedObjects = new ObjectToIdCache();
return _serializedObjects;
}
}
internal override bool IsGetOnlyCollection
{
get { return _isGetOnlyCollection; }
set { _isGetOnlyCollection = value; }
}
internal bool SerializeReadOnlyTypes
{
get { return this.serializeReadOnlyTypes; }
}
internal bool UnsafeTypeForwardingEnabled
{
get { return _unsafeTypeForwardingEnabled; }
}
#if USE_REFEMIT
public void StoreIsGetOnlyCollection()
#else
internal void StoreIsGetOnlyCollection()
#endif
{
_isGetOnlyCollection = true;
}
#if USE_REFEMIT
public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/))
InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle);
OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/);
}
#if USE_REFEMIT
public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (writeXsiType)
{
Type declaredType = Globals.TypeOfObject;
SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType);
}
else if (isDeclaredType)
{
DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle);
SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle);
}
else
{
RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle;
if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL
{
DataContract dataContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, null /*type*/);
SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle);
}
else
{
SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle));
}
}
}
internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
scopedKnownTypes.Pop();
}
else
{
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
}
}
internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
{
bool verifyKnownType = false;
Type declaredType = rootTypeDataContract.UnderlyingType;
if (rootTypeDataContract.TypeIsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
if (DataContractResolver != null)
{
WriteResolvedTypeInfo(xmlWriter, graphType, declaredType);
}
}
else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType);
}
protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool verifyKnownType = false;
#if !NET_NATIVE
DataContract dataContract;
if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#else
DataContract dataContract = DataContract.GetDataContractFromGeneratedAssembly(declaredType);
if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode))
dataContract = dataContract.GetValidContract(this.Mode);
else
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#endif
if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null)
{
if (objectType == null)
{
objectType = Type.GetTypeFromHandle(objectTypeHandle);
}
WriteResolvedTypeInfo(xmlWriter, objectType, declaredType);
}
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
// A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference
dataContract = GetDataContract(objectTypeHandle, objectType);
WriteClrTypeInfo(xmlWriter, dataContract);
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else
{
dataContract = GetDataContract(objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (!WriteClrTypeInfo(xmlWriter, dataContract))
{
DataContract declaredTypeContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, declaredType);
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
}
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType);
}
internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj)
{
if (!contract.IsReference || _isGetOnlyCollection)
{
return false;
}
bool isNew = true;
int objectId = SerializedObjects.GetId(obj, ref isNew);
_byValObjectsInScope.EnsureSetAsIsReference(obj);
if (isNew)
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName,
DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return false;
}
else
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return true;
}
}
protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
#if !NET_NATIVE
if (verifyKnownType)
{
if (!IsKnownType(dataContract, declaredType))
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
}
#endif
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
{
return false;
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#else
internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#endif
{
xmlWriter.WriteAnyType(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#endif
{
xmlWriter.WriteString(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteString(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#endif
{
xmlWriter.WriteBase64(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteBase64(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#endif
{
xmlWriter.WriteUri(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteUri(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#endif
{
xmlWriter.WriteQName(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns);
else
{
if (ns != null && ns.Value != null && ns.Value.Length > 0)
xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns);
else
xmlWriter.WriteStartElement(name, ns);
xmlWriter.WriteQName(value);
xmlWriter.WriteEndElement();
}
}
internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract)
{
writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace);
OnHandleReference(writer, obj, true /*canContainReferences*/);
}
internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return false;
if (canContainCyclicReference)
{
if (_byValObjectsInScope.Contains(obj))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType()))));
_byValObjectsInScope.Push(obj);
}
return false;
}
internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return;
if (canContainCyclicReference)
{
_byValObjectsInScope.Pop(obj);
}
}
#if USE_REFEMIT
public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#else
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#endif
{
CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
WriteNull(xmlWriter);
}
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns)
{
xmlWriter.WriteStartElement(name, ns);
WriteNull(xmlWriter, memberType, isMemberTypeSerializable);
xmlWriter.WriteEndElement();
}
#if USE_REFEMIT
public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#else
internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#endif
{
IncrementCollectionCount(xmlWriter, array.GetLength(0));
}
#if USE_REFEMIT
public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#else
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
#if USE_REFEMIT
public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#else
internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size)
{
IncrementItemCount(size);
WriteArraySize(xmlWriter, size);
}
internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
}
#if USE_REFEMIT
public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#else
internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#endif
{
if (obj == null || memberType == null)
return false;
return obj.GetType().TypeHandle.Equals(memberType.TypeHandle);
}
#if USE_REFEMIT
public static T GetDefaultValue<T>()
#else
internal static T GetDefaultValue<T>()
#endif
{
return default(T);
}
#if USE_REFEMIT
public static T GetNullableValue<T>(Nullable<T> value) where T : struct
#else
internal static T GetNullableValue<T>(Nullable<T> value) where T : struct
#endif
{
// value.Value will throw if hasValue is false
return value.Value;
}
#if USE_REFEMIT
public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#else
internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#endif
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName)));
}
#if USE_REFEMIT
public static bool GetHasValue<T>(Nullable<T> value) where T : struct
#else
internal static bool GetHasValue<T>(Nullable<T> value) where T : struct
#endif
{
return value.HasValue;
}
internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
if (_xmlSerializableWriter == null)
_xmlSerializableWriter = new XmlSerializableWriter();
WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter);
}
internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter());
}
private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter)
{
xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj);
IXmlSerializable xmlSerializable = obj as IXmlSerializable;
if (xmlSerializable != null)
xmlSerializable.WriteXml(xmlSerializableWriter);
xmlSerializableWriter.EndWrite();
}
protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
dataContract.WriteXmlValue(xmlWriter, obj, this);
}
protected virtual void WriteNull(XmlWriterDelegator xmlWriter)
{
XmlObjectSerializer.WriteNull(xmlWriter);
}
private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
{
XmlDictionaryString typeName, typeNamespace;
if (ResolveType(objectType, declaredType, out typeName, out typeNamespace))
{
WriteTypeInfo(writer, typeName, typeNamespace);
}
}
private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
if (typeName == null)
{
if (typeNamespace == null)
{
return false;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
}
if (typeNamespace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
return true;
}
protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
{
if (XmlObjectSerializer.IsContractDeclared(contract, declaredContract))
{
return false;
}
bool hasResolver = DataContractResolver != null;
if (hasResolver)
{
WriteResolvedTypeInfo(writer, contract.UnderlyingType, declaredContract.UnderlyingType);
}
else
{
WriteTypeInfo(writer, contract.Name, contract.Namespace);
}
return hasResolver;
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ISalesTaxRateOriginalData : ISchemaBaseOriginalData
{
string TaxType { get; }
string TaxRate { get; }
string Name { get; }
string rowguid { get; }
StateProvince StateProvince { get; }
}
public partial class SalesTaxRate : OGM<SalesTaxRate, SalesTaxRate.SalesTaxRateData, System.String>, ISchemaBase, INeo4jBase, ISalesTaxRateOriginalData
{
#region Initialize
static SalesTaxRate()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, SalesTaxRate> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.SalesTaxRateAlias, IWhereQuery> query)
{
q.SalesTaxRateAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.SalesTaxRate.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"SalesTaxRate => TaxType : {this.TaxType}, TaxRate : {this.TaxRate}, Name : {this.Name}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new SalesTaxRateData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.TaxType == null)
throw new PersistenceException(string.Format("Cannot save SalesTaxRate with key '{0}' because the TaxType cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.TaxRate == null)
throw new PersistenceException(string.Format("Cannot save SalesTaxRate with key '{0}' because the TaxRate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.Name == null)
throw new PersistenceException(string.Format("Cannot save SalesTaxRate with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save SalesTaxRate with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save SalesTaxRate with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class SalesTaxRateData : Data<System.String>
{
public SalesTaxRateData()
{
}
public SalesTaxRateData(SalesTaxRateData data)
{
TaxType = data.TaxType;
TaxRate = data.TaxRate;
Name = data.Name;
rowguid = data.rowguid;
StateProvince = data.StateProvince;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "SalesTaxRate";
StateProvince = new EntityCollection<StateProvince>(Wrapper, Members.StateProvince);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("TaxType", TaxType);
dictionary.Add("TaxRate", TaxRate);
dictionary.Add("Name", Name);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("TaxType", out value))
TaxType = (string)value;
if (properties.TryGetValue("TaxRate", out value))
TaxRate = (string)value;
if (properties.TryGetValue("Name", out value))
Name = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ISalesTaxRate
public string TaxType { get; set; }
public string TaxRate { get; set; }
public string Name { get; set; }
public string rowguid { get; set; }
public EntityCollection<StateProvince> StateProvince { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ISalesTaxRate
public string TaxType { get { LazyGet(); return InnerData.TaxType; } set { if (LazySet(Members.TaxType, InnerData.TaxType, value)) InnerData.TaxType = value; } }
public string TaxRate { get { LazyGet(); return InnerData.TaxRate; } set { if (LazySet(Members.TaxRate, InnerData.TaxRate, value)) InnerData.TaxRate = value; } }
public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
public StateProvince StateProvince
{
get { return ((ILookupHelper<StateProvince>)InnerData.StateProvince).GetItem(null); }
set
{
if (LazySet(Members.StateProvince, ((ILookupHelper<StateProvince>)InnerData.StateProvince).GetItem(null), value))
((ILookupHelper<StateProvince>)InnerData.StateProvince).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static SalesTaxRateMembers members = null;
public static SalesTaxRateMembers Members
{
get
{
if (members == null)
{
lock (typeof(SalesTaxRate))
{
if (members == null)
members = new SalesTaxRateMembers();
}
}
return members;
}
}
public class SalesTaxRateMembers
{
internal SalesTaxRateMembers() { }
#region Members for interface ISalesTaxRate
public Property TaxType { get; } = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"].Properties["TaxType"];
public Property TaxRate { get; } = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"].Properties["TaxRate"];
public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"].Properties["Name"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"].Properties["rowguid"];
public Property StateProvince { get; } = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"].Properties["StateProvince"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static SalesTaxRateFullTextMembers fullTextMembers = null;
public static SalesTaxRateFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(SalesTaxRate))
{
if (fullTextMembers == null)
fullTextMembers = new SalesTaxRateFullTextMembers();
}
}
return fullTextMembers;
}
}
public class SalesTaxRateFullTextMembers
{
internal SalesTaxRateFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(SalesTaxRate))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["SalesTaxRate"];
}
}
return entity;
}
private static SalesTaxRateEvents events = null;
public static SalesTaxRateEvents Events
{
get
{
if (events == null)
{
lock (typeof(SalesTaxRate))
{
if (events == null)
events = new SalesTaxRateEvents();
}
}
return events;
}
}
public class SalesTaxRateEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<SalesTaxRate, EntityEventArgs> onNew;
public event EventHandler<SalesTaxRate, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesTaxRate, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<SalesTaxRate, EntityEventArgs> onDelete;
public event EventHandler<SalesTaxRate, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesTaxRate, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<SalesTaxRate, EntityEventArgs> onSave;
public event EventHandler<SalesTaxRate, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesTaxRate, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnTaxType
private static bool onTaxTypeIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onTaxType;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnTaxType
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onTaxTypeIsRegistered)
{
Members.TaxType.Events.OnChange -= onTaxTypeProxy;
Members.TaxType.Events.OnChange += onTaxTypeProxy;
onTaxTypeIsRegistered = true;
}
onTaxType += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onTaxType -= value;
if (onTaxType == null && onTaxTypeIsRegistered)
{
Members.TaxType.Events.OnChange -= onTaxTypeProxy;
onTaxTypeIsRegistered = false;
}
}
}
}
private static void onTaxTypeProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onTaxType;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnTaxRate
private static bool onTaxRateIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onTaxRate;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnTaxRate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onTaxRateIsRegistered)
{
Members.TaxRate.Events.OnChange -= onTaxRateProxy;
Members.TaxRate.Events.OnChange += onTaxRateProxy;
onTaxRateIsRegistered = true;
}
onTaxRate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onTaxRate -= value;
if (onTaxRate == null && onTaxRateIsRegistered)
{
Members.TaxRate.Events.OnChange -= onTaxRateProxy;
onTaxRateIsRegistered = false;
}
}
}
}
private static void onTaxRateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onTaxRate;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnName
private static bool onNameIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onName;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnName
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
Members.Name.Events.OnChange += onNameProxy;
onNameIsRegistered = true;
}
onName += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onName -= value;
if (onName == null && onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
onNameIsRegistered = false;
}
}
}
}
private static void onNameProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onName;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onrowguid;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnStateProvince
private static bool onStateProvinceIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onStateProvince;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnStateProvince
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStateProvinceIsRegistered)
{
Members.StateProvince.Events.OnChange -= onStateProvinceProxy;
Members.StateProvince.Events.OnChange += onStateProvinceProxy;
onStateProvinceIsRegistered = true;
}
onStateProvince += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStateProvince -= value;
if (onStateProvince == null && onStateProvinceIsRegistered)
{
Members.StateProvince.Events.OnChange -= onStateProvinceProxy;
onStateProvinceIsRegistered = false;
}
}
}
}
private static void onStateProvinceProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onStateProvince;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onModifiedDate;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<SalesTaxRate, PropertyEventArgs> onUid;
public static event EventHandler<SalesTaxRate, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesTaxRate, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((SalesTaxRate)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ISalesTaxRateOriginalData
public ISalesTaxRateOriginalData OriginalVersion { get { return this; } }
#region Members for interface ISalesTaxRate
string ISalesTaxRateOriginalData.TaxType { get { return OriginalData.TaxType; } }
string ISalesTaxRateOriginalData.TaxRate { get { return OriginalData.TaxRate; } }
string ISalesTaxRateOriginalData.Name { get { return OriginalData.Name; } }
string ISalesTaxRateOriginalData.rowguid { get { return OriginalData.rowguid; } }
StateProvince ISalesTaxRateOriginalData.StateProvince { get { return ((ILookupHelper<StateProvince>)OriginalData.StateProvince).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.InvokeDelegateWithConditionalAccess
{
public partial class InvokeDelegateWithConditionalAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new InvokeDelegateWithConditionalAccessAnalyzer(),
new InvokeDelegateWithConditionalAccessCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task Test1()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestOnIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestOnInvoke()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v != null)
{
[||]v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
[WorkItem(13226, "https://github.com/dotnet/roslyn/issues/13226")]
public async Task TestMissingBeforeCSharp6()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
}
}", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInvertedIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (null != v)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestIfWithNoBraces()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (null != v)
v();
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestWithComplexExpression()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
bool b = true;
[||]var v = b ? a : null;
if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
bool b = true;
(b ? a : null)?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingWithElseClause()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
else {}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnDeclarationWithMultipleVariables()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a, x = a;
if (v != null)
{
v();
}
}
}");
}
/// <remarks>
/// With multiple variables in the same declaration, the fix _is not_ offered on the declaration
/// itself, but _is_ offered on the invocation pattern.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocationWhereOfferedWithMultipleVariables()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a, x = a;
[||]if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a, x = a;
v?.Invoke();
}
}");
}
/// <remarks>
/// If we have a variable declaration and if it is read/written outside the delegate
/// invocation pattern, the fix is not offered on the declaration.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnDeclarationIfUsedOutside()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
v = null;
}
}");
}
/// <remarks>
/// If we have a variable declaration and if it is read/written outside the delegate
/// invocation pattern, the fix is not offered on the declaration but is offered on
/// the invocation pattern itself.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocationWhereOfferedIfUsedOutside()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]if (v != null)
{
v();
}
v = null;
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a;
v?.Invoke();
v = null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestSimpleForm1()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
[||]if (this.E != null)
{
this.E(this, EventArgs.Empty);
}
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
this.E?.Invoke(this, EventArgs.Empty);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestSimpleForm2()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (this.E != null)
{
[||]this.E(this, EventArgs.Empty);
}
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
this.E?.Invoke(this, EventArgs.Empty);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInElseClause1()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else [||]if (this.E != null)
{
this.E(this, EventArgs.Empty);
}
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else
{
this.E?.Invoke(this, EventArgs.Empty);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInElseClause2()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else [||]if (this.E != null)
this.E(this, EventArgs.Empty);
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else this.E?.Invoke(this, EventArgs.Empty);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestTrivia1()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
// Comment
[||]var v = a;
if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
// Comment
a?.Invoke();
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestTrivia2()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
// Comment
[||]if (a != null)
{
a();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
// Comment
a?.Invoke();
}
}", compareTokens: false);
}
/// <remarks>
/// tests locations where the fix is offered.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestFixOfferedOnIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
/// <remarks>
/// tests locations where the fix is offered.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestFixOfferedInsideIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v != null)
{
[||]v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation2()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation3()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnNonNullCheckExpressions()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v == a)
{
[||]v();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnNonNullCheckExpressions2()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v == null)
{
[||]v();
}
}
}");
}
/// <remarks>
/// if local declaration is not immediately preceding the invocation pattern,
/// the fix is not offered on the declaration.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocalNotImmediatelyPrecedingNullCheckAndInvokePattern()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
int x;
if (v != null)
{
v();
}
}
}");
}
/// <remarks>
/// if local declaration is not immediately preceding the invocation pattern,
/// the fix is not offered on the declaration but is offered on the invocation pattern itself.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocalDNotImmediatelyPrecedingNullCheckAndInvokePattern2()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
int x;
[||]if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a;
int x;
v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnFunc()
{
await TestMissingAsync(
@"class C
{
System.Func<int> a;
int Foo()
{
var v = a;
[||]if (v != null)
{
return v();
}
}
}");
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Wrapper for NCrypt's implementation of elliptic curve DSA
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class ECDsaCng : ECDsa {
private static KeySizes[] s_legalKeySizes = new KeySizes[] { new KeySizes(256, 384, 128), new KeySizes(521, 521, 0) };
private CngKey m_key;
private CngAlgorithm m_hashAlgorithm = CngAlgorithm.Sha256;
//
// Constructors
//
public ECDsaCng() : this(521) {
Contract.Ensures(LegalKeySizesValue != null);
}
public ECDsaCng(int keySize) {
Contract.Ensures(LegalKeySizesValue != null);
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
LegalKeySizesValue = s_legalKeySizes;
KeySize = keySize;
}
[SecuritySafeCritical]
public ECDsaCng(CngKey key) {
Contract.Ensures(LegalKeySizesValue != null);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
if (key == null) {
throw new ArgumentNullException("key");
}
if (key.AlgorithmGroup != CngAlgorithmGroup.ECDsa) {
throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDsaRequiresECDsaKey), "key");
}
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
LegalKeySizesValue = s_legalKeySizes;
// Make a copy of the key so that we continue to work if it gets disposed before this algorithm
//
// This requires an assert for UnmanagedCode since we'll need to access the raw handles of the key
// and the handle constructor of CngKey. The assert is safe since ECDsaCng will never expose the
// key handles to calling code (without first demanding UnmanagedCode via the Handle property of
// CngKey).
//
// We also need to dispose of the key handle since CngKey.Handle returns a duplicate
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
using (SafeNCryptKeyHandle keyHandle = key.Handle) {
Key = CngKey.Open(keyHandle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
}
CodeAccessPermission.RevertAssert();
KeySize = m_key.KeySize;
}
/// <summary>
/// Hash algorithm to use when generating a signature over arbitrary data
/// </summary>
public CngAlgorithm HashAlgorithm {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
return m_hashAlgorithm;
}
set {
Contract.Ensures(m_hashAlgorithm != null);
if (value == null) {
throw new ArgumentNullException("value");
}
m_hashAlgorithm = value;
}
}
/// <summary>
/// Key to use for signing
/// </summary>
public CngKey Key {
get {
Contract.Ensures(Contract.Result<CngKey>() != null);
Contract.Ensures(Contract.Result<CngKey>().AlgorithmGroup == CngAlgorithmGroup.ECDsa);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
// If the size of the key no longer matches our stored value, then we need to replace it with
// a new key of the correct size.
if (m_key != null && m_key.KeySize != KeySize) {
m_key.Dispose();
m_key = null;
}
if (m_key == null) {
// Map the current key size to a CNG algorithm name
CngAlgorithm algorithm = null;
switch (KeySize) {
case 256:
algorithm = CngAlgorithm.ECDsaP256;
break;
case 384:
algorithm = CngAlgorithm.ECDsaP384;
break;
case 521:
algorithm = CngAlgorithm.ECDsaP521;
break;
default:
Debug.Assert(false, "Illegal key size set");
break;
}
m_key = CngKey.Create(algorithm);
}
return m_key;
}
private set {
Contract.Requires(value != null);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
if (value.AlgorithmGroup != CngAlgorithmGroup.ECDsa) {
throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDsaRequiresECDsaKey));
}
if (m_key != null) {
m_key.Dispose();
}
//
// We do not duplicate the handle because the only time the user has access to the key itself
// to dispose underneath us is when they construct via the CngKey constructor, which does a
// copy. Otherwise all key lifetimes are controlled directly by the ECDsaCng class.
//
m_key = value;
KeySize = m_key.KeySize;
}
}
/// <summary>
/// Clean up the algorithm
/// </summary>
protected override void Dispose(bool disposing) {
try {
if (m_key != null) {
m_key.Dispose();
}
}
finally {
base.Dispose(disposing);
}
}
//
// XML Import
//
// #ECCXMLFormat
//
// There is currently not a standard XML format for ECC keys, so we will not implement the default
// To/FromXmlString so that we're not tied to one format when a standard one does exist. Instead we'll
// use an overload which allows the user to specify the format they'd like to serialize into.
//
// See code:System.Security.Cryptography.Rfc4050KeyFormatter#RFC4050ECKeyFormat for information about
// the currently supported format.
//
public override void FromXmlString(string xmlString) {
throw new NotImplementedException(SR.GetString(SR.Cryptography_ECXmlSerializationFormatRequired));
}
public void FromXmlString(string xml, ECKeyXmlFormat format) {
if (xml == null) {
throw new ArgumentNullException("xml");
}
if (format != ECKeyXmlFormat.Rfc4050) {
throw new ArgumentOutOfRangeException("format");
}
Key = Rfc4050KeyFormatter.FromXml(xml);
}
//
// Signature generation
//
public byte[] SignData(byte[] data) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
return SignData(data, 0, data.Length);
}
[SecuritySafeCritical]
public byte[] SignData(byte[] data, int offset, int count) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashCore(data, offset, count);
byte[] hashValue = hashAlgorithm.HashFinal();
return SignHash(hashValue);
}
}
[SecuritySafeCritical]
public byte[] SignData(Stream data) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashStream(data);
byte[] hashValue = hashAlgorithm.HashFinal();
return SignHash(hashValue);
}
}
[SecuritySafeCritical]
public override byte[] SignHash(byte[] hash) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
// Make sure we're allowed to sign using this key
KeyContainerPermission permission = Key.BuildKeyContainerPermission(KeyContainerPermissionFlags.Sign);
if (permission != null) {
permission.Demand();
}
// Now that know we have permission to use this key for signing, pull the key value out, which
// will require unmanaged code permission
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
// This looks odd, but the key handle is actually a duplicate so we need to dispose it
using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
CodeAccessPermission.RevertAssert();
return NCryptNative.SignHash(keyHandle, hash);
}
}
//
// XML Export
//
// See code:System.Security.Cryptography.ECDsaCng#ECCXMLFormat and
// code:System.Security.Cryptography.Rfc4050KeyFormatter#RFC4050ECKeyFormat for information about
// XML serialization of elliptic curve keys
//
public override string ToXmlString(bool includePrivateParameters) {
throw new NotImplementedException(SR.GetString(SR.Cryptography_ECXmlSerializationFormatRequired));
}
public string ToXmlString(ECKeyXmlFormat format) {
Contract.Ensures(Contract.Result<string>() != null);
if (format != ECKeyXmlFormat.Rfc4050) {
throw new ArgumentOutOfRangeException("format");
}
return Rfc4050KeyFormatter.ToXml(Key);
}
//
// Signature verification
//
public bool VerifyData(byte[] data, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
return VerifyData(data, 0, data.Length, signature);
}
[SecuritySafeCritical]
public bool VerifyData(byte[] data, int offset, int count, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashCore(data, offset, count);
byte[] hashValue = hashAlgorithm.HashFinal();
return VerifyHash(hashValue, signature);
}
}
[SecuritySafeCritical]
public bool VerifyData(Stream data, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashStream(data);
byte[] hashValue = hashAlgorithm.HashFinal();
return VerifyHash(hashValue, signature);
}
}
[SecuritySafeCritical]
public override bool VerifyHash(byte[] hash, byte[] signature) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
// We need to get the raw key handle to verify the signature. Asserting here is safe since verifiation
// is not a protected operation, and we do not expose the handle to the user code.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
// This looks odd, but Key.Handle is really a duplicate so we need to dispose it
using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
CodeAccessPermission.RevertAssert();
return NCryptNative.VerifySignature(keyHandle, hash, signature);
}
}
}
}
| |
// 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.
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Text
{
public static partial class PrimitiveParser
{
public static partial class InvariantUtf8
{
public unsafe static bool TryParseBoolean(byte* text, int length, out bool value)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public unsafe static bool TryParseBoolean(byte* text, int length, out bool value, out int bytesConsumed)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
bytesConsumed = 4;
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
bytesConsumed = 5;
value = false;
return true;
}
}
}
bytesConsumed = 0;
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value, out int bytesConsumed)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
bytesConsumed = 4;
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
bytesConsumed = 5;
value = false;
return true;
}
}
}
bytesConsumed = 0;
value = default;
return false;
}
}
public static partial class InvariantUtf16
{
public unsafe static bool TryParseBoolean(char* text, int length, out bool value)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public unsafe static bool TryParseBoolean(char* text, int length, out bool value, out int charsConsumed)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
charsConsumed = 4;
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
charsConsumed = 5;
value = false;
return true;
}
}
}
charsConsumed = 0;
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value, out int charsConsumed)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
charsConsumed = 4;
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
charsConsumed = 5;
value = false;
return true;
}
}
}
charsConsumed = 0;
value = default;
return false;
}
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: UserList
// ObjectType: UserList
// CSLAType: ReadOnlyCollection
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
namespace DocStore.Business.Admin
{
/// <summary>
/// Collection of user's basic information (read only list).<br/>
/// This is a generated <see cref="UserList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="UserInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class UserList : ReadOnlyBindingListBase<UserList, UserInfo>
#else
public partial class UserList : ReadOnlyListBase<UserList, UserInfo>
#endif
{
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="UserInfo"/> item is in the collection.
/// </summary>
/// <param name="userID">The UserID of the item to search for.</param>
/// <returns><c>true</c> if the UserInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int userID)
{
foreach (var userInfo in this)
{
if (userInfo.UserID == userID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="UserInfo"/> item of the <see cref="UserList"/> collection, based on a given UserID.
/// </summary>
/// <param name="userID">The UserID.</param>
/// <returns>A <see cref="UserInfo"/> object.</returns>
public UserInfo FindUserInfoByUserID(int userID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].UserID.Equals(userID))
{
return this[i];
}
}
return null;
}
#endregion
#region Private Fields
private static UserList _list;
#endregion
#region Cache Management Methods
/// <summary>
/// Clears the in-memory UserList cache so it is reloaded on the next request.
/// </summary>
public static void InvalidateCache()
{
_list = null;
}
/// <summary>
/// Used by async loaders to load the cache.
/// </summary>
/// <param name="list">The list to cache.</param>
internal static void SetCache(UserList list)
{
_list = list;
}
internal static bool IsCached
{
get { return _list != null; }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="UserList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="UserList"/> collection.</returns>
public static UserList GetUserList()
{
if (_list == null)
_list = DataPortal.Fetch<UserList>();
return _list;
}
/// <summary>
/// Factory method. Loads a <see cref="UserList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the UserList to fetch.</param>
/// <param name="login">The Login parameter of the UserList to fetch.</param>
/// <param name="email">The Email parameter of the UserList to fetch.</param>
/// <param name="isActive">The IsActive parameter of the UserList to fetch.</param>
/// <returns>A reference to the fetched <see cref="UserList"/> collection.</returns>
public static UserList GetUserList(string name, string login, string email, bool? isActive)
{
return DataPortal.Fetch<UserList>(new FilteredCriteria(name, login, email, isActive));
}
/// <summary>
/// Factory method. Loads a <see cref="UserList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the UserList to fetch.</param>
/// <returns>A reference to the fetched <see cref="UserList"/> collection.</returns>
public static UserList GetUserList(string name)
{
return DataPortal.Fetch<UserList>(new CriteriaInactive(name));
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="UserList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetUserList(EventHandler<DataPortalResult<UserList>> callback)
{
if (_list == null)
DataPortal.BeginFetch<UserList>((o, e) =>
{
_list = e.Object;
callback(o, e);
});
else
callback(null, new DataPortalResult<UserList>(_list, null, null));
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="UserList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the UserList to fetch.</param>
/// <param name="login">The Login parameter of the UserList to fetch.</param>
/// <param name="email">The Email parameter of the UserList to fetch.</param>
/// <param name="isActive">The IsActive parameter of the UserList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetUserList(string name, string login, string email, bool? isActive, EventHandler<DataPortalResult<UserList>> callback)
{
DataPortal.BeginFetch<UserList>(new FilteredCriteria(name, login, email, isActive), callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="UserList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the UserList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetUserList(string name, EventHandler<DataPortalResult<UserList>> callback)
{
DataPortal.BeginFetch<UserList>(new CriteriaInactive(name), callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="UserList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public UserList()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Nested Criteria
/// <summary>
/// FilteredCriteria criteria.
/// </summary>
[Serializable]
protected class FilteredCriteria : CriteriaBase<FilteredCriteria>
{
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name);
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return ReadProperty(NameProperty); }
set { LoadProperty(NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Login"/> property.
/// </summary>
public static readonly PropertyInfo<string> LoginProperty = RegisterProperty<string>(p => p.Login);
/// <summary>
/// Gets or sets the Login.
/// </summary>
/// <value>The Login.</value>
public string Login
{
get { return ReadProperty(LoginProperty); }
set { LoadProperty(LoginProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Email"/> property.
/// </summary>
public static readonly PropertyInfo<string> EmailProperty = RegisterProperty<string>(p => p.Email);
/// <summary>
/// Gets or sets the Email.
/// </summary>
/// <value>The Email.</value>
public string Email
{
get { return ReadProperty(EmailProperty); }
set { LoadProperty(EmailProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="IsActive"/> property.
/// </summary>
public static readonly PropertyInfo<bool?> IsActiveProperty = RegisterProperty<bool?>(p => p.IsActive);
/// <summary>
/// Gets or sets the active or deleted state.
/// </summary>
/// <value><c>true</c> if Is Active; <c>false</c> if not Is Active; otherwise, <c>null</c>.</value>
public bool? IsActive
{
get { return ReadProperty(IsActiveProperty); }
set { LoadProperty(IsActiveProperty, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="FilteredCriteria"/> class.
/// </summary>
/// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public FilteredCriteria()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FilteredCriteria"/> class.
/// </summary>
/// <param name="name">The Name.</param>
/// <param name="login">The Login.</param>
/// <param name="email">The Email.</param>
/// <param name="isActive">The IsActive.</param>
public FilteredCriteria(string name, string login, string email, bool? isActive)
{
Name = name;
Login = login;
Email = email;
IsActive = isActive;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is FilteredCriteria)
{
var c = (FilteredCriteria) obj;
if (!Name.Equals(c.Name))
return false;
if (!Login.Equals(c.Login))
return false;
if (!Email.Equals(c.Email))
return false;
if (!IsActive.Equals(c.IsActive))
return false;
return true;
}
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return string.Concat("FilteredCriteria", Name.ToString(), Login.ToString(), Email.ToString(), IsActive.ToString()).GetHashCode();
}
}
/// <summary>
/// CriteriaInactive criteria.
/// </summary>
[Serializable]
protected class CriteriaInactive : CriteriaBase<CriteriaInactive>
{
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name);
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return ReadProperty(NameProperty); }
set { LoadProperty(NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="IsActive"/> property.
/// </summary>
public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive);
/// <summary>
/// Gets the active or deleted state.
/// </summary>
/// <value><c>true</c> if Is Active; otherwise, <c>false</c>.</value>
public bool IsActive
{
get { return ReadProperty(IsActiveProperty); }
private set { LoadProperty(IsActiveProperty, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CriteriaInactive"/> class.
/// </summary>
/// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CriteriaInactive()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CriteriaInactive"/> class.
/// </summary>
/// <param name="name">The Name.</param>
public CriteriaInactive(string name)
{
Name = name;
IsActive = false;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is CriteriaInactive)
{
var c = (CriteriaInactive) obj;
if (!Name.Equals(c.Name))
return false;
if (!IsActive.Equals(c.IsActive))
return false;
return true;
}
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return string.Concat("CriteriaInactive", Name.ToString(), IsActive.ToString()).GetHashCode();
}
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (UserList), new IsInRole(AuthorizationActions.GetObject, "User"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can retrieve UserList's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(UserList));
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="UserList"/> collection from the database or from the cache.
/// </summary>
protected void DataPortal_Fetch()
{
if (IsCached)
{
LoadCachedList();
return;
}
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetUserList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
_list = this;
}
private void LoadCachedList()
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AddRange(_list);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
/// <summary>
/// Loads a <see cref="UserList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
protected void DataPortal_Fetch(FilteredCriteria crit)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetUserList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", crit.Name == null ? (object)DBNull.Value : crit.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Login", crit.Login == null ? (object)DBNull.Value : crit.Login).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Email", crit.Email == null ? (object)DBNull.Value : crit.Email).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", crit.IsActive == null ? (object)DBNull.Value : crit.IsActive.Value).DbType = DbType.Boolean;
var args = new DataPortalHookArgs(cmd, crit);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
/// <summary>
/// Loads a <see cref="UserList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
protected void DataPortal_Fetch(CriteriaInactive crit)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetUserList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", crit.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", crit.IsActive).DbType = DbType.Boolean;
var args = new DataPortalHookArgs(cmd, crit);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="UserList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(UserInfo.GetUserInfo(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <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);
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using NPOI.Util;
public class MutableFPNumber
{
// TODO - what about values between (10<sup>14</sup>-0.5) and (10<sup>14</sup>-0.05) ?
/**
* The minimum value in 'Base-10 normalised form'.<br/>
* When {@link #_binaryExponent} == 46 this is the the minimum {@link #_frac} value
* (10<sup>14</sup>-0.05) * 2^17
* <br/>
* Values between (10<sup>14</sup>-0.05) and 10<sup>14</sup> will be represented as '1'
* followed by 14 zeros.
* Values less than (10<sup>14</sup>-0.05) will get Shifted by one more power of 10
*
* This frac value rounds to '1' followed by fourteen zeros with an incremented decimal exponent
*/
//private static BigInteger BI_MIN_BASE = new BigInteger("0B5E620F47FFFE666", 16);
private static readonly BigInteger BI_MIN_BASE = new BigInteger(new int[] { -1243209484, 2147477094 }, 1);
/**
* For 'Base-10 normalised form'<br/>
* The maximum {@link #_frac} value when {@link #_binaryExponent} == 49
* (10^15-0.5) * 2^14
*/
//private static BigInteger BI_MAX_BASE = new BigInteger("0E35FA9319FFFE000", 16);
private static readonly BigInteger BI_MAX_BASE = new BigInteger(new int[] { -480270031, -1610620928 }, 1);
/**
* Width of a long
*/
private const int C_64 = 64;
/**
* Minimum precision after discarding whole 32-bit words from the significand
*/
private const int MIN_PRECISION = 72;
private BigInteger _significand;
private int _binaryExponent;
public MutableFPNumber(BigInteger frac, int binaryExponent)
{
_significand = frac;
_binaryExponent = binaryExponent;
}
public MutableFPNumber Copy()
{
return new MutableFPNumber(_significand, _binaryExponent);
}
public void Normalise64bit()
{
int oldBitLen = _significand.BitLength();
int sc = oldBitLen - C_64;
if (sc == 0)
{
return;
}
if (sc < 0)
{
throw new InvalidOperationException("Not enough precision");
}
_binaryExponent += sc;
if (sc > 32)
{
int highShift = (sc - 1) & 0xFFFFE0;
_significand = _significand>>(highShift);
sc -= highShift;
oldBitLen -= highShift;
}
if (sc < 1)
{
throw new InvalidOperationException();
}
_significand = Rounder.Round(_significand, sc);
if (_significand.BitLength() > oldBitLen)
{
sc++;
_binaryExponent++;
}
_significand = _significand>>(sc);
}
public int Get64BitNormalisedExponent()
{
//return _binaryExponent + _significand.BitCount() - C_64;
return _binaryExponent + _significand.BitLength() - C_64;
}
public bool IsBelowMaxRep()
{
int sc = _significand.BitLength() - C_64;
//return _significand<(BI_MAX_BASE<<(sc));
return _significand.CompareTo(BI_MAX_BASE.ShiftLeft(sc)) < 0;
}
public bool IsAboveMinRep()
{
int sc = _significand.BitLength() - C_64;
return _significand.CompareTo(BI_MIN_BASE.ShiftLeft(sc)) > 0;
//return _significand>(BI_MIN_BASE<<(sc));
}
public NormalisedDecimal CreateNormalisedDecimal(int pow10)
{
// missingUnderBits is (0..3)
int missingUnderBits = _binaryExponent - 39;
int fracPart = (_significand.IntValue() << missingUnderBits) & 0xFFFF80;
long wholePart = (_significand>>(C_64 - _binaryExponent - 1)).LongValue();
return new NormalisedDecimal(wholePart, fracPart, pow10);
}
public void multiplyByPowerOfTen(int pow10)
{
TenPower tp = TenPower.GetInstance(Math.Abs(pow10));
if (pow10 < 0)
{
mulShift(tp._divisor, tp._divisorShift);
}
else
{
mulShift(tp._multiplicand, tp._multiplierShift);
}
}
private void mulShift(BigInteger multiplicand, int multiplierShift)
{
_significand = _significand*multiplicand;
_binaryExponent += multiplierShift;
// check for too much precision
int sc = (_significand.BitLength() - MIN_PRECISION) & unchecked((int)0xFFFFFFE0);
// mask Makes multiples of 32 which optimises BigInt32.ShiftRight
if (sc > 0)
{
// no need to round because we have at least 8 bits of extra precision
_significand = _significand>>(sc);
_binaryExponent += sc;
}
}
private class Rounder
{
private static BigInteger[] HALF_BITS;
static Rounder()
{
BigInteger[] bis = new BigInteger[33];
long acc = 1;
for (int i = 1; i < bis.Length; i++)
{
bis[i] = new BigInteger(acc);
acc <<= 1;
}
HALF_BITS = bis;
}
/**
* @param nBits number of bits to shift right
*/
public static BigInteger Round(BigInteger bi, int nBits)
{
if (nBits < 1)
{
return bi;
}
return bi+(HALF_BITS[nBits]);
}
}
/**
* Holds values for quick multiplication and division by 10
*/
private class TenPower
{
private static readonly BigInteger FIVE = new BigInteger(5L);// new BigInteger("5",10);
private static TenPower[] _cache = new TenPower[350];
public BigInteger _multiplicand;
public BigInteger _divisor;
public int _divisorShift;
public int _multiplierShift;
private TenPower(int index)
{
//BigInteger fivePowIndex = FIVE.ModPow(new BigInteger(index),FIVE);
BigInteger fivePowIndex = FIVE.Pow(index);
int bitsDueToFiveFactors = fivePowIndex.BitLength();
int px = 80 + bitsDueToFiveFactors;
BigInteger fx = (BigInteger.One << px) / (fivePowIndex);
int adj = fx.BitLength() - 80;
_divisor = fx>>(adj);
bitsDueToFiveFactors -= adj;
_divisorShift = -(bitsDueToFiveFactors + index + 80);
int sc = fivePowIndex.BitLength() - 68;
if (sc > 0)
{
_multiplierShift = index + sc;
_multiplicand = fivePowIndex>>(sc);
}
else
{
_multiplierShift = index;
_multiplicand = fivePowIndex;
}
}
public static TenPower GetInstance(int index)
{
TenPower result = _cache[index];
if (result == null)
{
result = new TenPower(index);
_cache[index] = result;
}
return result;
}
}
public ExpandedDouble CreateExpandedDouble()
{
return new ExpandedDouble(_significand, _binaryExponent);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DbCommand.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
public abstract class DbCommand : Component, IDbCommand { // V1.2.3300
protected DbCommand() : base() {
}
[
DefaultValue(""),
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandText),
]
abstract public string CommandText {
get;
set;
}
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandTimeout),
]
abstract public int CommandTimeout {
get;
set;
}
[
DefaultValue(System.Data.CommandType.Text),
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandType),
]
abstract public CommandType CommandType {
get;
set;
}
[
Browsable(false),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_Connection),
]
public DbConnection Connection {
get {
return DbConnection;
}
set {
DbConnection = value;
}
}
IDbConnection IDbCommand.Connection {
get {
return DbConnection;
}
set {
DbConnection = (DbConnection)value;
}
}
abstract protected DbConnection DbConnection { // V1.2.3300
get;
set;
}
abstract protected DbParameterCollection DbParameterCollection { // V1.2.3300
get;
}
abstract protected DbTransaction DbTransaction { // V1.2.3300
get;
set;
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsableAttribute(EditorBrowsableState.Never),
]
public abstract bool DesignTimeVisible {
get;
set;
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_Parameters),
]
public DbParameterCollection Parameters {
get {
return DbParameterCollection;
}
}
IDataParameterCollection IDbCommand.Parameters {
get {
return (DbParameterCollection)DbParameterCollection;
}
}
[
Browsable(false),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(Res.DbCommand_Transaction),
]
public DbTransaction Transaction {
get {
return DbTransaction;
}
set {
DbTransaction = value;
}
}
IDbTransaction IDbCommand.Transaction {
get {
return DbTransaction;
}
set {
DbTransaction = (DbTransaction)value;
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both),
ResCategoryAttribute(Res.DataCategory_Update),
ResDescriptionAttribute(Res.DbCommand_UpdatedRowSource),
]
abstract public UpdateRowSource UpdatedRowSource {
get;
set;
}
internal void CancelIgnoreFailure() {
// This method is used to route CancellationTokens to the Cancel method.
// Cancellation is a suggestion, and exceptions should be ignored
// rather than allowed to be unhandled, as there is no way to route
// them to the caller. It would be expected that the error will be
// observed anyway from the regular method. An example is cancelling
// an operation on a closed connection.
try
{
Cancel();
} catch(Exception) {
}
}
abstract public void Cancel();
public DbParameter CreateParameter(){ // V1.2.3300
return CreateDbParameter();
}
IDbDataParameter IDbCommand.CreateParameter() { // V1.2.3300
return CreateDbParameter();
}
abstract protected DbParameter CreateDbParameter();
abstract protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior);
abstract public int ExecuteNonQuery();
public DbDataReader ExecuteReader() {
return (DbDataReader)ExecuteDbDataReader(CommandBehavior.Default);
}
IDataReader IDbCommand.ExecuteReader() {
return (DbDataReader)ExecuteDbDataReader(CommandBehavior.Default);
}
public DbDataReader ExecuteReader(CommandBehavior behavior){
return (DbDataReader)ExecuteDbDataReader(behavior);
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) {
return (DbDataReader)ExecuteDbDataReader(behavior);
}
public Task<int> ExecuteNonQueryAsync() {
return ExecuteNonQueryAsync(CancellationToken.None);
}
public virtual Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return ADP.CreatedTaskWithCancellation<int>();
}
else {
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled) {
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try {
return Task.FromResult<int>(ExecuteNonQuery());
}
catch (Exception e) {
registration.Dispose();
return ADP.CreatedTaskWithException<int>(e);
}
}
}
public Task<DbDataReader> ExecuteReaderAsync() {
return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) {
return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior) {
return ExecuteReaderAsync(behavior, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
return ExecuteDbDataReaderAsync(behavior, cancellationToken);
}
protected virtual Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return ADP.CreatedTaskWithCancellation<DbDataReader>();
}
else {
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled) {
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try {
return Task.FromResult<DbDataReader>(ExecuteReader(behavior));
}
catch (Exception e) {
registration.Dispose();
return ADP.CreatedTaskWithException<DbDataReader>(e);
}
}
}
public Task<object> ExecuteScalarAsync() {
return ExecuteScalarAsync(CancellationToken.None);
}
public virtual Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return ADP.CreatedTaskWithCancellation<object>();
}
else {
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled) {
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try {
return Task.FromResult<object>(ExecuteScalar());
}
catch (Exception e) {
registration.Dispose();
return ADP.CreatedTaskWithException<object>(e);
}
}
}
abstract public object ExecuteScalar();
abstract public void Prepare();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// <see cref="IApplicationBuilder"/> extension methods for the <see cref="HealthCheckMiddleware"/>.
/// </summary>
public static class HealthCheckApplicationBuilderExtensions
{
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests. If <paramref name="path"/> is set to a non-empty
/// value, the health check middleware will process requests with a URL that matches the provided value
/// of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/') character.
/// </para>
/// <para>
/// The health check middleware will use default settings from <see cref="IOptions{HealthCheckOptions}"/>.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
UseHealthChecksCore(app, path, port: null, Array.Empty<object>());
return app;
}
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests. If <paramref name="path"/> is set to a non-empty
/// value, the health check middleware will process requests with a URL that matches the provided value
/// of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/') character.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, HealthCheckOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
UseHealthChecksCore(app, path, port: null, new[] { Options.Create(options), });
return app;
}
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <param name="port">The port to listen on. Must be a local port on which the server is listening.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests on the specified port. If <paramref name="path"/> is
/// set to a non-empty value, the health check middleware will process requests with a URL that matches the
/// provided value of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/')
/// character.
/// </para>
/// <para>
/// The health check middleware will use default settings from <see cref="IOptions{HealthCheckOptions}"/>.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, int port)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
UseHealthChecksCore(app, path, port, Array.Empty<object>());
return app;
}
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <param name="port">The port to listen on. Must be a local port on which the server is listening.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests on the specified port. If <paramref name="path"/> is
/// set to a non-empty value, the health check middleware will process requests with a URL that matches the
/// provided value of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/')
/// character.
/// </para>
/// <para>
/// The health check middleware will use default settings from <see cref="IOptions{HealthCheckOptions}"/>.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, string port)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (port == null)
{
throw new ArgumentNullException(nameof(port));
}
if (!int.TryParse(port, out var portAsInt))
{
throw new ArgumentException("The port must be a valid integer.", nameof(port));
}
UseHealthChecksCore(app, path, portAsInt, Array.Empty<object>());
return app;
}
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <param name="port">The port to listen on. Must be a local port on which the server is listening.</param>
/// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests on the specified port. If <paramref name="path"/> is
/// set to a non-empty value, the health check middleware will process requests with a URL that matches the
/// provided value of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/')
/// character.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, int port, HealthCheckOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
UseHealthChecksCore(app, path, port, new[] { Options.Create(options), });
return app;
}
/// <summary>
/// Adds a middleware that provides health check status.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
/// <param name="path">The path on which to provide health check status.</param>
/// <param name="port">The port to listen on. Must be a local port on which the server is listening.</param>
/// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
/// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
/// <remarks>
/// <para>
/// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
/// will ignore the URL path and process all requests on the specified port. If <paramref name="path"/> is
/// set to a non-empty value, the health check middleware will process requests with a URL that matches the
/// provided value of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/')
/// character.
/// </para>
/// </remarks>
public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, string port, HealthCheckOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (port == null)
{
throw new ArgumentNullException(nameof(port));
}
if (!int.TryParse(port, out var portAsInt))
{
throw new ArgumentException("The port must be a valid integer.", nameof(port));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
UseHealthChecksCore(app, path, portAsInt, new[] { Options.Create(options), });
return app;
}
private static void UseHealthChecksCore(IApplicationBuilder app, PathString path, int? port, object[] args)
{
if (app.ApplicationServices.GetService(typeof(HealthCheckService)) == null)
{
throw new InvalidOperationException(Resources.FormatUnableToFindServices(
nameof(IServiceCollection),
nameof(HealthCheckServiceCollectionExtensions.AddHealthChecks),
"ConfigureServices(...)"));
}
// NOTE: we explicitly don't use Map here because it's really common for multiple health
// check middleware to overlap in paths. Ex: `/health`, `/health/detailed` - this is order
// sensitive with Map, and it's really surprising to people.
//
// See:
// https://github.com/aspnet/Diagnostics/issues/511
// https://github.com/aspnet/Diagnostics/issues/512
// https://github.com/aspnet/Diagnostics/issues/514
Func<HttpContext, bool> predicate = c =>
{
return
// Process the port if we have one
(port == null || c.Connection.LocalPort == port) &&
// We allow you to listen on all URLs by providing the empty PathString.
(!path.HasValue ||
// If you do provide a PathString, want to handle all of the special cases that
// StartsWithSegments handles, but we also want it to have exact match semantics.
//
// Ex: /Foo/ == /Foo (true)
// Ex: /Foo/Bar == /Foo (false)
(c.Request.Path.StartsWithSegments(path, out var remaining) &&
string.IsNullOrEmpty(remaining)));
};
app.MapWhen(predicate, b => b.UseMiddleware<HealthCheckMiddleware>(args));
}
}
}
| |
using System;
using Anotar.LibLog;
public class ClassWithLogging
{
public bool IsTraceEnabled()
{
return LogTo.IsTraceEnabled;
}
public void Trace()
{
LogTo.Trace();
}
public void TraceString()
{
LogTo.Trace("TheMessage");
}
public void TraceStringFunc()
{
LogTo.Trace(()=>"TheMessage");
}
public void TraceStringParams()
{
LogTo.Trace("TheMessage {0}", 1);
}
public void TraceStringException()
{
LogTo.TraceException("TheMessage", new Exception());
}
public void TraceStringExceptionFunc()
{
LogTo.TraceException(()=>"TheMessage", new Exception());
}
public bool IsDebugEnabled()
{
return LogTo.IsDebugEnabled;
}
public void Debug()
{
LogTo.Debug();
}
public void DebugString()
{
LogTo.Debug("TheMessage");
}
public void DebugStringFunc()
{
LogTo.Debug(()=>"TheMessage");
}
public void DebugStringParams()
{
LogTo.Debug("TheMessage {0}", 1);
}
public void DebugStringException()
{
LogTo.DebugException("TheMessage", new Exception());
}
public void DebugStringExceptionFunc()
{
LogTo.DebugException(()=>"TheMessage", new Exception());
}
public bool IsInfoEnabled()
{
return LogTo.IsInfoEnabled;
}
public void Info()
{
LogTo.Info();
}
public void InfoString()
{
LogTo.Info("TheMessage");
}
public void InfoStringFunc()
{
LogTo.Info(()=>"TheMessage");
}
public void InfoStringParams()
{
LogTo.Info("TheMessage {0}", 1);
}
public void InfoStringException()
{
LogTo.InfoException("TheMessage", new Exception());
}
public void InfoStringExceptionFunc()
{
LogTo.InfoException(()=>"TheMessage", new Exception());
}
public bool IsWarnEnabled()
{
return LogTo.IsWarnEnabled;
}
public void Warn()
{
LogTo.Warn();
}
public void WarnString()
{
LogTo.Warn("TheMessage");
}
public void WarnStringFunc()
{
LogTo.Warn(()=>"TheMessage");
}
public void WarnStringParams()
{
LogTo.Warn("TheMessage {0}", 1);
}
public void WarnStringException()
{
LogTo.WarnException("TheMessage", new Exception());
}
public void WarnStringExceptionFunc()
{
LogTo.WarnException(()=>"TheMessage", new Exception());
}
public bool IsErrorEnabled()
{
return LogTo.IsErrorEnabled;
}
public void Error()
{
LogTo.Error();
}
public void ErrorString()
{
LogTo.Error("TheMessage");
}
public void ErrorStringFunc()
{
LogTo.Error(()=>"TheMessage");
}
public void ErrorStringParams()
{
LogTo.Error("TheMessage {0}", 1);
}
public void ErrorStringException()
{
LogTo.ErrorException("TheMessage", new Exception());
}
public void ErrorStringExceptionFunc()
{
LogTo.ErrorException(()=>"TheMessage", new Exception());
}
public bool IsFatalEnabled()
{
return LogTo.IsFatalEnabled;
}
public void Fatal()
{
LogTo.Fatal();
}
public void FatalString()
{
LogTo.Fatal("TheMessage");
}
public void FatalStringFunc()
{
LogTo.Fatal(()=>"TheMessage");
}
public void FatalStringParams()
{
LogTo.Fatal("TheMessage {0}", 1);
}
public void FatalStringException()
{
LogTo.FatalException("TheMessage", new Exception());
}
public void FatalStringExceptionFunc()
{
LogTo.FatalException(()=>"TheMessage", new Exception());
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
using System.Security.Permissions;
namespace System.Management.Automation
{
/// <summary>
/// An exception that wraps all exceptions that are thrown by providers. This allows
/// callers of the provider APIs to be able to catch a single exception no matter
/// what any of the various providers may have thrown.
/// </summary>
[Serializable]
public class ProviderInvocationException : RuntimeException
{
#region Constructors
/// <summary>
/// Constructs a ProviderInvocationException.
/// </summary>
public ProviderInvocationException() : base()
{
}
/// <summary>
/// Constructs a ProviderInvocationException using serialized data.
/// </summary>
/// <param name="info">
/// serialization information
/// </param>
/// <param name="context">
/// streaming context
/// </param>
protected ProviderInvocationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Constructs a ProviderInvocationException with a message.
/// </summary>
/// <param name="message">
/// The message for the exception.
/// </param>
public ProviderInvocationException(string message)
: base(message)
{
_message = message;
}
/// <summary>
/// Constructs a ProviderInvocationException with provider information and an inner exception.
/// </summary>
/// <param name="provider">
/// Information about the provider to be used in formatting the message.
/// </param>
/// <param name="innerException">
/// The inner exception for this exception.
/// </param>
internal ProviderInvocationException(ProviderInfo provider, Exception innerException)
: base(RuntimeException.RetrieveMessage(innerException), innerException)
{
_message = base.Message;
_providerInfo = provider;
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
}
else
{
_errorRecord = new ErrorRecord(
innerException,
"ErrorRecordNotSpecified",
ErrorCategory.InvalidOperation,
null);
}
}
/// <summary>
/// Constructs a ProviderInvocationException with provider information and an
/// ErrorRecord.
/// </summary>
/// <param name="provider">
/// Information about the provider to be used in formatting the message.
/// </param>
/// <param name="errorRecord">
/// Detailed error information
/// </param>
internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRecord)
: base(RuntimeException.RetrieveMessage(errorRecord),
RuntimeException.RetrieveException(errorRecord))
{
if (errorRecord == null)
{
throw new ArgumentNullException("errorRecord");
}
_message = base.Message;
_providerInfo = provider;
_errorRecord = errorRecord;
}
/// <summary>
/// Constructs a ProviderInvocationException with a message
/// and inner exception.
/// </summary>
/// <param name="message">
/// The message for the exception.
/// </param>
/// <param name="innerException">
/// The inner exception for this exception.
/// </param>
public ProviderInvocationException(string message, Exception innerException)
: base(message, innerException)
{
_message = message;
}
/// <summary>
/// Constructs a ProviderInvocationException.
/// </summary>
/// <param name="errorId">
/// This string will be used to construct the FullyQualifiedErrorId,
/// which is a global identifier of the error condition. Pass a
/// non-empty string which is specific to this error condition in
/// this context.
/// </param>
/// <param name="resourceStr">
/// This string is the message template string.
/// </param>
/// <param name="provider">
/// The provider information used to format into the message.
/// </param>
/// <param name="path">
/// The path that was being processed when the exception occurred.
/// </param>
/// <param name="innerException">
/// The exception that was thrown by the provider.
/// </param>
internal ProviderInvocationException(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException)
: this(errorId, resourceStr, provider, path, innerException, true)
{
}
/// <summary>
/// Constructor to make it easy to wrap a provider exception.
/// </summary>
/// <param name="errorId">
/// This string will be used to construct the FullyQualifiedErrorId,
/// which is a global identifier of the error condition. Pass a
/// non-empty string which is specific to this error condition in
/// this context.
/// </param>
/// <param name="resourceStr">
/// This is the message template string
/// </param>
/// <param name="provider">
/// The provider information used to format into the message.
/// </param>
/// <param name="path">
/// The path that was being processed when the exception occurred.
/// </param>
/// <param name="innerException">
/// The exception that was thrown by the provider.
/// </param>
/// <param name="useInnerExceptionMessage">
/// If true, the message from the inner exception will be used if the exception contains
/// an ErrorRecord. If false, the error message retrieved using the errorId will be used.
/// </param>
internal ProviderInvocationException(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException,
bool useInnerExceptionMessage)
: base(
RetrieveMessage(errorId, resourceStr, provider, path, innerException),
innerException)
{
_providerInfo = provider;
_message = base.Message;
Exception errorRecordException = null;
if (useInnerExceptionMessage)
{
errorRecordException = innerException;
}
else
{
errorRecordException = new ParentContainsErrorRecordException(this);
}
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException);
}
else
{
_errorRecord = new ErrorRecord(
errorRecordException,
errorId,
ErrorCategory.InvalidOperation,
null);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the provider information of the provider that threw an exception.
/// </summary>
public ProviderInfo ProviderInfo { get { return _providerInfo; } }
[NonSerialized]
internal ProviderInfo _providerInfo;
/// <summary>
/// Gets the error record.
/// </summary>
public override ErrorRecord ErrorRecord
{
get
{
if (_errorRecord == null)
{
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
"ProviderInvocationException",
ErrorCategory.NotSpecified,
null);
}
return _errorRecord;
}
}
[NonSerialized]
private ErrorRecord _errorRecord;
#endregion Properties
#region Private/Internal
private static string RetrieveMessage(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException)
{
if (innerException == null)
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs innerException");
return string.Empty;
}
if (string.IsNullOrEmpty(errorId))
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs errorId");
return RuntimeException.RetrieveMessage(innerException);
}
if (provider == null)
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs provider");
return RuntimeException.RetrieveMessage(innerException);
}
string format = resourceStr;
if (string.IsNullOrEmpty(format))
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage bad errorId " + errorId);
return RuntimeException.RetrieveMessage(innerException);
}
string result = null;
if (path == null)
{
result =
string.Format(
System.Globalization.CultureInfo.CurrentCulture,
format,
provider.Name,
RuntimeException.RetrieveMessage(innerException));
}
else
{
result =
string.Format(
System.Globalization.CultureInfo.CurrentCulture,
format,
provider.Name,
path,
RuntimeException.RetrieveMessage(innerException));
}
return result;
}
/// <summary>
/// Gets the exception message.
/// </summary>
public override string Message
{
get { return (string.IsNullOrEmpty(_message)) ? base.Message : _message; }
}
[NonSerialized]
private string _message /* = null */;
#endregion Private/Internal
}
/// <summary>
/// Categories of session state objects, used by SessionStateException.
/// </summary>
public enum SessionStateCategory
{
/// <summary>
/// Used when an exception is thrown accessing a variable.
/// </summary>
Variable = 0,
/// <summary>
/// Used when an exception is thrown accessing an alias.
/// </summary>
Alias = 1,
/// <summary>
/// Used when an exception is thrown accessing a function.
/// </summary>
Function = 2,
/// <summary>
/// Used when an exception is thrown accessing a filter.
/// </summary>
Filter = 3,
/// <summary>
/// Used when an exception is thrown accessing a drive.
/// </summary>
Drive = 4,
/// <summary>
/// Used when an exception is thrown accessing a Cmdlet Provider.
/// </summary>
CmdletProvider = 5,
/// <summary>
/// Used when an exception is thrown manipulating the PowerShell language scopes.
/// </summary>
Scope = 6,
/// <summary>
/// Used when generically accessing any type of command...
/// </summary>
Command = 7,
/// <summary>
/// Other resources not covered by the previous categories...
/// </summary>
Resource = 8,
/// <summary>
/// Used when an exception is thrown accessing a cmdlet.
/// </summary>
Cmdlet = 9,
}
/// <summary>
/// SessionStateException represents an error working with
/// session state objects: variables, aliases, functions, filters,
/// drives, or providers.
/// </summary>
[Serializable]
public class SessionStateException : RuntimeException
{
#region ctor
/// <summary>
/// Constructs a SessionStateException.
/// </summary>
/// <param name="itemName">Name of session state object.</param>
/// <param name="sessionStateCategory">Category of session state object.</param>
/// <param name="resourceStr">This string is the message template string.</param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="errorCategory">ErrorRecord.CategoryInfo.Category.</param>
/// <param name="messageArgs">
/// Additional insertion strings used to construct the message.
/// Note that itemName is always the first insertion string.
/// </param>
internal SessionStateException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr,
ErrorCategory errorCategory,
params object[] messageArgs)
: base(BuildMessage(itemName, resourceStr, messageArgs))
{
_itemName = itemName;
_sessionStateCategory = sessionStateCategory;
_errorId = errorIdAndResourceId;
_errorCategory = errorCategory;
}
/// <summary>
/// Constructs a SessionStateException.
/// </summary>
public SessionStateException()
: base()
{
}
/// <summary>
/// Constructs a SessionStateException.
/// </summary>
/// <param name="message">
/// The message used in the exception.
/// </param>
public SessionStateException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a SessionStateException.
/// </summary>
/// <param name="message">
/// The message used in the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public SessionStateException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a SessionStateException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected SessionStateException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_sessionStateCategory = (SessionStateCategory)info.GetInt32("SessionStateCategory"); // CODEWORK test this
}
/// <summary>
/// Serializes the exception data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
base.GetObjectData(info, context);
// If there are simple fields, serialize them with info.AddValue
info.AddValue("SessionStateCategory", (int)_sessionStateCategory);
}
#endregion Serialization
#region Properties
/// <summary>
/// Gets the error record information for this exception.
/// </summary>
public override ErrorRecord ErrorRecord
{
get
{
if (_errorRecord == null)
{
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
_errorId,
_errorCategory,
_itemName);
}
return _errorRecord;
}
}
private ErrorRecord _errorRecord;
/// <summary>
/// Gets the name of session state object the error occurred on.
/// </summary>
public string ItemName
{
get { return _itemName; }
}
private string _itemName = string.Empty;
/// <summary>
/// Gets the category of session state object the error occurred on.
/// </summary>
public SessionStateCategory SessionStateCategory
{
get { return _sessionStateCategory; }
}
private SessionStateCategory _sessionStateCategory = SessionStateCategory.Variable;
#endregion Properties
#region Private
private string _errorId = "SessionStateException";
private ErrorCategory _errorCategory = ErrorCategory.InvalidArgument;
private static string BuildMessage(
string itemName,
string resourceStr,
params object[] messageArgs)
{
object[] a;
if (messageArgs != null && 0 < messageArgs.Length)
{
a = new object[messageArgs.Length + 1];
a[0] = itemName;
messageArgs.CopyTo(a, 1);
}
else
{
a = new object[1];
a[0] = itemName;
}
return StringUtil.Format(resourceStr, a);
}
#endregion Private
}
/// <summary>
/// SessionStateUnauthorizedAccessException occurs when
/// a change to a session state object cannot be completed
/// because the object is read-only or constant, or because
/// an object which is declared constant cannot be removed
/// or made non-constant.
/// </summary>
[Serializable]
public class SessionStateUnauthorizedAccessException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException.
/// </summary>
/// <param name="itemName">
/// The name of the session state object the error occurred on.
/// </param>
/// <param name="sessionStateCategory">
/// The category of session state object.
/// </param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="resourceStr">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
internal SessionStateUnauthorizedAccessException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr
)
: base(itemName, sessionStateCategory,
errorIdAndResourceId, resourceStr, ErrorCategory.WriteError)
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException.
/// </summary>
public SessionStateUnauthorizedAccessException()
: base()
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
public SessionStateUnauthorizedAccessException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public SessionStateUnauthorizedAccessException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected SessionStateUnauthorizedAccessException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
}
/// <summary>
/// ProviderNotFoundException occurs when no provider can be found
/// with the specified name.
/// </summary>
[Serializable]
public class ProviderNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a ProviderNotFoundException.
/// </summary>
/// <param name="itemName">
/// The name of provider that could not be found.
/// </param>
/// <param name="sessionStateCategory">
/// The category of session state object
/// </param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
/// <param name="messageArgs">
/// Additional arguments to build the message from.
/// </param>
internal ProviderNotFoundException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr,
params object[] messageArgs)
: base(
itemName,
sessionStateCategory,
errorIdAndResourceId,
resourceStr,
ErrorCategory.ObjectNotFound,
messageArgs)
{
}
/// <summary>
/// Constructs a ProviderNotFoundException.
/// </summary>
public ProviderNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a ProviderNotFoundException.
/// </summary>
/// <param name="message">
/// The messaged used by the exception.
/// </param>
public ProviderNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ProviderNotFoundException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ProviderNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ProviderNotFoundException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ProviderNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
}
/// <summary>
/// ProviderNameAmbiguousException occurs when more than one provider exists
/// for a given name and the request did not contain the PSSnapin name qualifier.
/// </summary>
[Serializable]
public class ProviderNameAmbiguousException : ProviderNotFoundException
{
#region ctor
/// <summary>
/// Constructs a ProviderNameAmbiguousException.
/// </summary>
/// <param name="providerName">
/// The name of provider that was ambiguous.
/// </param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
/// <param name="possibleMatches">
/// The provider information for the providers that match the specified
/// name.
/// </param>
/// <param name="messageArgs">
/// Additional arguments to build the message from.
/// </param>
internal ProviderNameAmbiguousException(
string providerName,
string errorIdAndResourceId,
string resourceStr,
Collection<ProviderInfo> possibleMatches,
params object[] messageArgs)
: base(
providerName,
SessionStateCategory.CmdletProvider,
errorIdAndResourceId,
resourceStr,
messageArgs)
{
_possibleMatches = new ReadOnlyCollection<ProviderInfo>(possibleMatches);
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException.
/// </summary>
public ProviderNameAmbiguousException()
: base()
{
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException.
/// </summary>
/// <param name="message">
/// The messaged used by the exception.
/// </param>
public ProviderNameAmbiguousException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ProviderNameAmbiguousException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ProviderNameAmbiguousException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ProviderNameAmbiguousException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
#region public properties
/// <summary>
/// Gets the information of the providers which might match the specified
/// provider name.
/// </summary>
public ReadOnlyCollection<ProviderInfo> PossibleMatches
{
get
{
return _possibleMatches;
}
}
private ReadOnlyCollection<ProviderInfo> _possibleMatches;
#endregion public properties
}
/// <summary>
/// DriveNotFoundException occurs when no drive can be found
/// with the specified name.
/// </summary>
[Serializable]
public class DriveNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a DriveNotFoundException.
/// </summary>
/// <param name="itemName">
/// The name of the drive that could not be found.
/// </param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
internal DriveNotFoundException(
string itemName,
string errorIdAndResourceId,
string resourceStr
)
: base(itemName, SessionStateCategory.Drive,
errorIdAndResourceId, resourceStr, ErrorCategory.ObjectNotFound)
{
}
/// <summary>
/// Constructs a DriveNotFoundException.
/// </summary>
public DriveNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a DriveNotFoundException.
/// </summary>
/// <param name="message">
/// The message that will be used by the exception.
/// </param>
public DriveNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a DriveNotFoundException.
/// </summary>
/// <param name="message">
/// The message that will be used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public DriveNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a DriveNotFoundException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected DriveNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
}
/// <summary>
/// ItemNotFoundException occurs when the path contained no wildcard characters
/// and an item at that path could not be found.
/// </summary>
[Serializable]
public class ItemNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a ItemNotFoundException.
/// </summary>
/// <param name="path">
/// The path that was not found.
/// </param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="resourceStr">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
internal ItemNotFoundException(
string path,
string errorIdAndResourceId,
string resourceStr
)
: base(path, SessionStateCategory.Drive,
errorIdAndResourceId, resourceStr, ErrorCategory.ObjectNotFound)
{
}
/// <summary>
/// Constructs a ItemNotFoundException.
/// </summary>
public ItemNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a ItemNotFoundException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
public ItemNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ItemNotFoundException.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ItemNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ItemNotFoundException using serialized data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ItemNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace WinTunnel
{
public class WinTunnel : System.ServiceProcess.ServiceBase
{
public static String SERVICE_NAME = "WinTunnel";
public static String SERVERICE_DISPLAY_NAME = "Windows TCP Tunnel";
private static ManualResetEvent shutdownEvent = new ManualResetEvent(false);
private ConnectionManager m_connMgr;
private AppConfig m_config;
private Logger logger;
private bool m_debug = false;
private ConsoleCtrl m_ctrl = null;
public WinTunnel()
{
CanPauseAndContinue = true;
ServiceName = SERVICE_NAME;
AutoLog = false;
}
// The main entry point for the process
static void Main(string[] args)
{
if (args.Length==1 && args[0].CompareTo("-debug") ==0 ) //run as a console application
{
System.Console.WriteLine("Starting WinTunnel as a console application...");
WinTunnel tunnel = new WinTunnel();
tunnel.m_debug = true;
tunnel.OnStart(args);
return;
}
else if (args.Length == 1 && args[0].CompareTo("-remove") ==0 ) //remove service
{
System.Console.WriteLine("Remove WinTunnel as a service...");
String argument = "-u " + Process.GetCurrentProcess().MainModule.ModuleName;
String launchCmd = RuntimeEnvironment.GetRuntimeDirectory() + "InstallUtil.exe";
launchProcess(launchCmd, argument);
return;
}
else if (args.Length > 0 && args[0].CompareTo("-install") ==0 ) //install as a service
{
System.Console.WriteLine("Installing WinTunnel as a service...");
StringBuilder argument = new StringBuilder();
int i=1;
while(i < args.Length)
{
if (args[i].ToLower().CompareTo("-user") == 0)
{
argument.Append(" /user=");
argument.Append(args[i+1]);
i+=2;
}
else if ( args[i].ToLower().CompareTo("-password") == 0)
{
argument.Append(" /password=");
argument.Append( args[i+1]);
i+=2;
}
else
{
i++;
}
}
argument.Append(" ");
argument.Append( Process.GetCurrentProcess().MainModule.ModuleName );
String launchCmd = RuntimeEnvironment.GetRuntimeDirectory() + "InstallUtil.exe";
launchProcess(launchCmd, argument.ToString());
return;
}
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinTunnel() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
static void launchProcess(String binary, String argument)
{
System.Diagnostics.ProcessStartInfo psInfo =
new System.Diagnostics.ProcessStartInfo(binary, argument);
System.Console.WriteLine();
System.Console.WriteLine(psInfo.FileName + " " + psInfo.Arguments);
System.Console.WriteLine();
psInfo.RedirectStandardOutput = true;
psInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psInfo.UseShellExecute = false;
System.Diagnostics.Process ps;
ps = System.Diagnostics.Process.Start(psInfo);
System.IO.StreamReader msgOut = ps.StandardOutput;
ps.WaitForExit(5000); //wait up to 5 seconds
if (ps.HasExited)
{
System.Console.WriteLine(msgOut.ReadToEnd()); //write the output
}
return;
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
Thread t = new Thread( new ThreadStart(startApplication) );
t.Name = "main";
t.Start();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
//Signal the main thread to exit
shutdownEvent.Set();
}
public static void consoleEventHandler(ConsoleCtrl.ConsoleEvent consoleEvent)
{
if (ConsoleCtrl.ConsoleEvent.CTRL_C == consoleEvent)
{
Logger.getInstance().info("Received CTRL-C from Console. Shutting down...");
WinTunnel.shutdownEvent.Set();
}
else
{
Logger.getInstance().warn("Received unknown event {0}. Ignoring...", consoleEvent);
}
}
private void startApplication()
{
logger = Logger.getInstance();
logger.initialize(m_debug);
logger.info("");
logger.info("===============================");
logger.info("*** Starting up WinTunnel ****");
logger.info("===============================");
logger.info("Starting thread... ");
//create a signal handler to detect Ctrl-C to stop the service
if (m_debug)
{
m_ctrl = new ConsoleCtrl();
m_ctrl.ControlEvent += new ConsoleCtrl.ControlEventHandler(consoleEventHandler);
}
//Load configuration and startup
m_config = new AppConfig();
if ( ! m_config.initialize() )
{
logger.error("Error loading configuration file. Exiting...");
return;
}
//Initialize the threadpool
MyThreadPool pool = MyThreadPool.getInstance();
pool.initialize();
m_connMgr = ConnectionManager.getInstance();
foreach (ProxyConfig cfg in m_config.m_proxyConfigs)
{
ProxyClientListenerTask task = new ProxyClientListenerTask(cfg);
pool.addTask(task);
}
shutdownEvent.WaitOne(); //now just wait for signal to exit
logger.info("Thread is initiating shutdown... ");
if (m_ctrl != null)
{
logger.info("Releasing Console Event handler. ");
m_ctrl = null;
}
//Shutdown the connection manager
m_connMgr.shutdown();
logger.info("Connection Manager has been terminated. ");
//Shutdown the thread pool
pool.Stop();
logger.info("ThreadPool has been stopped. ");
logger.info("Terminating thread... ");
logger.info("*** WinTunnel exited. ****");
logger.close();
}
}
}
| |
// ======================================================================================
// File : exDebugHelper.cs
// Author : Wu Jie
// Last Change : 06/05/2011 | 11:08:21 AM | Sunday,June
// Description :
// ======================================================================================
///////////////////////////////////////////////////////////////////////////////
// usings
///////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
///////////////////////////////////////////////////////////////////////////////
// defines
///////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
[ExecuteInEditMode]
public class exDebugHelper : MonoBehaviour {
///////////////////////////////////////////////////////////////////////////////
// static
///////////////////////////////////////////////////////////////////////////////
// static instance
public static exDebugHelper instance = null;
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static void ScreenPrint ( string _text ) {
if ( instance.showScreenPrint_ ) {
instance.txtPrint = instance.txtPrint + _text + "\n";
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static void ScreenPrint ( Vector2 _pos, string _text, GUIStyle _style = null ) {
if ( instance.showScreenDebugText ) {
TextInfo info = new TextInfo( _pos, _text, _style );
instance.debugTextPool.Add(info);
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public enum LogType {
None,
Normal,
Warning,
Error,
}
public static void ScreenLog ( string _text, LogType _logType = LogType.None, GUIStyle _style = null, bool autoFadeOut = true) {
LogInfo info = new LogInfo( _text, _style, autoFadeOut ? 5.0f : 0 );
instance.pendingLogs.Enqueue(info);
if ( _logType != LogType.None ) {
switch ( _logType ) {
case LogType.Normal: Debug.Log(_text); break;
case LogType.Warning: Debug.LogWarning(_text); break;
case LogType.Error: Debug.LogError(_text); break;
}
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static void SetFPSColor ( Color _color ) {
instance.fpsStyle.normal.textColor = _color;
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static float GetFPS () { return instance.fps; }
///////////////////////////////////////////////////////////////////////////////
// serialized
///////////////////////////////////////////////////////////////////////////////
public Vector2 offset = new Vector2 ( 10.0f, 10.0f );
public GUIStyle printStyle = null;
public GUIStyle fpsStyle = null;
public GUIStyle logStyle = null;
public GUIStyle timeScaleStyle = null;
protected string txtPrint = "screen print: ";
protected string txtFPS = "fps: ";
// for screen debug text
public class TextInfo {
public Vector2 screenPos = Vector2.zero;
public string text;
public GUIStyle style = null;
public TextInfo ( Vector2 _screenPos, string _text, GUIStyle _style ) {
screenPos = _screenPos;
text = _text;
style = _style;
}
}
protected List<TextInfo> debugTextPool = new List<TextInfo>();
// for screen log
public class LogInfo {
public string text;
public GUIStyle style = null;
public float ratio {
get {
if (lifetime == 0) {
return 0;
}
return (timer >= lifetime - instance.logFadeOutDuration) ? (timer - (lifetime-instance.logFadeOutDuration))/instance.logFadeOutDuration : 0.0f;
}
}
public bool canDelete { get { return timer > lifetime; } }
// internal
float speed = 1.0f;
float timer = 0.0f;
float lifetime = 5.0f;
public LogInfo ( string _text, GUIStyle _style, float _lifetime ) {
text = _text;
style = _style;
lifetime = _lifetime;
}
public void Dead () {
if (lifetime > 0) {
float deadTime = lifetime - instance.logFadeOutDuration;
if ( timer < deadTime - 1.0f) {
timer = deadTime - 1.0f;
}
}
}
public void Tick () {
if (lifetime > 0) {
timer += Time.deltaTime * speed;
}
}
}
// DISABLE {
// float logInterval = 0.05f;
// float logTimer = 0.0f;
// } DISABLE end
float logFadeOutDuration = 0.3f;
protected List<LogInfo> logs = new List<LogInfo>();
protected Queue<LogInfo> pendingLogs = new Queue<LogInfo>();
// fps
[SerializeField] protected bool showFps_ = true;
public bool showFps {
get { return showFps_; }
set {
if ( showFps_ != value ) {
showFps_ = value;
}
}
}
public TextAnchor fpsAnchor = TextAnchor.UpperLeft;
// timescale
[SerializeField] protected bool enableTimeScaleDebug_ = true;
public bool enableTimeScaleDebug {
get { return enableTimeScaleDebug_; }
set {
if ( enableTimeScaleDebug_ != value ) {
enableTimeScaleDebug_ = value;
}
}
}
// screen print
[SerializeField] protected bool showScreenPrint_ = true;
public bool showScreenPrint {
get { return showScreenPrint_; }
set {
if ( showScreenPrint_ != value ) {
showScreenPrint_ = value;
}
}
}
// screen log
[SerializeField] protected bool showScreenLog_ = true;
public bool showScreenLog {
get { return showScreenLog_; }
set {
if ( showScreenLog_ != value ) {
showScreenLog_ = value;
}
}
}
public int logCount = 10;
// screen debug text
public bool showScreenDebugText = false;
///////////////////////////////////////////////////////////////////////////////
// non-serialized
///////////////////////////////////////////////////////////////////////////////
protected int frames = 0;
protected float fps = 0.0f;
protected float lastInterval = 0.0f;
///////////////////////////////////////////////////////////////////////////////
// functions
///////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void Awake () {
if ( instance == null )
instance = this;
// DISABLE {
// logTimer = logInterval;
// } DISABLE end
txtPrint = "";
txtFPS = "";
if ( showScreenDebugText ) {
debugTextPool.Clear();
}
useGUILayout = false;
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void Start () {
InvokeRepeating("UpdateFPS", 0.0f, 1.0f );
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void Update () {
// count fps
++frames;
//
UpdateTimeScale ();
// update log
UpdateLog ();
// NOTE: the OnGUI call multiple times in one frame, so we just clear text here.
StartCoroutine ( CleanDebugText() );
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void OnGUI () {
GUIContent content = null;
Vector2 size = Vector2.zero;
float curX = offset.x;
float curY = offset.y;
if ( showFps ) {
content = new GUIContent(txtFPS);
size = fpsStyle.CalcSize(content);
//
switch ( fpsAnchor ) {
//
case TextAnchor.UpperLeft:
break;
case TextAnchor.UpperCenter:
curX = curX + (Screen.width - size.x) * 0.5f;
break;
case TextAnchor.UpperRight:
curX = Screen.width - size.x - curX;
break;
//
case TextAnchor.MiddleLeft:
curY = curY + (Screen.height - size.y) * 0.5f;
break;
case TextAnchor.MiddleCenter:
curX = curX + (Screen.width - size.x) * 0.5f;
curY = curY + (Screen.height - size.y) * 0.5f;
break;
case TextAnchor.MiddleRight:
curX = Screen.width - size.x - curX;
curY = curY + (Screen.height - size.y) * 0.5f;
break;
//
case TextAnchor.LowerLeft:
curY = Screen.height - size.y - curY;
break;
case TextAnchor.LowerCenter:
curX = curX + (Screen.width - size.x) * 0.5f;
curY = Screen.height - size.y - curY;
break;
case TextAnchor.LowerRight:
curX = Screen.width - size.x - curX;
curY = Screen.height - size.y - curY;
break;
}
GUI.Label ( new Rect( curX, curY, size.x, size.y ), txtFPS, fpsStyle );
curX = 10.0f;
curY = 10.0f + size.y;
}
if ( enableTimeScaleDebug ) {
string txtTimeScale = "TimeScale = " + Time.timeScale.ToString("f2");
content = new GUIContent(txtTimeScale);
size = timeScaleStyle.CalcSize(content);
GUI.Label ( new Rect( curX, curY, size.x, size.y ), txtTimeScale, timeScaleStyle );
curY += size.y;
}
if ( showScreenPrint ) {
content = new GUIContent(txtPrint);
size = printStyle.CalcSize(content);
GUI.Label ( new Rect( curX, curY, size.x, size.y ), txtPrint, printStyle );
}
if ( showScreenLog ) {
float y;
bool downToUp = logStyle.alignment == TextAnchor.LowerLeft || logStyle.alignment == TextAnchor.LowerCenter || logStyle.alignment == TextAnchor.LowerRight;
bool rightAlign = logStyle.alignment == TextAnchor.LowerRight || logStyle.alignment == TextAnchor.MiddleRight || logStyle.alignment == TextAnchor.UpperRight;
if (downToUp) {
y = Screen.height - 10;
}
else {
y = 50;
}
for ( int i = logs.Count-1; i >= 0; --i ) {
LogInfo info = logs[i];
content = new GUIContent(info.text);
GUIStyle style = (info.style == null) ? logStyle : info.style;
size = style.CalcSize(content);
//
style.normal.textColor = new Color ( style.normal.textColor.r,
style.normal.textColor.g,
style.normal.textColor.b,
1.0f - info.ratio );
if (downToUp) {
y -= size.y;
}
else {
y += size.y;
}
if (rightAlign) {
GUI.Label(new Rect(Screen.width - 10.0f - size.x, y, size.x, size.y), info.text, style);
}
else {
GUI.Label(new Rect(10.0f, y, size.x, size.y), info.text, style);
}
}
}
if ( showScreenDebugText ) {
for ( int i = 0; i < debugTextPool.Count; ++i ) {
TextInfo info = debugTextPool[i];
content = new GUIContent(info.text);
GUIStyle style = (info.style == null) ? GUI.skin.label : info.style;
size = style.CalcSize(content);
Vector2 pos = new Vector2( info.screenPos.x, Screen.height - info.screenPos.y ) - size * 0.5f;
GUI.Label ( new Rect( pos.x, pos.y, size.x, size.y ), info.text, style );
}
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void UpdateFPS () {
float timeNow = Time.realtimeSinceStartup;
fps = frames / (timeNow - lastInterval);
frames = 0;
lastInterval = timeNow;
txtFPS = "fps: " + fps.ToString("f2");
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void UpdateTimeScale () {
if ( enableTimeScaleDebug ) {
if ( Input.GetKey(KeyCode.Minus) ) {
Time.timeScale = Mathf.Max( Time.timeScale - 0.01f, 0.0f );
}
else if ( Input.GetKey(KeyCode.Equals) ) {
Time.timeScale = Mathf.Min( Time.timeScale + 0.01f, 10.0f );
}
if ( Input.GetKey(KeyCode.Alpha0 ) ) {
Time.timeScale = 0.0f;
}
else if ( Input.GetKey(KeyCode.Alpha9 ) ) {
Time.timeScale = 1.0f;
}
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
IEnumerator CleanDebugText () {
yield return new WaitForEndOfFrame();
txtPrint = "";
if ( showScreenDebugText ) {
debugTextPool.Clear();
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
void UpdateLog () {
for ( int i = logs.Count-1; i >= 0; --i ) {
LogInfo info = logs[i];
info.Tick();
if ( info.canDelete ) {
logs.RemoveAt(i);
}
}
// DISABLE {
// if ( logTimer < logInterval ) {
// logTimer += Time.deltaTime;
// }
// else {
// if ( pendingLogs.Count > 0 ) {
// logTimer = 0.0f;
// logs.Add(pendingLogs.Dequeue());
// if ( instance.logs.Count > instance.logCount ) {
// for ( int i = 0; i < instance.logs.Count - instance.logCount; ++i ) {
// instance.logs[i].Dead();
// }
// }
// }
// }
// } DISABLE end
bool downToUp = logStyle.alignment == TextAnchor.LowerLeft || logStyle.alignment == TextAnchor.LowerCenter || logStyle.alignment == TextAnchor.LowerRight;
if ( pendingLogs.Count > 0 ) {
int count = Mathf.CeilToInt(pendingLogs.Count/2);
do {
if (downToUp) {
logs.Add(pendingLogs.Dequeue());
}
else {
logs.Insert(0, pendingLogs.Dequeue());
}
--count;
if ( instance.logs.Count > instance.logCount ) {
for ( int i = 0; i < instance.logs.Count - instance.logCount; ++i ) {
instance.logs[i].Dead();
}
}
} while ( count > 0 );
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static void ClearScreen () {
instance.pendingLogs.Clear ();
instance.logs.Clear ();
// for (int i = instance.logs.Count-1; i >= 0; --i) {
// LogInfo info = logs [i];
// info.Dead ();
// }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.IO.Tests
{
public partial class PathTests : PathTestsBase
{
[Fact]
public void GetDirectoryName_EmptyReturnsNull()
{
// In NetFX this throws argument exception
Assert.Null(Path.GetDirectoryName(string.Empty));
}
[Theory, MemberData(nameof(TestData_Spaces))]
public void GetDirectoryName_Spaces(string path)
{
if (PlatformDetection.IsWindows)
{
// In Windows spaces are eaten by Win32, making them effectively empty
Assert.Null(Path.GetDirectoryName(path));
}
else
{
Assert.Empty(Path.GetDirectoryName(path));
}
}
[Theory, MemberData(nameof(TestData_Spaces))]
public void GetDirectoryName_Span_Spaces(string path)
{
PathAssert.Empty(Path.GetDirectoryName(path.AsSpan()));
}
[Theory,
MemberData(nameof(TestData_EmbeddedNull)),
MemberData(nameof(TestData_ControlChars)),
MemberData(nameof(TestData_UnicodeWhiteSpace))]
public void GetDirectoryName_NetFxInvalid(string path)
{
Assert.Empty(Path.GetDirectoryName(path));
Assert.Equal(path, Path.GetDirectoryName(Path.Combine(path, path)));
PathAssert.Empty(Path.GetDirectoryName(path.AsSpan()));
PathAssert.Equal(path, new string(Path.GetDirectoryName(Path.Combine(path, path).AsSpan())));
}
[Theory, MemberData(nameof(TestData_GetDirectoryName))]
public void GetDirectoryName_Span(string path, string expected)
{
PathAssert.Equal(expected ?? ReadOnlySpan<char>.Empty, Path.GetDirectoryName(path.AsSpan()));
}
[Fact]
public void GetDirectoryName_Span_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
PathAssert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz").AsSpan()));
PathAssert.Empty(Path.GetDirectoryName(Path.GetPathRoot(curDir).AsSpan()));
}
[Theory,
InlineData(@" C:\dir/baz", @" C:\dir"),
InlineData(@" C:\dir/baz", @" C:\dir")]
public void GetDirectoryName_SkipSpaces(string path, string expected)
{
// We no longer trim leading spaces for any path
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory, MemberData(nameof(TestData_GetExtension))]
public void GetExtension_Span(string path, string expected)
{
PathAssert.Equal(expected, Path.GetExtension(path.AsSpan()));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path.AsSpan()));
}
[Theory, MemberData(nameof(TestData_GetFileName))]
public void GetFileName_Span(string path, string expected)
{
PathAssert.Equal(expected, Path.GetFileName(path.AsSpan()));
}
public static IEnumerable<object[]> TestData_GetFileName_Volume()
{
yield return new object[] { ":", ":" };
yield return new object[] { ".:", ".:" };
yield return new object[] { ".:.", ".:." }; // Not a valid drive letter
yield return new object[] { "file:", "file:" };
yield return new object[] { ":file", ":file" };
yield return new object[] { "file:exe", "file:exe" };
yield return new object[] { Path.Combine("baz", "file:exe"), "file:exe" };
yield return new object[] { Path.Combine("bar", "baz", "file:exe"), "file:exe" };
}
[Theory, MemberData(nameof(TestData_GetFileName_Volume))]
public void GetFileName_Volume(string path, string expected)
{
// We used to break on ':' on Windows. This is a valid file name character for alternate data streams.
// Additionally the character can show up on unix volumes mounted to Windows.
Assert.Equal(expected, Path.GetFileName(path));
PathAssert.Equal(expected, Path.GetFileName(path.AsSpan()));
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Theory, MemberData(nameof(TestData_GetFileNameWithoutExtension))]
public void GetFileNameWithoutExtension_Span(string path, string expected)
{
PathAssert.Equal(expected, Path.GetFileNameWithoutExtension(path.AsSpan()));
}
[Fact]
public void GetPathRoot_Empty()
{
Assert.Null(Path.GetPathRoot(string.Empty));
}
[Fact]
public void GetPathRoot_Empty_Span()
{
PathAssert.Empty(Path.GetPathRoot(ReadOnlySpan<char>.Empty));
}
[Theory,
InlineData(nameof(TestData_Spaces)),
InlineData(nameof(TestData_ControlChars)),
InlineData(nameof(TestData_EmbeddedNull)),
InlineData(nameof(TestData_InvalidDriveLetters)),
InlineData(nameof(TestData_UnicodeWhiteSpace)),
InlineData(nameof(TestData_EmptyString))]
public void IsPathRooted_NegativeCases(string path)
{
Assert.False(Path.IsPathRooted(path));
Assert.False(Path.IsPathRooted(path.AsSpan()));
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Fact]
public void GetInvalidPathChars()
{
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Equal(bad + ".ok", Path.ChangeExtension(bad, "ok"));
Assert.Equal(bad + Path.DirectorySeparatorChar + "ok", Path.Combine(bad, "ok"));
Assert.Equal("ok" + Path.DirectorySeparatorChar + "ok" + Path.DirectorySeparatorChar + bad, Path.Combine("ok", "ok", bad));
Assert.Equal("ok" + Path.DirectorySeparatorChar + "ok" + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + "ok", Path.Combine("ok", "ok", bad, "ok"));
Assert.Equal(bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad + Path.DirectorySeparatorChar + bad, Path.Combine(bad, bad, bad, bad, bad));
Assert.Equal("", Path.GetDirectoryName(bad));
Assert.Equal(string.Empty, Path.GetExtension(bad));
Assert.Equal(bad, Path.GetFileName(bad));
Assert.Equal(bad, Path.GetFileNameWithoutExtension(bad));
if (bad[0] == '\0')
{
Assert.Throws<ArgumentException>("path", () => Path.GetFullPath(bad));
}
else
{
Assert.True(Path.GetFullPath(bad).EndsWith(bad));
}
Assert.Equal(string.Empty, Path.GetPathRoot(bad));
Assert.False(Path.IsPathRooted(bad));
});
}
[Fact]
public void GetInvalidPathChars_Span()
{
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Equal(string.Empty, new string(Path.GetDirectoryName(bad.AsSpan())));
Assert.Equal(string.Empty, new string(Path.GetExtension(bad.AsSpan())));
Assert.Equal(bad, new string(Path.GetFileName(bad.AsSpan())));
Assert.Equal(bad, new string(Path.GetFileNameWithoutExtension(bad.AsSpan())));
Assert.Equal(string.Empty, new string(Path.GetPathRoot(bad.AsSpan())));
Assert.False(Path.IsPathRooted(bad.AsSpan()));
});
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Theory,
InlineData("http://www.microsoft.com"),
InlineData("file://somefile")]
public void GetFullPath_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", Path.DirectorySeparatorChar.ToString())),
Path.GetFullPath(uriAsFileName));
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Theory, MemberData(nameof(TestData_NonDriveColonPaths))]
public void GetFullPath_NowSupportedColons(string path)
{
// Used to throw on Windows, now should never throw
Path.GetFullPath(path);
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Theory, MemberData(nameof(TestData_InvalidUnc))]
public static void GetFullPath_UNC_Invalid(string path)
{
// These UNCs used to throw on Windows
Path.GetFullPath(path);
}
[ActiveIssue(27269, TestPlatforms.Windows)]
[Theory,
MemberData(nameof(TestData_Wildcards)),
MemberData(nameof(TestData_ExtendedWildcards))]
public void GetFullPath_Wildcards(char wildcard)
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + wildcard + "ing");
Assert.Equal(path, Path.GetFullPath(path));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
** Purpose: This class will encapsulate a short and provide an
** Object representation of it.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
// Wrapper for unsigned 16 bit integers.
[CLSCompliant(false)]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UInt16 : IComparable, IFormattable, IComparable<UInt16>, IEquatable<UInt16>, IConvertible
{
private ushort _value;
public const ushort MaxValue = (ushort)0xFFFF;
public const ushort MinValue = 0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt16, this method throws an ArgumentException.
//
int IComparable.CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt16)
{
return ((int)_value - (int)(((UInt16)value)._value));
}
throw new ArgumentException(SR.Arg_MustBeUInt16);
}
public int CompareTo(UInt16 value)
{
return ((int)_value - (int)value);
}
public override bool Equals(Object obj)
{
if (!(obj is UInt16))
{
return false;
}
return _value == ((UInt16)obj)._value;
}
[NonVersionable]
public bool Equals(UInt16 obj)
{
return _value == obj;
}
// Returns a HashCode for the UInt16
public override int GetHashCode()
{
return (int)_value;
}
// Converts the current value to a String in base-10 with no extra padding.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, null, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, null, provider);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, format, null);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, format, provider);
}
[CLSCompliant(false)]
public static ushort Parse(String s)
{
return Parse(s, NumberStyles.Integer, null);
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style)
{
UInt32.ValidateParseStyleInteger(style);
return Parse(s, style, null);
}
[CLSCompliant(false)]
public static ushort Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, provider);
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style, IFormatProvider provider)
{
UInt32.ValidateParseStyleInteger(style);
uint i = 0;
try
{
i = FormatProvider.ParseUInt32(s, style, provider);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_UInt16, e);
}
if (i > MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)i;
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt16 result)
{
return TryParse(s, NumberStyles.Integer, null, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result)
{
UInt32.ValidateParseStyleInteger(style);
result = 0;
UInt32 i;
if (!FormatProvider.TryParseUInt32(s, style, provider, out i))
{
return false;
}
if (i > MaxValue)
{
return false;
}
result = (UInt16)i;
return true;
}
//
// IConvertible implementation
//
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.UInt16;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return _value;
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
namespace Lucene.Net.Index
{
/// <summary> Combines multiple files into a single compound file.
/// The file format:<br/>
/// <ul>
/// <li>VInt fileCount</li>
/// <li>{Directory}
/// fileCount entries with the following structure:</li>
/// <ul>
/// <li>long dataOffset</li>
/// <li>String fileName</li>
/// </ul>
/// <li>{File Data}
/// fileCount entries with the raw data of the corresponding file</li>
/// </ul>
///
/// The fileCount integer indicates how many files are contained in this compound
/// file. The {directory} that follows has that many entries. Each directory entry
/// contains a long pointer to the start of this file's data section, and a String
/// with that file's name.
///
///
/// </summary>
/// <version> $Id: CompoundFileWriter.java 690539 2008-08-30 17:33:06Z mikemccand $
/// </version>
public sealed class CompoundFileWriter
{
private sealed class FileEntry
{
/// <summary>source file </summary>
internal System.String file;
/// <summary>temporary holder for the start of directory entry for this file </summary>
internal long directoryOffset;
/// <summary>temporary holder for the start of this file's data section </summary>
internal long dataOffset;
}
private Directory directory;
private System.String fileName;
private System.Collections.Hashtable ids;
private System.Collections.ArrayList entries;
private bool merged = false;
private SegmentMerger.CheckAbort checkAbort;
/// <summary>Create the compound stream in the specified file. The file name is the
/// entire name (no extensions are added).
/// </summary>
/// <throws> NullPointerException if <code>dir</code> or <code>name</code> is null </throws>
public CompoundFileWriter(Directory dir, System.String name):this(dir, name, null)
{
}
internal CompoundFileWriter(Directory dir, System.String name, SegmentMerger.CheckAbort checkAbort)
{
if (dir == null)
throw new System.NullReferenceException("directory cannot be null");
if (name == null)
throw new System.NullReferenceException("name cannot be null");
this.checkAbort = checkAbort;
directory = dir;
fileName = name;
ids = new System.Collections.Hashtable();
entries = new System.Collections.ArrayList();
}
/// <summary>Returns the directory of the compound file. </summary>
public Directory GetDirectory()
{
return directory;
}
/// <summary>Returns the name of the compound file. </summary>
public System.String GetName()
{
return fileName;
}
/// <summary>Add a source stream. <code>file</code> is the string by which the
/// sub-stream will be known in the compound stream.
///
/// </summary>
/// <throws> IllegalStateException if this writer is closed </throws>
/// <throws> NullPointerException if <code>file</code> is null </throws>
/// <throws> IllegalArgumentException if a file with the same name </throws>
/// <summary> has been added already
/// </summary>
public void AddFile(System.String file)
{
if (merged)
throw new System.SystemException("Can't add extensions after merge has been called");
if (file == null)
throw new System.NullReferenceException("file cannot be null");
try
{
ids.Add(file, file);
}
catch (Exception)
{
throw new System.ArgumentException("File " + file + " already added");
}
FileEntry entry = new FileEntry();
entry.file = file;
entries.Add(entry);
}
/// <summary>Merge files with the extensions added up to now.
/// All files with these extensions are combined sequentially into the
/// compound stream. After successful merge, the source files
/// are deleted.
/// </summary>
/// <throws> IllegalStateException if close() had been called before or </throws>
/// <summary> if no file has been added to this object
/// </summary>
public void Close()
{
if (merged)
throw new System.SystemException("Merge already performed");
if ((entries.Count == 0))
throw new System.SystemException("No entries to merge have been defined");
merged = true;
// open the compound stream
IndexOutput os = null;
try
{
os = directory.CreateOutput(fileName);
// Write the number of entries
os.WriteVInt(entries.Count);
// Write the directory with all offsets at 0.
// Remember the positions of directory entries so that we can
// adjust the offsets later
System.Collections.IEnumerator it = entries.GetEnumerator();
long totalSize = 0;
while (it.MoveNext())
{
FileEntry fe = (FileEntry) it.Current;
fe.directoryOffset = os.GetFilePointer();
os.WriteLong(0); // for now
os.WriteString(fe.file);
totalSize += directory.FileLength(fe.file);
}
// Pre-allocate size of file as optimization --
// this can potentially help IO performance as
// we write the file and also later during
// searching. It also uncovers a disk-full
// situation earlier and hopefully without
// actually filling disk to 100%:
long finalLength = totalSize + os.GetFilePointer();
os.SetLength(finalLength);
// Open the files and copy their data into the stream.
// Remember the locations of each file's data section.
byte[] buffer = new byte[16384];
it = entries.GetEnumerator();
while (it.MoveNext())
{
FileEntry fe = (FileEntry) it.Current;
fe.dataOffset = os.GetFilePointer();
CopyFile(fe, os, buffer);
}
// Write the data offsets into the directory of the compound stream
it = entries.GetEnumerator();
while (it.MoveNext())
{
FileEntry fe = (FileEntry) it.Current;
os.Seek(fe.directoryOffset);
os.WriteLong(fe.dataOffset);
}
System.Diagnostics.Debug.Assert(finalLength == os.Length());
// Close the output stream. Set the os to null before trying to
// close so that if an exception occurs during the close, the
// finally clause below will not attempt to close the stream
// the second time.
IndexOutput tmp = os;
os = null;
tmp.Close();
}
finally
{
if (os != null)
try
{
os.Close();
}
catch (System.IO.IOException e)
{
}
}
}
/// <summary>Copy the contents of the file with specified extension into the
/// provided output stream. Use the provided buffer for moving data
/// to reduce memory allocation.
/// </summary>
private void CopyFile(FileEntry source, IndexOutput os, byte[] buffer)
{
IndexInput is_Renamed = null;
try
{
long startPtr = os.GetFilePointer();
is_Renamed = directory.OpenInput(source.file);
long length = is_Renamed.Length();
long remainder = length;
int chunk = buffer.Length;
while (remainder > 0)
{
int len = (int) System.Math.Min(chunk, remainder);
is_Renamed.ReadBytes(buffer, 0, len, false);
os.WriteBytes(buffer, len);
remainder -= len;
if (checkAbort != null)
// Roughly every 2 MB we will check if
// it's time to abort
checkAbort.Work(80);
}
// Verify that remainder is 0
if (remainder != 0)
throw new System.IO.IOException("Non-zero remainder length after copying: " + remainder + " (id: " + source.file + ", length: " + length + ", buffer size: " + chunk + ")");
// Verify that the output length diff is equal to original file
long endPtr = os.GetFilePointer();
long diff = endPtr - startPtr;
if (diff != length)
throw new System.IO.IOException("Difference in the output file offsets " + diff + " does not match the original file length " + length);
}
finally
{
if (is_Renamed != null)
is_Renamed.Close();
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Content;
namespace GameStateManagement
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
#region Properties
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup { get; protected set; }
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return _transitionOnTime; }
protected set { _transitionOnTime = value; }
}
TimeSpan _transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return _transitionOffTime; }
protected set { _transitionOffTime = value; }
}
TimeSpan _transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public virtual float TransitionPosition
{
get { return _transitionPosition; }
protected set { _transitionPosition = value; }
}
float _transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 1 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionAlpha
{
get { return 1f - TransitionPosition; }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return _screenState; }
protected set { _screenState = value; }
}
ScreenState _screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return _isExiting; }
protected internal set { _isExiting = value; }
}
bool _isExiting;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !_otherScreenHasFocus &&
(_screenState == ScreenState.TransitionOn ||
_screenState == ScreenState.Active);
}
}
bool _otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager { get; internal set; }
#if WINDOWS_PHONE || WINDOWS || ANDROID
/// <summary>
/// Gets the gestures the screen is interested in. Screens should be as specific
/// as possible with gestures to increase the accuracy of the gesture engine.
/// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate.
/// These gestures are handled by the ScreenManager when screens change and
/// all gestures are placed in the InputState passed to the HandleInput method.
/// </summary>
public GestureType EnabledGestures
{
get { return _enabledGestures; }
protected set
{
_enabledGestures = value;
// the screen manager handles this during screen changes, but
// if this screen is active and the gesture types are changing,
// we have to update the TouchPanel ourself.
if (ScreenState == ScreenState.Active)
{
TouchPanel.EnabledGestures = value;
}
}
}
GestureType _enabledGestures = GestureType.None;
#endif
/// <summary>
/// Gets whether or not this screen is serializable. If this is true,
/// the screen will be recorded into the screen manager's state and
/// its Serialize and Deserialize methods will be called as appropriate.
/// If this is false, the screen will be ignored during serialization.
/// By default, all screens are assumed to be serializable.
/// </summary>
public bool IsSerializable
{
get { return _isSerializable; }
protected set { _isSerializable = value; }
}
bool _isSerializable = true;
public ContentManager content;
protected GameScreen()
{
IsPopup = false;
}
public object Tag { get; set; }
#endregion
#region Initialization
/// <summary>
/// Activates the screen. Called when the screen is added to the screen manager or if the game resumes
/// from being paused or tombstoned.
/// </summary>
/// <param name="instancePreserved">
/// True if the game was preserved during deactivation, false if the screen is just being added or if the game was tombstoned.
/// On Xbox and Windows this will always be false.
/// </param>
public virtual void Activate(bool instancePreserved) { }
/// <summary>
/// Deactivates the screen. Called when the game is being deactivated due to pausing or tombstoning.
/// </summary>
public virtual void Deactivate() { }
/// <summary>
/// Unload content for the screen. Called when the screen is removed from the screen manager.
/// </summary>
public virtual void Unload()
{
if (content != null)
content.Unload();
content = null;
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
_otherScreenHasFocus = otherScreenHasFocus;
if (_isExiting)
{
// If the screen is going away to die, it should transition off.
_screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, _transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, _transitionOffTime, 1))
{
// Still busy transitioning.
_screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
_screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, _transitionOnTime, -1))
{
// Still busy transitioning.
_screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
_screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds);
// Update the transition position.
TransitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if (((direction < 0) && (TransitionPosition <= 0)) ||
((direction > 0) && (TransitionPosition >= 1)))
{
TransitionPosition = MathHelper.Clamp(TransitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(GameTime gameTime, InputService input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime) { }
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
_isExiting = true;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Authentication;
using System.Security.Permissions;
namespace System.DirectoryServices.AccountManagement
{
abstract public class PrincipalException : SystemException
{
internal PrincipalException() : base() { }
internal PrincipalException(string message) : base(message) { }
internal PrincipalException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PrincipalException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
public class MultipleMatchesException : PrincipalException
{
public MultipleMatchesException() : base() { }
public MultipleMatchesException(string message) : base(message) { }
public MultipleMatchesException(string message, Exception innerException) :
base(message, innerException)
{ }
protected MultipleMatchesException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
public class NoMatchingPrincipalException : PrincipalException
{
public NoMatchingPrincipalException() : base() { }
public NoMatchingPrincipalException(string message) : base(message) { }
public NoMatchingPrincipalException(string message, Exception innerException) :
base(message, innerException)
{ }
protected NoMatchingPrincipalException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
public class PasswordException : PrincipalException
{
public PasswordException() : base() { }
public PasswordException(string message) : base(message) { }
public PasswordException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PasswordException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
public class PrincipalExistsException : PrincipalException
{
public PrincipalExistsException() : base() { }
public PrincipalExistsException(string message) : base(message) { }
public PrincipalExistsException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PrincipalExistsException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
public class PrincipalServerDownException : PrincipalException
{
private int _errorCode = 0;
private string _serverName = null;
public PrincipalServerDownException() : base() { }
public PrincipalServerDownException(string message) : base(message) { }
public PrincipalServerDownException(string message, Exception innerException) :
base(message, innerException)
{ }
public PrincipalServerDownException(string message, int errorCode) : base(message)
{
_errorCode = errorCode;
}
public PrincipalServerDownException(string message, Exception innerException, int errorCode) : base(message, innerException)
{
_errorCode = errorCode;
}
public PrincipalServerDownException(string message, Exception innerException, int errorCode, string serverName) : base(message, innerException)
{
_errorCode = errorCode;
_serverName = serverName;
}
protected PrincipalServerDownException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
public class PrincipalOperationException : PrincipalException
{
private int _errorCode = 0;
public PrincipalOperationException() : base() { }
public PrincipalOperationException(string message) : base(message) { }
public PrincipalOperationException(string message, Exception innerException) :
base(message, innerException)
{ }
public PrincipalOperationException(string message, int errorCode) : base(message)
{
_errorCode = errorCode;
}
public PrincipalOperationException(string message, Exception innerException, int errorCode) : base(message, innerException)
{
_errorCode = errorCode;
}
protected PrincipalOperationException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
public int ErrorCode
{
get
{
return _errorCode;
}
}
}
internal class ExceptionHelper
{
// Put a private constructor because this class should only be used as static methods
private ExceptionHelper() { }
private static int s_ERROR_NOT_ENOUGH_MEMORY = 8; // map to outofmemory exception
private static int s_ERROR_OUTOFMEMORY = 14; // map to outofmemory exception
private static int s_ERROR_DS_DRA_OUT_OF_MEM = 8446; // map to outofmemory exception
private static int s_ERROR_NO_SUCH_DOMAIN = 1355; // map to ActiveDirectoryServerDownException
private static int s_ERROR_ACCESS_DENIED = 5; // map to UnauthorizedAccessException
private static int s_ERROR_NO_LOGON_SERVERS = 1311; // map to ActiveDirectoryServerDownException
private static int s_ERROR_DS_DRA_ACCESS_DENIED = 8453; // map to UnauthorizedAccessException
private static int s_RPC_S_OUT_OF_RESOURCES = 1721; // map to outofmemory exception
internal static int RPC_S_SERVER_UNAVAILABLE = 1722; // map to ActiveDirectoryServerDownException
internal static int RPC_S_CALL_FAILED = 1726; // map to ActiveDirectoryServerDownException
// internal static int ERROR_DS_DRA_BAD_DN = 8439; //fix error CS0414: Warning as Error: is assigned but its value is never used
// internal static int ERROR_DS_NAME_UNPARSEABLE = 8350; //fix error CS0414: Warning as Error: is assigned but its value is never used
// internal static int ERROR_DS_UNKNOWN_ERROR = 8431; //fix error CS0414: Warning as Error: is assigned but its value is never used
// public static uint ERROR_HRESULT_ACCESS_DENIED = 0x80070005; //fix error CS0414: Warning as Error: is assigned but its value is never used
public static uint ERROR_HRESULT_LOGON_FAILURE = 0x8007052E;
public static uint ERROR_HRESULT_CONSTRAINT_VIOLATION = 0x8007202f;
public static uint ERROR_LOGON_FAILURE = 0x31;
// public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used
//
// This method maps some common COM Hresults to
// existing clr exceptions
//
internal static Exception GetExceptionFromCOMException(COMException e)
{
Exception exception;
int errorCode = e.ErrorCode;
string errorMessage = e.Message;
//
// Check if we can throw a more specific exception
//
if (errorCode == unchecked((int)0x80070005))
{
//
// Access Denied
//
exception = new UnauthorizedAccessException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052))
{
//
// Password does not meet complexity requirements or old password does not match or policy restriction has been enforced.
//
exception = new PasswordException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392))
{
//
// Principal already exists
//
exception = new PrincipalExistsException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007052e))
{
//
// Logon Failure
//
exception = new AuthenticationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007202f))
{
//
// Constraint Violation
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80072035))
{
//
// Unwilling to perform
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80070008))
{
//
// No Memory
//
exception = new OutOfMemoryException();
}
else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f)))
{
exception = new PrincipalServerDownException(errorMessage, e, errorCode, null);
}
else
{
//
// Wrap the exception in a generic OperationException
//
exception = new PrincipalOperationException(errorMessage, e, errorCode);
}
return exception;
}
[System.Security.SecuritySafeCritical]
internal static Exception GetExceptionFromErrorCode(int errorCode)
{
return GetExceptionFromErrorCode(errorCode, null);
}
[System.Security.SecurityCritical]
internal static Exception GetExceptionFromErrorCode(int errorCode, string targetName)
{
string errorMsg = GetErrorMessage(errorCode, false);
if ((errorCode == s_ERROR_ACCESS_DENIED) || (errorCode == s_ERROR_DS_DRA_ACCESS_DENIED))
return new UnauthorizedAccessException(errorMsg);
else if ((errorCode == s_ERROR_NOT_ENOUGH_MEMORY) || (errorCode == s_ERROR_OUTOFMEMORY) || (errorCode == s_ERROR_DS_DRA_OUT_OF_MEM) || (errorCode == s_RPC_S_OUT_OF_RESOURCES))
return new OutOfMemoryException();
else if ((errorCode == s_ERROR_NO_LOGON_SERVERS) || (errorCode == s_ERROR_NO_SUCH_DOMAIN) || (errorCode == RPC_S_SERVER_UNAVAILABLE) || (errorCode == RPC_S_CALL_FAILED))
{
return new PrincipalServerDownException(errorMsg, errorCode);
}
else
{
return new PrincipalOperationException(errorMsg, errorCode);
}
}
[System.Security.SecurityCritical]
internal static string GetErrorMessage(int errorCode, bool hresult)
{
uint temp = (uint)errorCode;
if (!hresult)
{
temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000));
}
string errorMsg = "";
StringBuilder sb = new StringBuilder(256);
int result = UnsafeNativeMethods.FormatMessageW(UnsafeNativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS |
UnsafeNativeMethods.FORMAT_MESSAGE_FROM_SYSTEM |
UnsafeNativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY,
IntPtr.Zero, (int)temp, 0, sb, sb.Capacity + 1, IntPtr.Zero);
if (result != 0)
{
errorMsg = sb.ToString(0, result);
}
else
{
errorMsg = StringResources.DSUnknown + Convert.ToString(temp, 16);
}
return errorMsg;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Web.UI.WebControls;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.Events;
using GuruComponents.Netrix.WebEditing.Behaviors;
using GuruComponents.Netrix.WebEditing.Documents;
using GuruComponents.Netrix.WebEditing.Styles;
using GuruComponents.Netrix.UserInterface.TypeConverters;
using TE=GuruComponents.Netrix.UserInterface.TypeEditors;
using GuruComponents.Netrix.UserInterface.TypeEditors;
using System.ComponentModel.Design;
using GuruComponents.Netrix.Designer;
using System.Web.UI;
using GuruComponents.Netrix.WebEditing.Elements;
namespace GuruComponents.Netrix.XmlDesigner
{
/// <summary>
/// The purpose of this class is to deal with the events a control will
/// fire at design time.
/// </summary>
sealed class ViewElementEventSink
{
private IElement _element;
private ConnectionPointCookie _eventSinkCookie;
private Interop.IHTMLElement _baseElement;
private class HtmlEvents
{
protected Interop.IHTMLEventObj _eventobj;
protected Interop.IHTMLElement _baseElement;
protected IElement _element;
private Interop.IHTMLWindow2 window;
protected HtmlEvents(IElement _element)
{
this._baseElement = ((ViewElement)_element).GetBaseElement();
this._element = _element;
Interop.IHTMLDocument2 _document = _element.HtmlEditor.GetActiveDocument(false);
if (_document == null) return;
window = _document.GetParentWindow();
}
/// <summary>
/// This method checks whether the element has been disposed during the call.
/// </summary>
/// <returns>Returns the return value set within the event handler, or false if already disposed.</returns>
protected bool GetSafeReturn()
{
if (((ViewElement)_element).IsDisposed)
return false;
else
return Convert.ToBoolean(_eventobj.returnValue == null ? true : _eventobj.returnValue);
}
protected bool GetEventObject()
{
try
{
// native event object
_eventobj = window.@event;
if (_eventobj != null && _eventobj.srcElement != null && (((ViewElement)_element).IsDisposed) == false)
{
System.Diagnostics.Debug.WriteLine(_eventobj.srcElement.GetTagName(), _eventobj.type);
_eventobj.cancelBubble = true;
return true;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message, "GetEvent::Exception");
}
return false;
}
}
/// <summary>
///
/// </summary>
private class HTMLSpecialEvents : HtmlEvents,
Interop.IHTMLAnchorEvents,
Interop.IHTMLAreaEvents,
Interop.IHTMLButtonElementEvents,
Interop.IHTMLControlElementEvents,
Interop.IHTMLDocumentEvents,
Interop.IHTMLElementEvents,
Interop.IHTMLFormElementEvents,
Interop.IHTMLFrameSiteEvents,
Interop.IHTMLImgEvents,
Interop.IHTMLInputFileElementEvents,
Interop.IHTMLInputImageEvents,
Interop.IHTMLInputTextElementEvents,
Interop.IHTMLLabelEvents,
Interop.IHTMLLinkElementEvents,
Interop.IHTMLMapEvents,
Interop.IHTMLObjectElementEvents,
Interop.IHTMLOptionButtonElementEvents,
Interop.IHTMLScriptEvents,
Interop.IHTMLSelectElementEvents,
Interop.IHTMLStyleElementEvents,
Interop.IHTMLTableEvents,
Interop.IHTMLTextContainerEvents
{
public HTMLSpecialEvents(IElement e)
: base(e)
{
}
#region IHTMLXXXEvents Member
# region DataSet Events -- not implemented
public void onrowsdelete()
{
//((ViewElement) _element).OnRowsDelete(new DocumentEventArgs(GetEventObject(), _element));
}
public void onrowsinserted()
{
//((ViewElement) _element).OnRowsInserted(new DocumentEventArgs(GetEventObject(), _element));
}
public void oncellchange()
{
//((ViewElement) _element).OnCellChange(new DocumentEventArgs(GetEventObject(), _element));
}
public void onreadystatechange()
{
//((ViewElement) _element).OnReadyStateChange(new DocumentEventArgs(GetEventObject(), _element));
}
public Boolean onbeforeupdate()
{
//((ViewElement) _element).OnBeforeUpdate(new DocumentEventArgs(GetEventObject(), _element));
return false;
}
public void onafterupdate()
{
//((ViewElement) _element).OnAfterUpdate(new DocumentEventArgs(GetEventObject(), _element));
}
public Boolean onerrorupdate()
{
//((ViewElement) _element).OnErrorUpdate(new DocumentEventArgs(GetEventObject(), _element));
return false;
}
public Boolean onrowexit()
{
//((ViewElement) _element).OnRowExit(new DocumentEventArgs(GetEventObject(), _element));
return false;
}
public void onrowenter()
{
//((ViewElement) _element).OnRowEnter(new DocumentEventArgs(GetEventObject(), _element));
}
public void ondatasetchanged()
{
//((ViewElement) _element).OnDatasetChanged(new DocumentEventArgs(GetEventObject(), _element));
}
public void ondataavailable()
{
//((ViewElement) _element).OnDataAvailable(new DocumentEventArgs(GetEventObject(), _element));
}
public void ondatasetcomplete()
{
//((ViewElement) _element).OnDatasetComplete(new DocumentEventArgs(GetEventObject(), _element));
}
# endregion
# region IE related high level events -- not supported
public Boolean onhelp()
{
return false;
}
public bool onstop()
{
return true;
}
public void onpage()
{
}
public void onabort()
{
}
public bool onreset()
{
return false;
}
public bool onsubmit()
{
return false;
}
# endregion
# region Supported Events -- Canncellable
public Boolean onclick()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeClick(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondblclick()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDblClick(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onkeypress()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeKeyPress(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondragstart()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDragStart(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondrag()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDrag(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondragenter()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDragEnter(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondragover()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDragOver(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean ondrop()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDrop(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onbeforecut()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBeforeCut(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean oncut()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeCut(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onbeforecopy()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBeforeCopy(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean oncopy()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeCopy(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onbeforepaste()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBeforePaste(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onpaste()
{
if (GetEventObject())
{
((ViewElement)_element).InvokePaste(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean oncontextmenu()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeContextMenu(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onbeforedeactivate()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBeforeDeactivate(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onbeforeactivate()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBeforeActivate(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean oncontrolselect()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeControlSelect(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onmovestart()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMoveStart(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onselectstart()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeSelectStart(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onresizestart()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeResizeStart(_eventobj);
return GetSafeReturn();
}
return true;
}
public Boolean onmousewheel()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseWheel(_eventobj);
return GetSafeReturn();
}
return true;
}
bool Interop.IHTMLObjectElementEvents.onerror()
{
return true;
}
public Boolean onchange()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeChange(_eventobj);
return GetSafeReturn();
}
return true;
}
# endregion
# region Supported Events -- Not canncellable
public void onkeydown()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeKeyDown(_eventobj);
}
}
public void onkeyup()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeKeyUp(_eventobj);
}
}
public void onmouseout()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseOut(_eventobj);
}
}
public void onmouseover()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseOver(_eventobj);
}
}
public void onmousemove()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseMove(_eventobj);
}
}
public void onmousedown()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseDown(_eventobj);
}
}
public void onmouseup()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseUp(_eventobj);
}
}
public void onfilterchange()
{
}
public void onlosecapture()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeLoseCapture(_eventobj);
}
}
public void onpropertychange()
{
if (GetEventObject())
{
((ViewElement)_element).InvokePropertyChange(_eventobj);
}
}
public void onscroll()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeScroll(_eventobj);
}
}
public void onfocus()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeFocus(_eventobj);
}
}
public void onblur()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeBlur(_eventobj);
}
}
public void onresize()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeResize(_eventobj);
}
}
public void ondragend()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDragEnd(_eventobj);
}
}
public void ondragleave()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDragLeave(_eventobj);
}
}
public void onbeforeeditfocus()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeEditFocus(_eventobj);
}
}
public void onlayoutcomplete()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeLayoutComplete(_eventobj);
}
}
public void onmove()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMove(_eventobj);
}
}
public void onmoveend()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMoveEnd(_eventobj);
}
}
public void onresizeend()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeResizeEnd(_eventobj);
}
}
public void onmouseenter()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseEnter(_eventobj);
}
}
public void onmouseleave()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeMouseLeave(_eventobj);
}
}
public void onactivate()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeActivate(_eventobj);
}
}
public void ondeactivate()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeDeactivate(_eventobj);
}
}
public void onfocusin()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeFocusIn(_eventobj);
}
}
public void onfocusout()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeFocusOut(_eventobj);
}
}
public void onload()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeLoad(_eventobj);
}
}
public void onerror()
{
}
void Interop.IHTMLSelectElementEvents.onchange()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeChange(_eventobj);
}
}
void Interop.IHTMLTextContainerEvents.onchange()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeChange(_eventobj);
}
}
public void onselect()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeSelect(_eventobj);
}
}
public void onselectionchange()
{
if (GetEventObject())
{
((ViewElement)_element).InvokeSelectionChange(_eventobj);
}
}
# endregion Supported Events -- Not canncellable
#endregion
}
public ViewElementEventSink(IElement element)
{
this._element = element;
}
/// <summary>
/// Connects the specified control and its underlying element to the event sink.
/// </summary>
public void Connect()
{
this._baseElement = ((ViewElement)this._element).GetBaseElement();
string scope = ((Interop.IHTMLElement2)_baseElement).GetScopeName();
if (!scope.Equals("HTML")) return; // do not attach other than HTML controls
try
{
Guid guid = Guid.Empty;
switch (_element.TagName.ToLower())
{
default:
// element
guid = typeof(Interop.IHTMLElementEvents).GUID;
break;
case "":
// generic/unknown elements
guid = Guid.Empty;
break;
case "body":
case "caption":
case "textarea":
case "td":
case "fieldset":
guid = typeof(Interop.IHTMLTextContainerEvents).GUID;
break;
case "hr":
case "tr":
guid = typeof(Interop.IHTMLControlElementEvents).GUID;
break;
case "a":
guid = typeof(Interop.IHTMLAnchorEvents).GUID;
break;
case "area":
guid = typeof(Interop.IHTMLAreaEvents).GUID;
break;
case "button":
guid = typeof(Interop.IHTMLButtonElementEvents).GUID;
break;
case "form":
guid = typeof(Interop.IHTMLFormElementEvents).GUID;
break;
case "img":
guid = typeof(Interop.IHTMLImgEvents).GUID;
break;
case "label":
guid = typeof(Interop.IHTMLLabelEvents).GUID;
break;
case "link":
guid = typeof(Interop.IHTMLLinkElementEvents).GUID;
break;
case "map":
guid = typeof(Interop.IHTMLMapEvents).GUID;
break;
case "marquee":
guid = typeof(Interop.IHTMLMarqueeElementEvents).GUID;
break;
case "object":
guid = typeof(Interop.IHTMLObjectElementEvents).GUID;
break;
case "script":
guid = typeof(Interop.IHTMLScriptEvents).GUID;
break;
case "select":
guid = typeof(Interop.IHTMLSelectElementEvents).GUID;
break;
case "style":
guid = typeof(Interop.IHTMLStyleElementEvents).GUID;
break;
case "table":
guid = typeof(Interop.IHTMLTableEvents).GUID;
break;
case "input":
object att = _element.GetAttribute("type");
{
switch (att.ToString().ToLower())
{
case "file":
guid = typeof(Interop.IHTMLInputFileElementEvents).GUID;
break;
case "image":
guid = typeof(Interop.IHTMLInputImageEvents).GUID;
break;
case "text":
guid = typeof(Interop.IHTMLInputTextElementEvents).GUID;
break;
case "checkbox":
case "radio":
guid = typeof(Interop.IHTMLOptionButtonElementEvents).GUID;
break;
case "button":
case "submit":
case "reset":
guid = typeof(Interop.IHTMLButtonElementEvents).GUID;
break;
default:
// control
guid = typeof(Interop.IHTMLControlElementEvents).GUID;
break;
}
break;
}
}
HTMLSpecialEvents specialEvents = new HTMLSpecialEvents(_element);
if (!guid.Equals(Guid.Empty))
{
this._eventSinkCookie = new ConnectionPointCookie(this._baseElement, specialEvents, guid, false);
}
}
catch (Exception)
{
}
}
public void Disconnect()
{
if (this._eventSinkCookie != null)
{
this._eventSinkCookie.Disconnect();
this._eventSinkCookie = null;
}
this._element = null;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using SimpleContainer.Configuration;
using SimpleContainer.Helpers;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
namespace SimpleContainer.Implementation
{
internal class SimpleContainer : IContainer
{
private readonly Func<ServiceName, ContainerServiceId> createId = _ => new ContainerServiceId();
private readonly ConcurrentDictionary<ServiceName, ContainerServiceId> instanceCache =
new ConcurrentDictionary<ServiceName, ContainerServiceId>();
private readonly ConcurrentDictionary<ServiceName, Func<object>> factoryCache =
new ConcurrentDictionary<ServiceName, Func<object>>();
private readonly DependenciesInjector dependenciesInjector;
private bool disposed;
private readonly List<ImplementationSelector> implementationSelectors;
internal ConfigurationRegistry Configuration { get; private set; }
private readonly ContainerContext containerContext;
private readonly LogError errorLogger;
public SimpleContainer(ConfigurationRegistry configurationRegistry, ContainerContext containerContext,
LogError errorLogger)
{
Configuration = configurationRegistry;
implementationSelectors = configurationRegistry.GetImplementationSelectors();
dependenciesInjector = new DependenciesInjector(this);
this.containerContext = containerContext;
this.errorLogger = errorLogger;
}
public ResolvedService Resolve(Type type, IEnumerable<string> contracts)
{
EnsureNotDisposed();
if (type == null)
throw new ArgumentNullException("type");
var t = type.UnwrapEnumerable();
return Resolve(t, contracts, t != type);
}
//todo remove this ugly hack
internal ResolvedService Resolve(Type type, IEnumerable<string> contracts, bool isEnumerable)
{
EnsureNotDisposed();
if (type == null)
throw new ArgumentNullException("type");
var name = CreateServiceName(type, contracts);
ContainerService result;
if (ContainerService.ThreadInitializing)
{
const string formatMessage = "attempt to resolve [{0}] is prohibited to prevent possible deadlocks";
var message = string.Format(formatMessage, name.Type.FormatName());
result = ContainerService.Error(name, message);
}
else
{
var id = instanceCache.GetOrAdd(name, createId);
if (id.TryGet(out result))
return new ResolvedService(result, containerContext, isEnumerable);
var activation = ResolutionContext.Push(this);
try
{
result = ResolveCore(name, false, null, activation.activated);
}
finally
{
PopResolutionContext(activation, result, isEnumerable);
}
}
return new ResolvedService(result, containerContext, isEnumerable);
}
private void PopResolutionContext(ResolutionContext.ResolutionContextActivation activation,
ContainerService containerService, bool isEnumerable)
{
ResolutionContext.Pop(activation);
if (activation.previous == null)
return;
var resultDependency = containerService.AsDependency(containerContext, "() => " + containerService.Type.FormatName(),isEnumerable);
if (activation.activated.Container != activation.previous.Container)
resultDependency.Comment = "container boundary";
activation.previous.TopBuilder.AddDependency(resultDependency, false);
}
public object Create(Type type, IEnumerable<string> contracts, object arguments)
{
EnsureNotDisposed();
if (type == null)
throw new ArgumentNullException("type");
var name = CreateServiceName(type.UnwrapEnumerable(), contracts);
return Create(name, name.Type != type, arguments);
}
internal object Create(ServiceName name, bool isEnumerable, object arguments)
{
Func<object> compiledFactory;
var hasPendingResolutionContext = ResolutionContext.HasPendingResolutionContext;
if (arguments == null && factoryCache.TryGetValue(name, out compiledFactory) && !hasPendingResolutionContext)
return compiledFactory();
var activation = ResolutionContext.Push(this);
ContainerService result = null;
List<string> oldContracts = null;
try
{
if (hasPendingResolutionContext)
{
oldContracts = activation.activated.Contracts.Replace(name.Contracts);
name = new ServiceName(name.Type);
}
result = ResolveCore(name, true, ObjectAccessor.Get(arguments), activation.activated);
}
finally
{
if (oldContracts != null)
activation.activated.Contracts.Restore(oldContracts);
PopResolutionContext(activation, result, isEnumerable);
}
if (!hasPendingResolutionContext)
result.EnsureInitialized(containerContext, result);
result.CheckStatusIsGood(containerContext);
if (isEnumerable)
return result.GetAllValues();
result.CheckSingleValue(containerContext);
return result.Instances[0].Instance;
}
private ServiceConfiguration GetConfigurationWithoutContracts(Type type)
{
return GetConfigurationOrNull(type, new ContractsList());
}
internal ServiceConfiguration GetConfiguration(Type type, ResolutionContext context)
{
return GetConfigurationOrNull(type, context.Contracts) ?? ServiceConfiguration.empty;
}
private ServiceConfiguration GetConfigurationOrNull(Type type, ContractsList contracts)
{
var result = Configuration.GetConfigurationOrNull(type, contracts);
if (result == null && type.IsGenericType)
result = Configuration.GetConfigurationOrNull(type.GetDefinition(), contracts);
return result;
}
public IEnumerable<Type> GetImplementationsOf(Type interfaceType)
{
EnsureNotDisposed();
if (interfaceType == null)
throw new ArgumentNullException("interfaceType");
var interfaceConfiguration = GetConfigurationWithoutContracts(interfaceType);
if (interfaceConfiguration != null && interfaceConfiguration.ImplementationTypes != null)
return interfaceConfiguration.ImplementationTypes;
return containerContext.typesList.InheritorsOf(interfaceType)
.Where(delegate(Type type)
{
var implementationConfiguration = GetConfigurationWithoutContracts(type);
return implementationConfiguration == null || !implementationConfiguration.DontUseIt;
})
.ToArray();
}
public BuiltUpService BuildUp(object target, IEnumerable<string> contracts)
{
EnsureNotDisposed();
if (target == null)
throw new ArgumentNullException("target");
return dependenciesInjector.BuildUp(CreateServiceName(target.GetType(), contracts), target);
}
private static ServiceName CreateServiceName(Type type, IEnumerable<string> contracts)
{
var contractsArray = contracts == null
? InternalHelpers.emptyStrings
: (contracts is string[] ? (string[]) contracts : contracts.ToArray());
for (var i = 0; i < contractsArray.Length; i++)
{
var contract = contractsArray[i];
if (string.IsNullOrEmpty(contract))
{
var message = string.Format("invalid contracts [{0}] - empty ones found", contractsArray.JoinStrings(","));
throw new SimpleContainerException(message);
}
for (var j = 0; j < i; j++)
if (contractsArray[j].EqualsIgnoringCase(contract))
{
var message = string.Format("invalid contracts [{0}] - duplicates found", contractsArray.JoinStrings(","));
throw new SimpleContainerException(message);
}
}
return ServiceName.Parse(type, contractsArray);
}
private IEnumerable<ServiceInstance> GetInstanceCache(Type interfaceType)
{
var seen = new HashSet<object>();
var target = new List<ServiceInstance>();
foreach (var wrap in instanceCache.Values)
{
ContainerService service;
if (wrap.TryGet(out service))
service.CollectInstances(interfaceType, seen, target);
}
return target;
}
public IContainer Clone(Action<ContainerConfigurationBuilder> configure)
{
EnsureNotDisposed();
return new SimpleContainer(Configuration.Apply(containerContext.typesList, configure), containerContext, null);
}
public Type[] AllTypes
{
get { return containerContext.AllTypes(); }
}
internal ContainerService ResolveCore(ServiceName name, bool createNew, IObjectAccessor arguments, ResolutionContext context)
{
var pushedContracts = context.Contracts.Push(name.Contracts);
var declaredName = new ServiceName(name.Type, context.Contracts.Snapshot());
if (context.HasCycle(declaredName))
{
var message = string.Format("cyclic dependency for service [{0}], stack\r\n{1}",
declaredName.Type.FormatName(), context.FormatStack() + "\r\n\t" + declaredName);
context.Contracts.RemoveLast(pushedContracts.pushedContractsCount);
return ContainerService.Error(declaredName, message);
}
if (!pushedContracts.isOk)
{
const string messageFormat = "contract [{0}] already declared, stack\r\n{1}";
var message = string.Format(messageFormat, pushedContracts.duplicatedContractName,
context.FormatStack() + "\r\n\t" + name);
context.Contracts.RemoveLast(pushedContracts.pushedContractsCount);
return ContainerService.Error(name, message);
}
context.ConstructingServices.Add(declaredName);
ServiceConfiguration configuration = null;
Exception configurationException = null;
try
{
configuration = GetConfiguration(declaredName.Type, context);
}
catch (Exception e)
{
configurationException = e;
}
var actualName = configuration != null && configuration.FactoryDependsOnTarget && context.Stack.Count > 0
? declaredName.AddContracts(context.TopBuilder.Type.FormatName())
: declaredName;
ContainerServiceId id = null;
if (!createNew)
{
id = instanceCache.GetOrAdd(actualName, createId);
var acquireResult = id.AcquireInstantiateLock();
if (!acquireResult.acquired)
{
context.ConstructingServices.Remove(declaredName);
context.Contracts.RemoveLast(pushedContracts.pushedContractsCount);
return acquireResult.alreadyConstructedService;
}
}
var builder = new ContainerService.Builder(actualName);
context.Stack.Add(builder);
builder.Context = context;
builder.DeclaredContracts = actualName.Contracts;
if (configuration == null)
builder.SetError(configurationException);
else
{
builder.SetConfiguration(configuration);
builder.ExpandedUnions = context.Contracts.TryExpandUnions(Configuration);
if (builder.ExpandedUnions.HasValue)
{
var poppedContracts = context.Contracts.PopMany(builder.ExpandedUnions.Value.contracts.Length);
foreach (var c in builder.ExpandedUnions.Value.contracts.CartesianProduct())
{
var childService = ResolveCore(new ServiceName(name.Type, c), createNew, arguments, context);
builder.LinkTo(containerContext, childService, null);
if (builder.Status.IsBad())
break;
}
context.Contracts.PushNoCheck(poppedContracts);
}
else
{
builder.CreateNew = createNew;
builder.Arguments = arguments;
Instantiate(builder);
}
}
context.ConstructingServices.Remove(declaredName);
context.Contracts.RemoveLast(pushedContracts.pushedContractsCount);
context.Stack.RemoveLast();
var result = builder.GetService();
if (id != null)
id.ReleaseInstantiateLock(builder.Context.AnalizeDependenciesOnly ? null : result);
return result;
}
internal void Instantiate(ContainerService.Builder builder)
{
LifestyleAttribute lifestyle;
if (builder.Type.IsSimpleType())
builder.SetError("can't create simple type");
else if (builder.Type == typeof (IContainer))
builder.AddInstance(this, false, false);
else if (builder.Configuration.ImplementationAssigned)
builder.AddInstance(builder.Configuration.Implementation, builder.Configuration.ContainerOwnsInstance, true);
else if (builder.Configuration.Factory != null)
{
if (!builder.Context.AnalizeDependenciesOnly)
builder.CreateInstanceBy(CallTarget.F(builder.Configuration.Factory), builder.Configuration.ContainerOwnsInstance);
}
else if (builder.Type.IsValueType)
builder.SetError("can't create value type");
else if (builder.Type.IsGenericType && builder.Type.ContainsGenericParameters)
builder.SetError("can't create open generic");
else if (!builder.CreateNew && builder.Type.TryGetCustomAttribute(out lifestyle) &&
lifestyle.Lifestyle == Lifestyle.PerRequest)
{
const string messageFormat = "service [{0}] with PerRequest lifestyle can't be resolved, use Func<{0}> instead";
builder.SetError(string.Format(messageFormat, builder.Type.FormatName()));
}
else if (builder.Type.IsAbstract)
InstantiateInterface(builder);
else
InstantiateImplementation(builder);
}
private void ApplySelectors(HashSet<ImplementationType> implementations, ContainerService.Builder builder)
{
if (builder.Configuration != ServiceConfiguration.empty)
return;
if (implementationSelectors.Count == 0)
return;
var selectorDecisions = new List<ImplementationSelectorDecision>();
var typesArray = implementations.Select(x => x.type).ToArray();
foreach (var s in implementationSelectors)
s(builder.Type, typesArray, selectorDecisions);
foreach (var decision in selectorDecisions)
{
var item = new ImplementationType
{
type = decision.target,
comment = decision.comment,
accepted = decision.action == ImplementationSelectorDecision.Action.Include
};
implementations.Replace(item);
}
}
private void InstantiateInterface(ContainerService.Builder builder)
{
HashSet<ImplementationType> implementationTypes;
try
{
implementationTypes = GetImplementationTypes(builder);
}
catch (Exception e)
{
builder.SetError(e);
return;
}
ApplySelectors(implementationTypes, builder);
if (implementationTypes.Count == 0)
{
builder.SetComment("has no implementations");
return;
}
Func<object> factory = null;
var canUseFactory = true;
foreach (var implementationType in implementationTypes)
if (implementationType.accepted)
{
var implementationService = ResolveCore(ServiceName.Parse(implementationType.type, InternalHelpers.emptyStrings),
builder.CreateNew, builder.Arguments, builder.Context);
builder.LinkTo(containerContext, implementationService, implementationType.comment);
if (builder.CreateNew && builder.Arguments == null &&
implementationService.Status == ServiceStatus.Ok && canUseFactory)
if (factory == null)
{
if (!factoryCache.TryGetValue(implementationService.Name, out factory))
canUseFactory = false;
}
else
canUseFactory = false;
if (builder.Status.IsBad())
return;
}
else
{
var dependency = containerContext.NotResolved(null, implementationType.type.FormatName());
dependency.Comment = implementationType.comment;
builder.AddDependency(dependency, true);
}
builder.EndResolveDependencies();
if (factory != null && canUseFactory)
factoryCache.TryAdd(builder.GetFinalName(), factory);
}
private HashSet<ImplementationType> GetImplementationTypes(ContainerService.Builder builder)
{
var result = new HashSet<ImplementationType>();
var candidates = builder.Configuration.ImplementationTypes ??
containerContext.typesList.InheritorsOf(builder.Type.GetDefinition());
var implementationTypesAreExplicitlyConfigured = builder.Configuration.ImplementationTypes != null;
foreach (var implType in candidates)
{
if (!implementationTypesAreExplicitlyConfigured)
{
var configuration = GetConfiguration(implType, builder.Context);
if (configuration.IgnoredImplementation || implType.IsDefined("IgnoredImplementationAttribute"))
result.Add(new ImplementationType
{
type = implType,
comment = "IgnoredImplementation",
accepted = false
});
}
if (!implType.IsGenericType)
{
if (!builder.Type.IsGenericType || builder.Type.IsAssignableFrom(implType))
result.Add(ImplementationType.Accepted(implType));
}
else if (!implType.ContainsGenericParameters)
result.Add(ImplementationType.Accepted(implType));
else
{
var mapped = containerContext.genericsAutoCloser.AutoCloseDefinition(implType);
foreach (var type in mapped)
if (builder.Type.IsAssignableFrom(type))
result.Add(ImplementationType.Accepted(type));
if (builder.Type.IsGenericType)
{
var implInterfaces = implType.ImplementationsOf(builder.Type.GetGenericTypeDefinition());
foreach (var implInterface in implInterfaces)
{
var closed = implType.TryCloseByPattern(implInterface, builder.Type);
if (closed != null)
result.Add(ImplementationType.Accepted(closed));
}
}
if (builder.Arguments == null)
continue;
var serviceConstructor = implType.GetConstructor();
if (!serviceConstructor.isOk)
continue;
foreach (var formalParameter in serviceConstructor.value.GetParameters())
{
if (!formalParameter.ParameterType.ContainsGenericParameters)
continue;
ValueWithType parameterValue;
if (!builder.Arguments.TryGet(formalParameter.Name, out parameterValue))
continue;
var parameterType = parameterValue.value == null ? parameterValue.type : parameterValue.value.GetType();
var implInterfaces = formalParameter.ParameterType.IsGenericParameter
? new List<Type>(1) {parameterType}
: parameterType.ImplementationsOf(formalParameter.ParameterType.GetGenericTypeDefinition());
foreach (var implInterface in implInterfaces)
{
var closedItem = implType.TryCloseByPattern(formalParameter.ParameterType, implInterface);
if (closedItem != null)
result.Add(ImplementationType.Accepted(closedItem));
}
}
}
}
return result;
}
public IEnumerable<Type> GetDependencies(Type type)
{
EnsureNotDisposed();
if (type.IsDelegate())
return Enumerable.Empty<Type>();
if (!type.IsAbstract)
{
var result = dependenciesInjector.GetDependencies(type)
.Select(ReflectionHelpers.UnwrapEnumerable)
.ToArray();
if (result.Any())
return result;
}
var serviceConstructor = type.GetConstructor();
if (!serviceConstructor.isOk)
return Enumerable.Empty<Type>();
var typeConfiguration = GetConfigurationWithoutContracts(type);
return serviceConstructor.value.GetParameters()
.Where(p => typeConfiguration == null || typeConfiguration.GetOrNull(p) == null)
.Select(x => x.ParameterType)
.Select(ReflectionHelpers.UnwrapEnumerable)
.Where(p => GetConfigurationWithoutContracts(p) == null)
.Where(IsDependency);
}
private static bool IsDependency(Type type)
{
if (type.IsDelegate())
return false;
if (type.IsSimpleType())
return false;
if (type.IsArray && type.GetElementType().IsSimpleType())
return false;
return true;
}
private void InstantiateImplementation(ContainerService.Builder builder)
{
if (builder.DontUse())
{
builder.SetComment("DontUse");
return;
}
var result = FactoryCreator.TryCreate(builder) ?? LazyCreator.TryCreate(builder);
if (result != null)
{
builder.AddInstance(result, true, false);
return;
}
if (NestedFactoryCreator.TryCreate(builder))
return;
if (CtorFactoryCreator.TryCreate(builder))
return;
if (builder.Type.IsDelegate())
{
builder.SetError(string.Format("can't create delegate [{0}]", builder.Type.FormatName()));
return;
}
var constructor = builder.Type.GetConstructor();
if (!constructor.isOk)
{
builder.SetError(constructor.errorMessage);
return;
}
var formalParameters = constructor.value.GetParameters();
var actualArguments = new object[formalParameters.Length];
var hasServiceNameParameters = false;
for (var i = 0; i < formalParameters.Length; i++)
{
var formalParameter = formalParameters[i];
if (formalParameter.ParameterType == typeof (ServiceName))
{
hasServiceNameParameters = true;
continue;
}
var dependency = InstantiateDependency(formalParameter, builder).CastTo(formalParameter.ParameterType);
builder.AddDependency(dependency, false);
if (dependency.ContainerService != null)
builder.UnionUsedContracts(dependency.ContainerService);
if (builder.Status != ServiceStatus.Ok && !builder.Context.AnalizeDependenciesOnly)
return;
actualArguments[i] = dependency.Value;
}
foreach (var d in builder.Configuration.ImplicitDependencies)
{
var dependency = ResolveCore(ServiceName.Parse(d.Type, d.Contracts), false, null, builder.Context)
.AsDependency(containerContext, null, false);
dependency.Comment = "implicit";
builder.AddDependency(dependency, false);
if (dependency.ContainerService != null)
builder.UnionUsedContracts(dependency.ContainerService);
if (builder.Status != ServiceStatus.Ok)
return;
}
builder.EndResolveDependencies();
if (builder.Context.AnalizeDependenciesOnly)
return;
var dependenciesResolvedByArguments = builder.Arguments == null ? null : builder.Arguments.GetUsed();
List<string> unusedConfigurationKeys = null;
foreach (var k in builder.Configuration.GetUnusedDependencyKeys())
{
var resolvedByArguments = dependenciesResolvedByArguments != null &&
k.name != null &&
dependenciesResolvedByArguments.Contains(k.name);
if (resolvedByArguments)
continue;
if (unusedConfigurationKeys == null)
unusedConfigurationKeys = new List<string>();
unusedConfigurationKeys.Add(k.ToString());
}
if (unusedConfigurationKeys != null)
{
builder.SetError(string.Format("unused dependency configurations [{0}]", unusedConfigurationKeys.JoinStrings(",")));
return;
}
if (hasServiceNameParameters)
for (var i = 0; i < formalParameters.Length; i++)
if (formalParameters[i].ParameterType == typeof (ServiceName))
actualArguments[i] = builder.GetFinalName();
if (builder.CreateNew || builder.DeclaredContracts.Length == builder.FinalUsedContracts.Length)
{
builder.CreateInstanceBy(CallTarget.M(constructor.value, null, actualArguments), true);
if (builder.CreateNew && builder.Arguments == null)
{
var compiledConstructor = constructor.value.Compile();
factoryCache.TryAdd(builder.GetFinalName(), () =>
{
var instance = compiledConstructor(null, actualArguments);
var component = instance as IInitializable;
if (component != null)
component.Initialize();
return instance;
});
}
return;
}
var serviceForUsedContractsId = instanceCache.GetOrAdd(builder.GetFinalName(), createId);
var acquireResult = serviceForUsedContractsId.AcquireInstantiateLock();
if (acquireResult.acquired)
{
builder.CreateInstanceBy(CallTarget.M(constructor.value, null, actualArguments), true);
serviceForUsedContractsId.ReleaseInstantiateLock(builder.Context.AnalizeDependenciesOnly
? null
: builder.GetService());
}
else
builder.Reuse(acquireResult.alreadyConstructedService);
}
internal ServiceDependency InstantiateDependency(ParameterInfo formalParameter, ContainerService.Builder builder)
{
ValueWithType actualArgument;
if (builder.Arguments != null && builder.Arguments.TryGet(formalParameter.Name, out actualArgument))
return containerContext.Constant(formalParameter, actualArgument.value);
var parameters = builder.Configuration.ParametersSource;
object actualParameter;
if (parameters != null && parameters.TryGet(formalParameter.Name, formalParameter.ParameterType, out actualParameter))
return containerContext.Constant(formalParameter, actualParameter);
var dependencyConfiguration = builder.Configuration.GetOrNull(formalParameter);
Type implementationType = null;
if (dependencyConfiguration != null)
{
if (dependencyConfiguration.ValueAssigned)
return containerContext.Constant(formalParameter, dependencyConfiguration.Value);
if (dependencyConfiguration.Factory != null)
{
var dependencyBuilder = new ContainerService.Builder(new ServiceName(formalParameter.ParameterType))
{
Context = builder.Context,
DependencyName = formalParameter.Name
};
builder.Context.Stack.Add(dependencyBuilder);
dependencyBuilder.CreateInstanceBy(CallTarget.F(dependencyConfiguration.Factory), true);
builder.Context.Stack.RemoveLast();
return dependencyBuilder.GetService().AsDependency(containerContext, formalParameter.Name, false);
}
implementationType = dependencyConfiguration.ImplementationType;
}
implementationType = implementationType ?? formalParameter.ParameterType;
FromResourceAttribute resourceAttribute;
if (implementationType == typeof (Stream) && formalParameter.TryGetCustomAttribute(out resourceAttribute))
{
var resourceStream = builder.Type.Assembly.GetManifestResourceStream(builder.Type, resourceAttribute.Name);
if (resourceStream == null)
return containerContext.Error(null, formalParameter.Name,
"can't find resource [{0}] in namespace of [{1}], assembly [{2}]",
resourceAttribute.Name, builder.Type, builder.Type.Assembly.GetName().Name);
return containerContext.Resource(formalParameter, resourceAttribute.Name, resourceStream);
}
var dependencyName = ServiceName.Parse(implementationType.UnwrapEnumerable(),
InternalHelpers.ParseContracts(formalParameter));
if (dependencyName.Type.IsSimpleType())
{
if (!formalParameter.HasDefaultValue)
return containerContext.Error(null, formalParameter.Name,
"parameter [{0}] of service [{1}] is not configured",
formalParameter.Name, builder.Type.FormatName());
return containerContext.Constant(formalParameter, formalParameter.DefaultValue);
}
var resultService = ResolveCore(dependencyName, false, null, builder.Context);
if (resultService.Status.IsBad())
return containerContext.ServiceError(resultService);
var isEnumerable = dependencyName.Type != implementationType;
if (isEnumerable)
return containerContext.Service(resultService, resultService.GetAllValues());
if (resultService.Status == ServiceStatus.NotResolved)
{
if (formalParameter.HasDefaultValue)
return containerContext.Service(resultService, formalParameter.DefaultValue);
if (formalParameter.IsDefined<OptionalAttribute>() || formalParameter.IsDefined("CanBeNullAttribute"))
return containerContext.Service(resultService, null);
return containerContext.NotResolved(resultService);
}
return resultService.AsDependency(containerContext, null, false);
}
public void Dispose()
{
if (disposed)
return;
var exceptions = new List<SimpleContainerException>();
foreach (var disposable in GetInstanceCache(typeof (IDisposable)).Reverse())
{
try
{
DisposeService(disposable);
}
catch (SimpleContainerException e)
{
exceptions.Add(e);
}
}
disposed = true;
if (exceptions.Count > 0)
{
var error = new AggregateException("SimpleContainer dispose error", exceptions);
if (errorLogger == null)
throw error;
errorLogger(error.Message, error);
}
}
private static void DisposeService(ServiceInstance disposable)
{
try
{
disposable.ContainerService.disposing = true;
((IDisposable) disposable.Instance).Dispose();
}
catch (Exception e)
{
if (e is OperationCanceledException)
return;
var aggregateException = e as AggregateException;
if (aggregateException != null)
if (aggregateException.Flatten().InnerExceptions.All(x => x is OperationCanceledException))
return;
var instanceName = new ServiceName(disposable.Instance.GetType(), disposable.ContainerService.UsedContracts);
var message = string.Format("error disposing [{0}]", instanceName);
throw new SimpleContainerException(message, e);
}
finally
{
disposable.ContainerService.disposing = false;
}
}
private void EnsureNotDisposed()
{
if (disposed)
throw new ObjectDisposedException("SimpleContainer");
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.IO.Caching;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
namespace Neo
{
/// <summary>
/// A helper class that provides common functions.
/// </summary>
public static class Helper
{
private static readonly DateTime unixEpoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int BitLen(int w)
{
return (w < 1 << 15 ? (w < 1 << 7
? (w < 1 << 3 ? (w < 1 << 1
? (w < 1 << 0 ? (w < 0 ? 32 : 0) : 1)
: (w < 1 << 2 ? 2 : 3)) : (w < 1 << 5
? (w < 1 << 4 ? 4 : 5)
: (w < 1 << 6 ? 6 : 7)))
: (w < 1 << 11
? (w < 1 << 9 ? (w < 1 << 8 ? 8 : 9) : (w < 1 << 10 ? 10 : 11))
: (w < 1 << 13 ? (w < 1 << 12 ? 12 : 13) : (w < 1 << 14 ? 14 : 15)))) : (w < 1 << 23 ? (w < 1 << 19
? (w < 1 << 17 ? (w < 1 << 16 ? 16 : 17) : (w < 1 << 18 ? 18 : 19))
: (w < 1 << 21 ? (w < 1 << 20 ? 20 : 21) : (w < 1 << 22 ? 22 : 23))) : (w < 1 << 27
? (w < 1 << 25 ? (w < 1 << 24 ? 24 : 25) : (w < 1 << 26 ? 26 : 27))
: (w < 1 << 29 ? (w < 1 << 28 ? 28 : 29) : (w < 1 << 30 ? 30 : 31)))));
}
/// <summary>
/// Concatenates the specified byte arrays.
/// </summary>
/// <param name="buffers">The byte arrays to concatenate.</param>
/// <returns>The concatenated byte array.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] Concat(params byte[][] buffers)
{
int length = 0;
for (int i = 0; i < buffers.Length; i++)
length += buffers[i].Length;
byte[] dst = new byte[length];
int p = 0;
foreach (byte[] src in buffers)
{
Buffer.BlockCopy(src, 0, dst, p, src.Length);
p += src.Length;
}
return dst;
}
/// <summary>
/// Concatenates two byte arrays.
/// </summary>
/// <param name="a">The first byte array to concatenate.</param>
/// <param name="b">The second byte array to concatenate.</param>
/// <returns>The concatenated byte array.</returns>
public static byte[] Concat(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
{
byte[] buffer = new byte[a.Length + b.Length];
a.CopyTo(buffer);
b.CopyTo(buffer.AsSpan(a.Length));
return buffer;
}
internal static int GetLowestSetBit(this BigInteger i)
{
if (i.Sign == 0)
return -1;
byte[] b = i.ToByteArray();
int w = 0;
while (b[w] == 0)
w++;
for (int x = 0; x < 8; x++)
if ((b[w] & 1 << x) > 0)
return x + w * 8;
throw new Exception();
}
internal static void Remove<T>(this HashSet<T> set, ISet<T> other)
{
if (set.Count > other.Count)
{
set.ExceptWith(other);
}
else
{
set.RemoveWhere(u => other.Contains(u));
}
}
internal static void Remove<T>(this HashSet<T> set, HashSetCache<T> other)
where T : IEquatable<T>
{
if (set.Count > other.Count)
{
set.ExceptWith(other);
}
else
{
set.RemoveWhere(u => other.Contains(u));
}
}
internal static void Remove<T, V>(this HashSet<T> set, IReadOnlyDictionary<T, V> other)
{
if (set.Count > other.Count)
{
set.ExceptWith(other.Keys);
}
else
{
set.RemoveWhere(u => other.ContainsKey(u));
}
}
internal static string GetVersion(this Assembly assembly)
{
CustomAttributeData attribute = assembly.CustomAttributes.FirstOrDefault(p => p.AttributeType == typeof(AssemblyInformationalVersionAttribute));
if (attribute == null) return assembly.GetName().Version.ToString(3);
return (string)attribute.ConstructorArguments[0].Value;
}
/// <summary>
/// Converts a hex <see cref="string"/> to byte array.
/// </summary>
/// <param name="value">The hex <see cref="string"/> to convert.</param>
/// <returns>The converted byte array.</returns>
public static byte[] HexToBytes(this string value)
{
if (value == null || value.Length == 0)
return Array.Empty<byte>();
if (value.Length % 2 == 1)
throw new FormatException();
byte[] result = new byte[value.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = byte.Parse(value.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static BigInteger Mod(this BigInteger x, BigInteger y)
{
x %= y;
if (x.Sign < 0)
x += y;
return x;
}
internal static BigInteger ModInverse(this BigInteger a, BigInteger n)
{
BigInteger i = n, v = 0, d = 1;
while (a > 0)
{
BigInteger t = i / a, x = a;
a = i % x;
i = x;
x = d;
d = v - t * x;
v = x;
}
v %= n;
if (v < 0) v = (v + n) % n;
return v;
}
internal static BigInteger NextBigInteger(this Random rand, int sizeInBits)
{
if (sizeInBits < 0)
throw new ArgumentException("sizeInBits must be non-negative");
if (sizeInBits == 0)
return 0;
Span<byte> b = stackalloc byte[sizeInBits / 8 + 1];
rand.NextBytes(b);
if (sizeInBits % 8 == 0)
b[^1] = 0;
else
b[^1] &= (byte)((1 << sizeInBits % 8) - 1);
return new BigInteger(b);
}
/// <summary>
/// Finds the sum of the specified integers.
/// </summary>
/// <param name="source">The specified integers.</param>
/// <returns>The sum of the integers.</returns>
public static BigInteger Sum(this IEnumerable<BigInteger> source)
{
var sum = BigInteger.Zero;
foreach (var bi in source) sum += bi;
return sum;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TestBit(this BigInteger i, int index)
{
return (i & (BigInteger.One << index)) > BigInteger.Zero;
}
/// <summary>
/// Converts a <see cref="BigInteger"/> to byte array and eliminates all the leading zeros.
/// </summary>
/// <param name="i">The <see cref="BigInteger"/> to convert.</param>
/// <returns>The converted byte array.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] ToByteArrayStandard(this BigInteger i)
{
if (i.IsZero) return Array.Empty<byte>();
return i.ToByteArray();
}
/// <summary>
/// Converts a byte array to hex <see cref="string"/>.
/// </summary>
/// <param name="value">The byte array to convert.</param>
/// <returns>The converted hex <see cref="string"/>.</returns>
public static string ToHexString(this byte[] value)
{
StringBuilder sb = new();
foreach (byte b in value)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
/// <summary>
/// Converts a byte array to hex <see cref="string"/>.
/// </summary>
/// <param name="value">The byte array to convert.</param>
/// <param name="reverse">Indicates whether it should be converted in the reversed byte order.</param>
/// <returns>The converted hex <see cref="string"/>.</returns>
public static string ToHexString(this byte[] value, bool reverse = false)
{
StringBuilder sb = new();
for (int i = 0; i < value.Length; i++)
sb.AppendFormat("{0:x2}", value[reverse ? value.Length - i - 1 : i]);
return sb.ToString();
}
/// <summary>
/// Converts a byte array to hex <see cref="string"/>.
/// </summary>
/// <param name="value">The byte array to convert.</param>
/// <returns>The converted hex <see cref="string"/>.</returns>
public static string ToHexString(this ReadOnlySpan<byte> value)
{
StringBuilder sb = new();
foreach (byte b in value)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
/// <summary>
/// Converts a <see cref="DateTime"/> to timestamp.
/// </summary>
/// <param name="time">The <see cref="DateTime"/> to convert.</param>
/// <returns>The converted timestamp.</returns>
public static uint ToTimestamp(this DateTime time)
{
return (uint)(time.ToUniversalTime() - unixEpoch).TotalSeconds;
}
/// <summary>
/// Converts a <see cref="DateTime"/> to timestamp in milliseconds.
/// </summary>
/// <param name="time">The <see cref="DateTime"/> to convert.</param>
/// <returns>The converted timestamp.</returns>
public static ulong ToTimestampMS(this DateTime time)
{
return (ulong)(time.ToUniversalTime() - unixEpoch).TotalMilliseconds;
}
/// <summary>
/// Checks if address is IPv4 Maped to IPv6 format, if so, Map to IPv4.
/// Otherwise, return current address.
/// </summary>
internal static IPAddress Unmap(this IPAddress address)
{
if (address.IsIPv4MappedToIPv6)
address = address.MapToIPv4();
return address;
}
/// <summary>
/// Checks if IPEndPoint is IPv4 Maped to IPv6 format, if so, unmap to IPv4.
/// Otherwise, return current endpoint.
/// </summary>
internal static IPEndPoint Unmap(this IPEndPoint endPoint)
{
if (!endPoint.Address.IsIPv4MappedToIPv6)
return endPoint;
return new IPEndPoint(endPoint.Address.Unmap(), endPoint.Port);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
static bool httpWebRequestWebPermissionDenied = false;
static RequestCachePolicy requestCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
static long connectionGroupNamePrefix = 0;
readonly ClientWebSocketFactory clientWebSocketFactory;
bool allowCookies;
AuthenticationSchemes authenticationScheme;
HttpCookieContainerManager httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile MruCache<Uri, Uri> credentialCacheUriPrefixCache;
bool decompressionEnabled;
// Double-checked locking pattern requires volatile for read/write synchronization
[Fx.Tag.SecurityNote(Critical = "This cache stores strings that contain domain/user name/password. Must not be settable from PT code.")]
[SecurityCritical]
volatile MruCache<string, string> credentialHashCache;
[Fx.Tag.SecurityNote(Critical = "This hash algorithm takes strings that contain domain/user name/password. Must not be settable from PT code.")]
[SecurityCritical]
HashAlgorithm hashAlgorithm;
bool keepAliveEnabled;
int maxBufferSize;
IWebProxy proxy;
WebProxyFactory proxyFactory;
SecurityCredentialsManager channelCredentials;
SecurityTokenManager securityTokenManager;
TransferMode transferMode;
ISecurityCapabilities securityCapabilities;
WebSocketTransportSettings webSocketSettings;
ConnectionBufferPool bufferPool;
Lazy<string> webSocketSoapContentType;
string uniqueConnectionGroupNamePrefix;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.GetString(SR.MaxReceivedMessageSizeMustBeInIntegerRange)));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.GetString(SR.MaxBufferSizeMustMatchMaxReceivedMessageSize));
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.GetString(SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize));
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString(
SR.HttpAuthDoesNotSupportRequestStreaming));
}
this.allowCookies = bindingElement.AllowCookies;
#pragma warning disable 618
if (!this.allowCookies)
{
Collection<HttpCookieContainerBindingElement> httpCookieContainerBindingElements = context.BindingParameters.FindAll<HttpCookieContainerBindingElement>();
if (httpCookieContainerBindingElements.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MultipleCCbesInParameters, typeof(HttpCookieContainerBindingElement))));
}
if (httpCookieContainerBindingElements.Count == 1)
{
this.allowCookies = true;
context.BindingParameters.Remove<HttpCookieContainerBindingElement>();
}
}
#pragma warning restore 618
if (this.allowCookies)
{
this.httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
this.authenticationScheme = bindingElement.AuthenticationScheme;
this.decompressionEnabled = bindingElement.DecompressionEnabled;
this.keepAliveEnabled = bindingElement.KeepAliveEnabled;
this.maxBufferSize = bindingElement.MaxBufferSize;
this.transferMode = bindingElement.TransferMode;
if (bindingElement.Proxy != null)
{
this.proxy = bindingElement.Proxy;
}
else if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress)));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
this.proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
this.proxy = null;
this.proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
this.proxy = new WebProxy();
}
this.channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
this.securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
this.webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(this.MaxReceivedMessageSize);
this.bufferPool = new ConnectionBufferPool(webSocketBufferSize);
Collection<ClientWebSocketFactory> clientWebSocketFactories = context.BindingParameters.FindAll<ClientWebSocketFactory>();
if (clientWebSocketFactories.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
"context",
SR.GetString(SR.MultipleClientWebSocketFactoriesSpecified, typeof(BindingContext).Name, typeof(ClientWebSocketFactory).Name));
}
else
{
this.clientWebSocketFactory = clientWebSocketFactories.Count == 0 ? null : clientWebSocketFactories[0];
}
this.webSocketSoapContentType = new Lazy<string>(() => { return this.MessageEncoderFactory.CreateSessionEncoder().ContentType; }, LazyThreadSafetyMode.ExecutionAndPublication);
if (ServiceModelAppSettings.HttpTransportPerFactoryConnectionPool)
{
this.uniqueConnectionGroupNamePrefix = Interlocked.Increment(ref connectionGroupNamePrefix).ToString();
}
else
{
this.uniqueConnectionGroupNamePrefix = string.Empty;
}
}
public bool AllowCookies
{
get
{
return this.allowCookies;
}
}
public AuthenticationSchemes AuthenticationScheme
{
get
{
return this.authenticationScheme;
}
}
public bool DecompressionEnabled
{
get
{
return this.decompressionEnabled;
}
}
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public bool KeepAliveEnabled
{
get
{
return this.keepAliveEnabled;
}
}
public SecurityTokenManager SecurityTokenManager
{
get
{
return this.securityTokenManager;
}
}
public int MaxBufferSize
{
get
{
return maxBufferSize;
}
}
public IWebProxy Proxy
{
get
{
return this.proxy;
}
}
public TransferMode TransferMode
{
get
{
return transferMode;
}
}
public override string Scheme
{
get
{
return Uri.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get { return this.webSocketSettings; }
}
internal string WebSocketSoapContentType
{
get
{
return this.webSocketSoapContentType.Value;
}
}
protected ConnectionBufferPool WebSocketBufferPool
{
get { return this.bufferPool; }
}
// must be called under lock (this.credentialHashCache)
HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (this.hashAlgorithm == null)
{
this.hashAlgorithm = CryptoHelper.CreateHashAlgorithm(SecurityAlgorithms.Sha1Digest);
}
else
{
this.hashAlgorithm.Initialize();
}
return this.hashAlgorithm;
}
}
int IHttpTransportFactorySettings.MaxBufferSize
{
get { return MaxBufferSize; }
}
TransferMode IHttpTransportFactorySettings.TransferMode
{
get { return TransferMode; }
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return this.clientWebSocketFactory;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)this.securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)this.GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return this.httpCookieContainerManager;
}
internal virtual SecurityMessageProperty CreateReplySecurityProperty(HttpWebRequest request,
HttpWebResponse response)
{
// Don't pull in System.Authorization if we don't need to!
if (!response.IsMutuallyAuthenticated)
{
return null;
}
return CreateMutuallyAuthenticatedReplySecurityProperty(response);
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.GetString(SR.HttpToMustEqualVia, to, via));
}
[MethodImpl(MethodImplOptions.NoInlining)]
SecurityMessageProperty CreateMutuallyAuthenticatedReplySecurityProperty(HttpWebResponse response)
{
string spn = AuthenticationManager.CustomTargetNameDictionary[response.ResponseUri.AbsoluteUri];
if (spn == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.HttpSpnNotFound,
response.ResponseUri)));
}
ReadOnlyCollection<IAuthorizationPolicy> spnPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(spn);
SecurityMessageProperty remoteSecurity = new SecurityMessageProperty();
remoteSecurity.TransportToken = new SecurityTokenSpecification(null, spnPolicies);
remoteSecurity.ServiceSecurityContext = new ServiceSecurityContext(spnPolicies);
return remoteSecurity;
}
internal override int GetMaxBufferSize()
{
return MaxBufferSize;
}
SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
base.ValidateScheme(via);
if (this.MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
EndpointAddress httpRemoteAddress = remoteAddress != null && WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeWsSchemeWithHttpScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
Uri httpVia = WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeWsSchemeWithHttpScheme(via) : via;
return this.OnCreateChannelCore(httpRemoteAddress, httpVia);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
this.ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, this.clientWebSocketFactory, remoteAddress, via, this.WebSocketBufferPool);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && this.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
this.WebSocketSettings.TransportUsage)));
}
else if (channelType == typeof(IDuplexSessionChannel))
{
if (this.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
this.WebSocketSettings.TransportUsage)));
}
else if (!WebSocketHelper.OSSupportsWebSockets() && this.ClientWebSocketFactory == null)
{
throw FxTrace.Exception.AsError(new PlatformNotSupportedException(SR.GetString(SR.WebSocketsClientSideNotSupported, typeof(ClientWebSocketFactory).FullName)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
void InitializeSecurityTokenManager()
{
if (this.channelCredentials == null)
{
this.channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
this.securityTokenManager = this.channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
if (this.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
if (this.proxyFactory != null && this.proxyFactory.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
else
{
return false;
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
this.OnOpen(timeout);
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
this.InitializeSecurityTokenManager();
}
if (this.AllowCookies &&
!this.httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
this.httpCookieContainerManager.CookieContainer = new CookieContainer();
}
// we need to make sure System.Net will buffer faults (sent as 500 requests) up to our allowed size
// Their value is in Kbytes and ours is in bytes. We round up so that the KB value is large enough to
// encompass our MaxReceivedMessageSize. See MB#20860 and related for details
if (!httpWebRequestWebPermissionDenied && HttpWebRequest.DefaultMaximumErrorResponseLength != -1)
{
int MaxReceivedMessageSizeKbytes;
if (MaxBufferSize >= (int.MaxValue - 1024)) // make sure NCL doesn't overflow
{
MaxReceivedMessageSizeKbytes = -1;
}
else
{
MaxReceivedMessageSizeKbytes = (int)(MaxBufferSize / 1024);
if (MaxReceivedMessageSizeKbytes * 1024 < MaxBufferSize)
{
MaxReceivedMessageSizeKbytes++;
}
}
if (MaxReceivedMessageSizeKbytes == -1
|| MaxReceivedMessageSizeKbytes > HttpWebRequest.DefaultMaximumErrorResponseLength)
{
try
{
HttpWebRequest.DefaultMaximumErrorResponseLength = MaxReceivedMessageSizeKbytes;
}
catch (SecurityException exception)
{
// CSDMain\33725 - setting DefaultMaximumErrorResponseLength should not fail HttpChannelFactory.OnOpen
// if the user does not have the permission to do so.
httpWebRequestWebPermissionDenied = true;
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
}
}
}
}
protected override void OnClosed()
{
base.OnClosed();
if (this.bufferPool != null)
{
this.bufferPool.Close();
}
}
static internal void TraceResponseReceived(HttpWebResponse response, Message message, object receiver)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
if (response != null && response.ResponseUri != null)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.HttpResponseReceived, SR.GetString(SR.TraceCodeHttpResponseReceived), new StringTraceRecord("ResponseUri", response.ResponseUri.ToString()), receiver, null, message);
}
else
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.HttpResponseReceived, SR.GetString(SR.TraceCodeHttpResponseReceived), receiver, message);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method AppendWindowsAuthenticationInfo to access the credential domain/user name/password.")]
[SecurityCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(HttpWebRequest httpWebRequest, SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Fx.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm;
}
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method AppendWindowsAuthenticationInfo to access the credential domain/user name/password.",
Safe = "Uses the domain/user name/password to store and compute a hash. The store is SecurityCritical. The hash leaks but" +
"the hash cannot be reversed to the domain/user name/password.")]
[SecuritySafeCritical]
string GetConnectionGroupName(HttpWebRequest httpWebRequest, NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (this.credentialHashCache == null)
{
lock (ThisLock)
{
if (this.credentialHashCache == null)
{
this.credentialHashCache = new MruCache<string, string>(5);
}
}
}
// The following line is a work-around for VSWhidbey 558605. In particular, we need to isolate our
// connection groups based on whether we are streaming the request.
string inputString = TransferModeHelper.IsRequestStreamed(this.TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(this.AuthenticationScheme))
{
// for NTLM & Negotiate, System.Net doesn't pool connections by default. This is because
// IIS doesn't re-authenticate NTLM connections (made for a perf reason), and HttpWebRequest
// shared connections among multiple callers.
// This causes Indigo a performance problem in turn. We mitigate this by (1) enabling
// connection sharing for NTLM connections on our pool, and (2) scoping the pool we use
// to be based on the NetworkCredential that is being used to authenticate the connection.
// Therefore we're only sharing connections among the same Credential.
// Setting this will fail in partial trust, and that's ok since this is an optimization.
if (!httpWebRequestWebPermissionDenied)
{
try
{
httpWebRequest.UnsafeAuthenticatedConnectionSharing = true;
}
catch (SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
httpWebRequestWebPermissionDenied = true;
}
}
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
string prefix = this.OnGetConnectionGroupPrefix(httpWebRequest, clientCertificateToken);
inputString = string.Concat(this.uniqueConnectionGroupNamePrefix, prefix, inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (this.credentialHashCache)
{
if (!this.credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = this.HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
this.credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (this.credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (this.credentialCacheUriPrefixCache == null)
{
this.credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (this.credentialCacheUriPrefixCache)
{
if (!this.credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
this.credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
// core code for creating an HttpWebRequest
HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, NetworkCredential credential,
TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel,
SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout, bool isWebSocketRequest)
{
Uri httpWebRequestUri = isWebSocketRequest ? WebSocketHelper.GetWebSocketUri(via) : via;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpWebRequestUri);
Fx.Assert(httpWebRequest.Method.Equals("GET", StringComparison.OrdinalIgnoreCase), "the default HTTP method of HttpWebRequest should be 'Get'.");
if (!isWebSocketRequest)
{
httpWebRequest.Method = "POST";
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
httpWebRequest.SendChunked = true;
httpWebRequest.AllowWriteStreamBuffering = false;
}
else
{
httpWebRequest.AllowWriteStreamBuffering = true;
}
}
httpWebRequest.CachePolicy = requestCachePolicy;
httpWebRequest.KeepAlive = this.keepAliveEnabled;
if (this.decompressionEnabled)
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
else
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
}
if (credential != null)
{
CredentialCache credentials = new CredentialCache();
credentials.Add(this.GetCredentialCacheUriPrefix(via),
AuthenticationSchemesHelper.ToString(this.authenticationScheme), credential);
httpWebRequest.Credentials = credentials;
}
httpWebRequest.AuthenticationLevel = authenticationLevel;
httpWebRequest.ImpersonationLevel = impersonationLevel;
string connectionGroupName = GetConnectionGroupName(httpWebRequest, credential, authenticationLevel, impersonationLevel, clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName, remoteCertificateIdentity.Certificates[0].Thumbprint);
}
if (!string.IsNullOrEmpty(connectionGroupName))
{
httpWebRequest.ConnectionGroupName = connectionGroupName;
}
if (AuthenticationScheme == AuthenticationSchemes.Basic)
{
httpWebRequest.PreAuthenticate = true;
}
if (this.proxy != null)
{
httpWebRequest.Proxy = this.proxy;
}
else if (this.proxyFactory != null)
{
httpWebRequest.Proxy = this.proxyFactory.CreateWebProxy(httpWebRequest, proxyTokenProvider, timeout);
}
if (this.AllowCookies)
{
httpWebRequest.CookieContainer = this.httpCookieContainerManager.CookieContainer;
}
// we do this at the end so that we access the correct ServicePoint
httpWebRequest.ServicePoint.UseNagleAlgorithm = false;
return httpWebRequest;
}
void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ManualAddressingRequiresAddressedMessages)), message);
}
to = new EndpointAddress(toHeader);
if (this.MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), this.AuthenticationScheme, to, via, channelParameters);
if (this.proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), this.proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider,
SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout, bool isWebSocketRequest)
{
TokenImpersonationLevel impersonationLevel;
AuthenticationLevel authenticationLevel;
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
NetworkCredential credential = HttpChannelUtilities.GetCredential(this.authenticationScheme,
tokenProvider, timeoutHelper.RemainingTime(), out impersonationLevel, out authenticationLevel);
return GetWebRequest(to, via, credential, impersonationLevel, authenticationLevel, proxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime(), isWebSocketRequest);
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if ((target.Identity == null) || (target.Identity is X509CertificateEndpointIdentity))
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, this.AuthenticationScheme);
}
protected class HttpRequestChannel : RequestChannel
{
// Double-checked locking pattern requires volatile for read/write synchronization
volatile bool cleanupIdentity;
HttpChannelFactory<IRequestChannel> factory;
SecurityTokenProviderContainer tokenProvider;
SecurityTokenProviderContainer proxyTokenProvider;
ServiceModelActivity activity = null;
ChannelParameterCollection channelParameters;
public HttpRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
this.factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory
{
get { return this.factory; }
}
internal ServiceModelActivity Activity
{
get { return this.activity; }
}
protected ChannelParameterCollection ChannelParameters
{
get
{
return this.channelParameters;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (this.State == CommunicationState.Created)
{
lock (ThisLock)
{
if (this.channelParameters == null)
{
this.channelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)this.channelParameters;
}
else
{
return base.GetProperty<T>();
}
}
void PrepareOpen()
{
if (Factory.MapIdentity(RemoteAddress))
{
lock (ThisLock)
{
cleanupIdentity = HttpTransportSecurityHelpers.AddIdentityMapping(Via, RemoteAddress);
}
}
}
void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(this.RemoteAddress, this.Via, this.channelParameters, timeoutHelper.RemainingTime(), out this.tokenProvider, out this.proxyTokenProvider);
}
}
void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.tokenProvider != null)
{
tokenProvider.Close(timeoutHelper.RemainingTime());
}
if (this.proxyTokenProvider != null)
{
proxyTokenProvider.Close(timeoutHelper.RemainingTime());
}
}
void AbortTokenProviders()
{
if (this.tokenProvider != null)
{
tokenProvider.Abort();
}
if (this.proxyTokenProvider != null)
{
proxyTokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
PrepareOpen();
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProviders(timeoutHelper.RemainingTime());
return new CompletedAsyncResult(callback, state);
}
protected override void OnOpen(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
void PrepareClose(bool aborting)
{
if (cleanupIdentity)
{
lock (ThisLock)
{
if (cleanupIdentity)
{
cleanupIdentity = false;
HttpTransportSecurityHelpers.RemoveIdentityMapping(Via, RemoteAddress, !aborting);
}
}
}
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
IAsyncResult retval = null;
using (ServiceModelActivity.BoundOperation(this.activity))
{
PrepareClose(false);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProviders(timeoutHelper.RemainingTime());
retval = base.BeginWaitForPendingRequests(timeoutHelper.RemainingTime(), callback, state);
}
ServiceModelActivity.Stop(this.activity);
return retval;
}
protected override void OnEndClose(IAsyncResult result)
{
using (ServiceModelActivity.BoundOperation(this.activity))
{
base.EndWaitForPendingRequests(result);
}
ServiceModelActivity.Stop(this.activity);
}
protected override void OnClose(TimeSpan timeout)
{
using (ServiceModelActivity.BoundOperation(this.activity))
{
PrepareClose(false);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProviders(timeoutHelper.RemainingTime());
base.WaitForPendingRequests(timeoutHelper.RemainingTime());
}
ServiceModelActivity.Stop(this.activity);
}
protected override IAsyncRequest CreateAsyncRequest(Message message, AsyncCallback callback, object state)
{
if (DiagnosticUtility.ShouldUseActivity && this.activity == null)
{
this.activity = ServiceModelActivity.CreateActivity();
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(this.activity.Id);
}
ServiceModelActivity.Start(this.activity, SR.GetString(SR.ActivityReceiveBytes, this.RemoteAddress.Uri.ToString()), ActivityType.ReceiveBytes);
}
return new HttpChannelAsyncRequest(this, callback, state);
}
protected override IRequest CreateRequest(Message message)
{
return new HttpChannelRequest(this, Factory);
}
public virtual HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper)
{
return GetWebRequest(to, via, null, ref timeoutHelper);
}
protected HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer webRequestTokenProvider;
SecurityTokenProviderContainer webRequestProxyTokenProvider;
if (this.ManualAddressing)
{
this.Factory.CreateAndOpenTokenProviders(to, via, this.channelParameters, timeoutHelper.RemainingTime(),
out webRequestTokenProvider, out webRequestProxyTokenProvider);
}
else
{
webRequestTokenProvider = this.tokenProvider;
webRequestProxyTokenProvider = this.proxyTokenProvider;
}
try
{
return this.Factory.GetWebRequest(to, via, webRequestTokenProvider, webRequestProxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime(), false);
}
finally
{
if (this.ManualAddressing)
{
if (webRequestTokenProvider != null)
{
webRequestTokenProvider.Abort();
}
if (webRequestProxyTokenProvider != null)
{
webRequestProxyTokenProvider.Abort();
}
}
}
}
protected IAsyncResult BeginGetWebRequest(
EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
{
return new GetWebRequestAsyncResult(this, to, via, clientCertificateToken, ref timeoutHelper, callback, state);
}
public virtual IAsyncResult BeginGetWebRequest(
EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
{
return BeginGetWebRequest(to, via, null, ref timeoutHelper, callback, state);
}
public virtual HttpWebRequest EndGetWebRequest(IAsyncResult result)
{
return GetWebRequestAsyncResult.End(result);
}
public virtual bool WillGetWebRequestCompleteSynchronously()
{
return ((this.tokenProvider == null) && !Factory.ManualAddressing);
}
internal virtual void OnWebRequestCompleted(HttpWebRequest request)
{
// empty
}
class HttpChannelRequest : IRequest
{
HttpRequestChannel channel;
HttpChannelFactory<IRequestChannel> factory;
EndpointAddress to;
Uri via;
HttpWebRequest webRequest;
HttpAbortReason abortReason;
ChannelBinding channelBinding;
int webRequestCompleted;
EventTraceActivity eventTraceActivity;
const string ConnectionGroupPrefixMessagePropertyName = "HttpTransportConnectionGroupNamePrefix";
public HttpChannelRequest(HttpRequestChannel channel, HttpChannelFactory<IRequestChannel> factory)
{
this.channel = channel;
this.to = channel.RemoteAddress;
this.via = channel.Via;
this.factory = factory;
}
private string GetConnectionGroupPrefix(Message message)
{
object property;
if (message.Properties.TryGetValue(ConnectionGroupPrefixMessagePropertyName, out property))
{
string prefix = property as string;
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public void SendRequest(Message message, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
factory.ApplyManualAddressing(ref this.to, ref this.via, message);
this.webRequest = channel.GetWebRequest(this.to, this.via, ref timeoutHelper);
this.webRequest.ConnectionGroupName = GetConnectionGroupPrefix(message) + this.webRequest.ConnectionGroupName;
Message request = message;
try
{
if (channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the web request and bail
Cleanup();
channel.ThrowIfDisposedOrNotOpen();
}
HttpChannelUtilities.SetRequestTimeout(this.webRequest, timeoutHelper.RemainingTime());
HttpOutput httpOutput = HttpOutput.CreateHttpOutput(this.webRequest, this.factory, request, this.factory.IsChannelBindingSupportEnabled);
bool success = false;
try
{
httpOutput.Send(timeoutHelper.RemainingTime());
this.channelBinding = httpOutput.TakeChannelBinding();
httpOutput.Close();
success = true;
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
{
this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
if (TD.MessageSentByTransportIsEnabled())
{
TD.MessageSentByTransport(eventTraceActivity, this.to.Uri.AbsoluteUri);
}
}
}
finally
{
if (!success)
{
httpOutput.Abort(HttpAbortReason.Aborted);
}
}
}
finally
{
if (!object.ReferenceEquals(request, message))
{
request.Close();
}
}
}
void Cleanup()
{
if (this.webRequest != null)
{
HttpChannelUtilities.AbortRequest(this.webRequest);
this.TryCompleteWebRequest(this.webRequest);
}
ChannelBindingUtility.Dispose(ref this.channelBinding);
}
public void Abort(RequestChannel channel)
{
Cleanup();
abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
Justification = "This is an old method from previous release.")]
public Message WaitForReply(TimeSpan timeout)
{
if (TD.HttpResponseReceiveStartIsEnabled())
{
TD.HttpResponseReceiveStart(this.eventTraceActivity);
}
HttpWebResponse response = null;
WebException responseException = null;
try
{
try
{
response = (HttpWebResponse)webRequest.GetResponse();
}
catch (NullReferenceException nullReferenceException)
{
// workaround for Whidbey bug #558605 - only happens in streamed case.
if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException));
}
throw;
}
if (TD.MessageReceivedByTransportIsEnabled())
{
TD.MessageReceivedByTransport(this.eventTraceActivity ?? EventTraceActivity.Empty,
response.ResponseUri != null ? response.ResponseUri.AbsoluteUri : string.Empty,
EventTraceActivity.GetActivityIdFromThread());
}
if (DiagnosticUtility.ShouldTraceVerbose)
{
HttpChannelFactory<TChannel>.TraceResponseReceived(response, null, this);
}
}
catch (WebException webException)
{
responseException = webException;
response = HttpChannelUtilities.ProcessGetResponseWebException(webException, this.webRequest,
abortReason);
}
HttpInput httpInput = HttpChannelUtilities.ValidateRequestReplyResponse(this.webRequest, response,
this.factory, responseException, this.channelBinding);
this.channelBinding = null;
Message replyMessage = null;
if (httpInput != null)
{
Exception exception = null;
replyMessage = httpInput.ParseIncomingMessage(out exception);
Fx.Assert(exception == null, "ParseIncomingMessage should not set an exception after parsing a response message.");
if (replyMessage != null)
{
HttpChannelUtilities.AddReplySecurityProperty(this.factory, this.webRequest, response,
replyMessage);
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && (eventTraceActivity != null))
{
EventTraceActivityHelper.TryAttachActivity(replyMessage, eventTraceActivity);
}
}
}
this.TryCompleteWebRequest(this.webRequest);
return replyMessage;
}
public void OnReleaseRequest()
{
this.TryCompleteWebRequest(this.webRequest);
}
void TryCompleteWebRequest(HttpWebRequest request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref this.webRequestCompleted, 1, 0) == 0)
{
this.channel.OnWebRequestCompleted(request);
}
}
}
class HttpChannelAsyncRequest : TraceAsyncResult, IAsyncRequest
{
static AsyncCallback onProcessIncomingMessage = Fx.ThunkCallback(new AsyncCallback(OnParseIncomingMessage));
static AsyncCallback onGetResponse = Fx.ThunkCallback(new AsyncCallback(OnGetResponse));
static AsyncCallback onGetWebRequestCompleted;
static AsyncCallback onSend = Fx.ThunkCallback(new AsyncCallback(OnSend));
static Action<object> onSendTimeout;
ChannelBinding channelBinding;
HttpChannelFactory<IRequestChannel> factory;
HttpRequestChannel channel;
HttpOutput httpOutput;
HttpInput httpInput;
Message message;
Message requestMessage;
Message replyMessage;
HttpWebResponse response;
HttpWebRequest request;
object sendLock = new object();
IOThreadTimer sendTimer;
TimeoutHelper timeoutHelper;
EndpointAddress to;
Uri via;
HttpAbortReason abortReason;
int webRequestCompleted;
EventTraceActivity eventTraceActivity;
public HttpChannelAsyncRequest(HttpRequestChannel channel, AsyncCallback callback, object state)
: base(callback, state)
{
this.channel = channel;
this.to = channel.RemoteAddress;
this.via = channel.Via;
this.factory = channel.Factory;
}
IOThreadTimer SendTimer
{
get
{
if (this.sendTimer == null)
{
if (onSendTimeout == null)
{
onSendTimeout = new Action<object>(OnSendTimeout);
}
this.sendTimer = new IOThreadTimer(onSendTimeout, this, false);
}
return this.sendTimer;
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<HttpChannelAsyncRequest>(result);
}
public void BeginSendRequest(Message message, TimeSpan timeout)
{
this.message = this.requestMessage = message;
this.timeoutHelper = new TimeoutHelper(timeout);
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
{
this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
}
factory.ApplyManualAddressing(ref this.to, ref this.via, this.requestMessage);
if (this.channel.WillGetWebRequestCompleteSynchronously())
{
SetWebRequest(channel.GetWebRequest(this.to, this.via, ref this.timeoutHelper));
if (this.SendWebRequest())
{
base.Complete(true);
}
}
else
{
if (onGetWebRequestCompleted == null)
{
onGetWebRequestCompleted = Fx.ThunkCallback(
new AsyncCallback(OnGetWebRequestCompletedCallback));
}
IAsyncResult result = channel.BeginGetWebRequest(
to, via, ref this.timeoutHelper, onGetWebRequestCompleted, this);
if (result.CompletedSynchronously)
{
if (TD.MessageSentByTransportIsEnabled())
{
TD.MessageSentByTransport(this.eventTraceActivity, this.to.Uri.AbsoluteUri);
}
if (this.OnGetWebRequestCompleted(result))
{
base.Complete(true);
}
}
}
}
static void OnGetWebRequestCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState;
Exception completionException = null;
bool completeSelf;
try
{
completeSelf = thisPtr.OnGetWebRequestCompleted(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
void AbortSend()
{
CancelSendTimer();
if (this.request != null)
{
this.TryCompleteWebRequest(this.request);
this.abortReason = HttpAbortReason.TimedOut;
httpOutput.Abort(this.abortReason);
}
}
void CancelSendTimer()
{
lock (sendLock)
{
if (this.sendTimer != null)
{
this.sendTimer.Cancel();
this.sendTimer = null;
}
}
}
bool OnGetWebRequestCompleted(IAsyncResult result)
{
SetWebRequest(this.channel.EndGetWebRequest(result));
return this.SendWebRequest();
}
bool SendWebRequest()
{
this.httpOutput = HttpOutput.CreateHttpOutput(this.request, this.factory, this.requestMessage, this.factory.IsChannelBindingSupportEnabled);
bool success = false;
try
{
bool result = false;
SetSendTimeout(timeoutHelper.RemainingTime());
IAsyncResult asyncResult = httpOutput.BeginSend(timeoutHelper.RemainingTime(), onSend, this);
success = true;
if (asyncResult.CompletedSynchronously)
{
result = CompleteSend(asyncResult);
}
return result;
}
finally
{
if (!success)
{
this.httpOutput.Abort(HttpAbortReason.Aborted);
if (!object.ReferenceEquals(this.message, this.requestMessage))
{
this.requestMessage.Close();
}
}
}
}
bool CompleteSend(IAsyncResult result)
{
bool success = false;
try
{
httpOutput.EndSend(result);
this.channelBinding = httpOutput.TakeChannelBinding();
httpOutput.Close();
success = true;
if (TD.MessageSentByTransportIsEnabled())
{
TD.MessageSentByTransport(this.eventTraceActivity, this.to.Uri.AbsoluteUri);
}
}
finally
{
if (!success)
{
httpOutput.Abort(HttpAbortReason.Aborted);
}
if (!object.ReferenceEquals(this.message, this.requestMessage))
{
this.requestMessage.Close();
}
}
try
{
IAsyncResult getResponseResult;
try
{
getResponseResult = request.BeginGetResponse(onGetResponse, this);
}
catch (NullReferenceException nullReferenceException)
{
// workaround for Whidbey bug #558605 - only happens in streamed case.
if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException));
}
throw;
}
if (getResponseResult.CompletedSynchronously)
{
return CompleteGetResponse(getResponseResult);
}
return false;
}
catch (IOException ioException)
{
throw TraceUtility.ThrowHelperError(new CommunicationException(ioException.Message,
ioException), this.requestMessage);
}
catch (WebException webException)
{
throw TraceUtility.ThrowHelperError(new CommunicationException(webException.Message,
webException), this.requestMessage);
}
catch (ObjectDisposedException objectDisposedException)
{
if (abortReason == HttpAbortReason.Aborted)
{
throw TraceUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.GetString(SR.HttpRequestAborted, to.Uri),
objectDisposedException), this.requestMessage);
}
throw TraceUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.HttpRequestTimedOut,
to.Uri, this.timeoutHelper.OriginalTimeout), objectDisposedException), this.requestMessage);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
Justification = "This is an old method from previous release.")]
bool CompleteGetResponse(IAsyncResult result)
{
using (ServiceModelActivity.BoundOperation(this.channel.Activity))
{
HttpWebResponse response = null;
WebException responseException = null;
try
{
try
{
CancelSendTimer();
response = (HttpWebResponse)request.EndGetResponse(result);
}
catch (NullReferenceException nullReferenceException)
{
// workaround for Whidbey bug #558605 - only happens in streamed case.
if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException));
}
throw;
}
if (TD.MessageReceivedByTransportIsEnabled())
{
TD.MessageReceivedByTransport(
this.eventTraceActivity ?? EventTraceActivity.Empty,
this.to.Uri.AbsoluteUri,
EventTraceActivity.GetActivityIdFromThread());
}
if (DiagnosticUtility.ShouldTraceVerbose)
{
HttpChannelFactory<TChannel>.TraceResponseReceived(response, this.message, this);
}
}
catch (WebException webException)
{
responseException = webException;
response = HttpChannelUtilities.ProcessGetResponseWebException(webException, request,
abortReason);
}
return ProcessResponse(response, responseException);
}
}
void Cleanup()
{
if (this.request != null)
{
HttpChannelUtilities.AbortRequest(this.request);
this.TryCompleteWebRequest(this.request);
}
ChannelBindingUtility.Dispose(ref this.channelBinding);
}
void SetSendTimeout(TimeSpan timeout)
{
// We also set the timeout on the HttpWebRequest so that we can subsequently use it in the
// exception message in the event of a timeout.
HttpChannelUtilities.SetRequestTimeout(this.request, timeout);
if (timeout == TimeSpan.MaxValue)
{
CancelSendTimer();
}
else
{
SendTimer.Set(timeout);
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
void SetWebRequest(HttpWebRequest webRequest)
{
this.request = webRequest;
if (channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request, we need to abort the web request and bail
Cleanup();
channel.ThrowIfDisposedOrNotOpen();
}
}
public Message End()
{
HttpChannelAsyncRequest.End(this);
return replyMessage;
}
bool ProcessResponse(HttpWebResponse response, WebException responseException)
{
this.httpInput = HttpChannelUtilities.ValidateRequestReplyResponse(this.request, response,
this.factory, responseException, this.channelBinding);
this.channelBinding = null;
if (httpInput != null)
{
this.response = response;
IAsyncResult result =
httpInput.BeginParseIncomingMessage(onProcessIncomingMessage, this);
if (!result.CompletedSynchronously)
{
return false;
}
CompleteParseIncomingMessage(result);
}
else
{
this.replyMessage = null;
}
this.TryCompleteWebRequest(this.request);
return true;
}
void CompleteParseIncomingMessage(IAsyncResult result)
{
Exception exception = null;
this.replyMessage = this.httpInput.EndParseIncomingMessage(result, out exception);
Fx.Assert(exception == null, "ParseIncomingMessage should not set an exception after parsing a response message.");
if (this.replyMessage != null)
{
HttpChannelUtilities.AddReplySecurityProperty(this.factory, this.request, this.response,
this.replyMessage);
}
}
static void OnParseIncomingMessage(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.CompleteParseIncomingMessage(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
static void OnSend(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState;
Exception completionException = null;
bool completeSelf;
try
{
completeSelf = thisPtr.CompleteSend(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
static void OnSendTimeout(object state)
{
HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)state;
thisPtr.AbortSend();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
Justification = "This is an old method from previous release.")]
static void OnGetResponse(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState;
Exception completionException = null;
bool completeSelf;
try
{
completeSelf = thisPtr.CompleteGetResponse(result);
}
catch (WebException webException)
{
completeSelf = true;
completionException = new CommunicationException(webException.Message, webException);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
public void OnReleaseRequest()
{
this.TryCompleteWebRequest(this.request);
}
void TryCompleteWebRequest(HttpWebRequest request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref this.webRequestCompleted, 1, 0) == 0)
{
this.channel.OnWebRequestCompleted(request);
}
}
}
class GetWebRequestAsyncResult : AsyncResult
{
static AsyncCallback onGetSspiCredential;
static AsyncCallback onGetUserNameCredential;
SecurityTokenContainer clientCertificateToken;
HttpChannelFactory<IRequestChannel> factory;
SecurityTokenProviderContainer proxyTokenProvider;
HttpWebRequest request;
EndpointAddress to;
TimeoutHelper timeoutHelper;
SecurityTokenProviderContainer tokenProvider;
Uri via;
public GetWebRequestAsyncResult(HttpRequestChannel channel,
EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper,
AsyncCallback callback, object state)
: base(callback, state)
{
this.to = to;
this.via = via;
this.clientCertificateToken = clientCertificateToken;
this.timeoutHelper = timeoutHelper;
this.factory = channel.Factory;
this.tokenProvider = channel.tokenProvider;
this.proxyTokenProvider = channel.proxyTokenProvider;
if (factory.ManualAddressing)
{
this.factory.CreateAndOpenTokenProviders(to, via, channel.channelParameters, timeoutHelper.RemainingTime(),
out this.tokenProvider, out this.proxyTokenProvider);
}
bool completeSelf = false;
IAsyncResult result = null;
if (factory.AuthenticationScheme == AuthenticationSchemes.Anonymous)
{
SetupWebRequest(AuthenticationLevel.None, TokenImpersonationLevel.None, null);
completeSelf = true;
}
else if (factory.AuthenticationScheme == AuthenticationSchemes.Basic)
{
if (onGetUserNameCredential == null)
{
onGetUserNameCredential = Fx.ThunkCallback(new AsyncCallback(OnGetUserNameCredential));
}
result = TransportSecurityHelpers.BeginGetUserNameCredential(
tokenProvider, timeoutHelper.RemainingTime(), onGetUserNameCredential, this);
if (result.CompletedSynchronously)
{
CompleteGetUserNameCredential(result);
completeSelf = true;
}
}
else
{
if (onGetSspiCredential == null)
{
onGetSspiCredential = Fx.ThunkCallback(new AsyncCallback(OnGetSspiCredential));
}
result = TransportSecurityHelpers.BeginGetSspiCredential(
tokenProvider, timeoutHelper.RemainingTime(), onGetSspiCredential, this);
if (result.CompletedSynchronously)
{
CompleteGetSspiCredential(result);
completeSelf = true;
}
}
if (completeSelf)
{
CloseTokenProvidersIfRequired();
base.Complete(true);
}
}
public static HttpWebRequest End(IAsyncResult result)
{
GetWebRequestAsyncResult thisPtr = AsyncResult.End<GetWebRequestAsyncResult>(result);
return thisPtr.request;
}
void CompleteGetUserNameCredential(IAsyncResult result)
{
NetworkCredential credential =
TransportSecurityHelpers.EndGetUserNameCredential(result);
SetupWebRequest(AuthenticationLevel.None, TokenImpersonationLevel.None, credential);
}
void CompleteGetSspiCredential(IAsyncResult result)
{
AuthenticationLevel authenticationLevel;
TokenImpersonationLevel impersonationLevel;
NetworkCredential credential =
TransportSecurityHelpers.EndGetSspiCredential(result, out impersonationLevel, out authenticationLevel);
if (factory.AuthenticationScheme == AuthenticationSchemes.Digest)
{
HttpChannelUtilities.ValidateDigestCredential(ref credential, impersonationLevel);
}
else if (factory.AuthenticationScheme == AuthenticationSchemes.Ntlm)
{
if (authenticationLevel == AuthenticationLevel.MutualAuthRequired)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.CredentialDisallowsNtlm)));
}
}
SetupWebRequest(authenticationLevel, impersonationLevel, credential);
}
void SetupWebRequest(AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel, NetworkCredential credential)
{
this.request = factory.GetWebRequest(to, via, credential, impersonationLevel,
authenticationLevel, this.proxyTokenProvider, this.clientCertificateToken, timeoutHelper.RemainingTime(), false);
}
void CloseTokenProvidersIfRequired()
{
if (this.factory.ManualAddressing)
{
if (this.tokenProvider != null)
{
tokenProvider.Abort();
}
if (this.proxyTokenProvider != null)
{
proxyTokenProvider.Abort();
}
}
}
static void OnGetSspiCredential(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.CompleteGetSspiCredential(result);
thisPtr.CloseTokenProvidersIfRequired();
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
static void OnGetUserNameCredential(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.CompleteGetUserNameCredential(result);
thisPtr.CloseTokenProvidersIfRequired();
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
}
}
class WebProxyFactory
{
Uri address;
bool bypassOnLocal;
AuthenticationSchemes authenticationScheme;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
this.address = address;
this.bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
this.authenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme
{
get
{
return authenticationScheme;
}
}
public IWebProxy CreateWebProxy(HttpWebRequest request, SecurityTokenProviderContainer tokenProvider, TimeSpan timeout)
{
WebProxy result = new WebProxy(this.address, this.bypassOnLocal);
if (this.authenticationScheme != AuthenticationSchemes.Anonymous)
{
TokenImpersonationLevel impersonationLevel;
AuthenticationLevel authenticationLevel;
NetworkCredential credential = HttpChannelUtilities.GetCredential(this.authenticationScheme,
tokenProvider, timeout, out impersonationLevel, out authenticationLevel);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevel, request.ImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.ProxyImpersonationLevelMismatch, impersonationLevel, request.ImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevel == AuthenticationLevel.MutualAuthRequired) &&
(request.AuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.ProxyAuthenticationLevelMismatch, authenticationLevel, request.AuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
credentials.Add(this.address, AuthenticationSchemesHelper.ToString(this.authenticationScheme),
credential);
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Imgur.API.Enums;
using Imgur.API.Models;
using Imgur.API.Authentication;
using System.Net.Http;
using Imgur.API.Exceptions;
using Imgur.API.Models.Impl;
using System.Net;
using System.Diagnostics;
using Imgur.API.RequestBuilders;
namespace Imgur.API.Endpoints.Impl
{
/// <summary>
/// Implementation of gallery related actions.
/// </summary>
public partial class GalleryEndpoint : EndpointBase, IGalleryEndpoint
{
private const uint randomPageMax = 50;
/// <summary>
/// Initializes the endpoint.
/// </summary>
/// <param name="apiClient">The client to use.</param>
public GalleryEndpoint(IApiClient apiClient) : base(apiClient)
{
}
internal GalleryEndpoint(IApiClient client, HttpClient httpClient) : base(client, httpClient)
{
}
internal GalleryRequestBuilder RequestBuilder { get; } = new GalleryRequestBuilder();
/// <summary>
/// Fetches gallery submissions.
/// </summary>
/// <param name="section">The section of the gallery to fetch.</param>
/// <param name="sort">How to sort the gallery.</param>
/// <param name="window">The maximum age of the submissions to fetch.</param>
/// <param name="page">What page of the gallery to fetch.</param>
/// <param name="showViral">If true, viral pots will be included. If false, viral posts will be excluded.</param>
/// <exception cref="ArgumentException">Thrown when arguments are invalid or conflicting.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns>An array with gallery submissions.</returns>
public async Task<ICollection<IGalleryAlbumImageBase>> GetGalleryAsync(GallerySection section = GallerySection.Hot, GallerySortBy sort = GallerySortBy.Viral, GalleryWindow window = GalleryWindow.Day, uint page = 0, bool showViral = true)
{
if (sort == GallerySortBy.Rising && section != GallerySection.User)
throw new ArgumentException(nameof(sort) + " can only be rising if " + nameof(section) + " is user.");
var sectionStr = section.ToString().ToLower();
var sortStr = sort.ToString().ToLower();
var windowStr = window.ToString().ToLower();
var url = $"gallery/{sectionStr}/{sortStr}/{windowStr}/{page}.json?showViral={showViral}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var gallery = await SendRequestAsync<IGalleryAlbumImageBase[]>(request);
return gallery;
}
}
/// <summary>
/// Fetches the image identified by the given id.
/// </summary>
/// <param name="id">The id of the image to fetch.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns>The gallery image identified by the given ID.</returns>
public async Task<IGalleryImage> GetGalleryImageAsync(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/image/{id}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var image = await SendRequestAsync<GalleryImage>(request);
return image;
}
}
/// <summary>
/// Fetches the album identified by the given id.
/// </summary>
/// <param name="id">The id of the album to fetch.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns>The gallery album identified by the given id.</returns>
public async Task<IGalleryAlbum> GetGalleryAlbumAsync(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/album/{id}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var album = await SendRequestAsync<GalleryAlbum>(request);
return album;
};
}
/// <summary>
/// Report an item currently in the gallery.
/// </summary>
/// <param name="id">The id of the gallery submission to report.</param>
/// <param name="reason">The reason for reporting the item.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns></returns>
public async Task<bool> PostReportAsync(string id, Reporting reason)
{
if(string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/{id}/report";
using (var request = RequestBuilder.PostReportRequest(url, reason))
{
var result = await SendRequestAsync<bool>(request);
return result;
}
}
/// <summary>
/// Get the vote information about an image
/// </summary>
/// <param name="id">The id of the gallery submission to get the votes for.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns>Vote information on the gallery submission.</returns>
public async Task<IVotes> GetVotesAsync(string id)
{
if(string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/{id}/votes";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var votes = await SendRequestAsync<Votes>(request);
return votes;
}
}
/// <summary>
/// Vote for an image, 'up' or 'down' vote. Send the same value again to undo a vote.
/// </summary>
/// <param name="id">The id of the gallery submission to vote on.</param>
/// <param name="vote">The vote to send.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encountered an error.</exception>
/// <returns></returns>
public async Task<bool> PostVoteAsync(string id, Vote vote)
{
if(string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var voteStr = vote.ToString().ToLower();
var url = $"gallery/{id}/vote/{voteStr}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Post, url))
{
var result = await SendRequestAsync<bool>(request);
return result;
}
}
/// <summary>
/// Remove a submission from the gallery. You must be logged in as the owner of the item to do this action.
/// </summary>
/// <param name="id">The id of the submission to remove from the gallery.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns></returns>
public async Task<bool> DeleteFromGalleryAsync(string id)
{
if(string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/{id}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Delete, url))
{
var result = await SendRequestAsync<bool>(request);
return result;
}
}
/// <summary>
/// View tags for a gallery submission.
/// </summary>
/// <param name="id">The id of the gallery item to fetch tags for.</param>
/// <exception cref="ArgumentNullException">Thrown when id was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns>The tags related to the gallery submission.</returns>
public async Task<ICollection<ITagVote>> GetGalleryItemTagsAsync(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/{id}/tags";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var result = await SendRequestAsync<TagVote[]>(request);
return result;
}
}
/// <summary>
/// Returns a random set of gallery images. Pages are regenerated every hour.
/// </summary>
/// <param name="page">The page to fetch.</param>
/// <exception cref="ArgumentException">Thrown when page was higher than 50.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns>An array of gallery submissions.</returns>
public async Task<ICollection<IGalleryAlbumImageBase>> GetRandomItemsAsync(uint page = 0)
{
if (page > randomPageMax)
throw new ArgumentException(nameof(page) + " can not be higher than 50.");
var url = $"gallery/random/random/{page}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var items = await SendRequestAsync<IGalleryAlbumImageBase[]>(request);
return items;
}
}
/// <summary>
/// View images for a gallery tag
/// </summary>
/// <param name="tagname">The name of the tag to fetch items for.</param>
/// <param name="sort">How to sort the items.</param>
/// <param name="window">The maximum age of the items.</param>
/// <param name="page">The page to fetch.</param>
/// <exception cref="ArgumentNullException">Thrown when tagname was null or empty.</exception>
/// <exception cref="ArgumentException">Thrown when sort was set to GallerySortBy.Rising.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns>Information about the tag and an array of gallery submissions.</returns>
public async Task<ITag> GetTagAsync(string tagname, GallerySortBy sort = GallerySortBy.Viral, GalleryWindow window = GalleryWindow.Week, uint page = 0)
{
if (string.IsNullOrEmpty(tagname))
throw new ArgumentNullException(nameof(tagname));
if(sort == GallerySortBy.Rising)
throw new ArgumentException(nameof(sort) + " cannot be Rising.");
var sortStr = sort.ToString().ToLower();
var windowStr = window.ToString().ToLower();
var url = $"gallery/t/{tagname}/{sort}/{window}/{page}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var tag = await SendRequestAsync<Tag>(request);
return tag;
}
}
/// <summary>
/// View a single image in a gallery tag.
/// </summary>
/// <param name="tagname">The name of the tag.</param>
/// <param name="id">The id of the gallery image to fetch</param>
/// <exception cref="ArgumentNullException">Thrown when id or tagname was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns>The gallery image identified by the given id.</returns>
public async Task<IGalleryImage> GetTagImageAsync(string tagname, string id)
{
if (string.IsNullOrEmpty(tagname))
throw new ArgumentNullException(nameof(tagname));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
var url = $"gallery/t/{tagname}/{id}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var image = await SendRequestAsync<GalleryImage>(request);
return image;
}
}
/// <summary>
/// Vote for a tag, 'up' or 'down' vote. Send the same value again to undo a vote.
/// </summary>
/// <param name="id">The id of the gallery submission to vote on a tag for.</param>
/// <param name="tagname">The tag to vote for.</param>
/// <param name="vote">The vote.</param>
/// <exception cref="ArgumentNullException">Thrown when id or tagname was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns></returns>
public async Task<bool> PostGalleryTagVoteAsync(string id, string tagname, Vote vote)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(tagname))
throw new ArgumentNullException(nameof(tagname));
var url = $"gallery/{id}/vote/tag/{tagname}/{vote}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Post, url))
{
var result = await SendRequestAsync<bool>(request);
return result;
}
}
/// <summary>
/// Share an Album or Image to the Gallery.
/// </summary>
/// <param name="id">The id of the album or image to share.</param>
/// <param name="title">The title for the submission.</param>
/// <param name="topic">The topic for the submission.</param>
/// <param name="acceptTerms">Whether or not the user has accepted the Imgur terms of service.</param>
/// <param name="Nsfw">Whether or not the submission is nsfw.</param>
/// <exception cref="ArgumentNullException">Thrown when id or title was null or empty.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns></returns>
public async Task<bool> PublishToGalleryAsync(string id, string title, string topic = null, bool? acceptTerms = null, bool? Nsfw = null)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(title))
throw new ArgumentNullException(nameof(title));
var url = $"gallery/{id}";
using (var request = RequestBuilder.PublishRequest(url, title, topic, acceptTerms, Nsfw))
{
var result = await SendRequestAsync<bool>(request);
return result;
}
}
/// <summary>
/// Search the gallery with a given query string.
/// </summary>
/// <param name="query">The query to use for searching.</param>
/// <param name="sort">How to sort the results.</param>
/// <param name="window">The maximum age of the items in the result.</param>
/// <param name="page">The page of the result.</param>
/// <exception cref="ArgumentNullException">Thrown when query was null or empty.</exception>
/// <exception cref="ArgumentException">Thrown when sort was set to GallerySortBy.Rising.</exception>
/// <exception cref="ImgurException">Thrown when Imgur encounters an error.</exception>
/// <returns>An array of gallery submissions matching the query.</returns>
public async Task<ICollection<IGalleryAlbumImageBase>> SearchGalleryAsync(string query, GallerySortBy sort = GallerySortBy.Time, GalleryWindow window = GalleryWindow.All, uint page = 0)
{
if (string.IsNullOrEmpty(query))
throw new ArgumentNullException(nameof(query));
if(sort == GallerySortBy.Rising)
throw new ArgumentException(nameof(sort) + " cannot be Rising.");
var sortStr = sort.ToString().ToLower();
var windowStr = window.ToString().ToLower();
var queryStr = WebUtility.UrlEncode(query);
var url = $"gallery/search/{sortStr}/{windowStr}/{page}?q={queryStr}";
using (var request = RequestBuilder.CreateRequest(HttpMethod.Get, url))
{
var items = await SendRequestAsync<IGalleryAlbumImageBase[]>(request);
return items;
}
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
/// <summary>
/// A MySQL Interface for the Asset Server
/// </summary>
public class MySQLAssetData : AssetDataBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_connectionString;
private object m_dbLock = new object();
#region IPlugin Members
public override string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin.</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public override void Initialise(string connect)
{
m_connectionString = connect;
// This actually does the roll forward assembly stuff
Assembly assem = GetType().Assembly;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, assem, "AssetStore");
m.Update();
}
}
public override void Initialise()
{
throw new NotImplementedException();
}
public override void Dispose() { }
/// <summary>
/// The name of this DB provider
/// </summary>
override public string Name
{
get { return "MySQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
override public AssetBase GetAsset(UUID assetID)
{
AssetBase asset = null;
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(
"SELECT name, description, assetType, local, temporary, asset_flags, CreatorID, data FROM assets WHERE id=?id",
dbcon))
{
cmd.Parameters.AddWithValue("?id", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], dbReader["CreatorID"].ToString());
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];
string local = dbReader["local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
}
}
}
catch (Exception e)
{
m_log.Error("[ASSETS DB]: MySql failure fetching asset " + assetID + ": " + e.Message);
}
}
}
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
override public void StoreAsset(AssetBase asset)
{
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd =
new MySqlCommand(
"replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" +
"VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?asset_flags, ?CreatorID, ?data)",
dbcon);
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on add");
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on add");
}
// need to ensure we dispose
try
{
using (cmd)
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?name", assetName);
cmd.Parameters.AddWithValue("?description", assetDescription);
cmd.Parameters.AddWithValue("?assetType", asset.Type);
cmd.Parameters.AddWithValue("?local", asset.Local);
cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?create_time", now);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags);
cmd.Parameters.AddWithValue("?data", asset.Data);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
}
}
}
}
private void UpdateAccessTime(AssetBase asset)
{
// Writing to the database every time Get() is called on an asset is killing us. Seriously. -jph
return;
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd =
new MySqlCommand("update assets set access_time=?access_time where id=?id",
dbcon);
// need to ensure we dispose
try
{
using (cmd)
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS DB]: " +
"MySql failure updating access_time for asset {0} with name {1}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name);
}
}
}
}
/// <summary>
/// check if the asset UUID exist in database
/// </summary>
/// <param name="uuid">The asset UUID</param>
/// <returns>true if exist.</returns>
override public bool ExistsAsset(UUID uuid)
{
bool assetExists = false;
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT id FROM assets WHERE id=?id", dbcon))
{
cmd.Parameters.AddWithValue("?id", uuid.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
assetExists = true;
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString(), uuid);
}
}
}
}
return assetExists;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd = new MySqlCommand("SELECT name,description,assetType,temporary,id,asset_flags,CreatorID FROM assets LIMIT ?start, ?count", dbcon);
cmd.Parameters.AddWithValue("?start", start);
cmd.Parameters.AddWithValue("?count", count);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.Name = (string)dbReader["name"];
metadata.Description = (string)dbReader["description"];
metadata.Type = (sbyte)dbReader["assetType"];
metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
metadata.FullID = DBGuid.FromDB(dbReader["id"]);
metadata.CreatorID = dbReader["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] { };
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_log.Error("[ASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString());
}
}
}
return retList;
}
public override bool Delete(string id)
{
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd = new MySqlCommand("delete from assets where id=?id", dbcon);
cmd.Parameters.AddWithValue("?id", id);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
return true;
}
#endregion
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using StardewValleyMods.CategorizeChests.Framework;
namespace StardewValleyMods.CategorizeChests.Interface.Widgets
{
class CategoryMenu : Widget
{
public event Action OnClose;
// Dependencies
private readonly IItemDataManager ItemDataManager;
private readonly ITooltipManager TooltipManager;
private readonly ChestData ChestData;
// Styling settings
private SpriteFont HeaderFont => Game1.dialogueFont;
private const int MaxItemColumns = 12;
private int Padding => 2 * Game1.pixelZoom;
// Widgets
private Widget Body;
private Widget TopRow;
private LabeledCheckbox SelectAllButton;
private SpriteButton CloseButton;
private Background Background;
private Label CategoryLabel;
private WrapBag ToggleBag;
private SpriteButton PrevButton;
private SpriteButton NextButton;
private IEnumerable<ItemToggle> ItemToggles => from child in ToggleBag.Children
where child is ItemToggle
select child as ItemToggle;
private List<string> AvailableCategories;
private string SelectedCategory;
public CategoryMenu(ChestData chestData, IItemDataManager itemDataManager, ITooltipManager tooltipManager)
{
ItemDataManager = itemDataManager;
TooltipManager = tooltipManager;
ChestData = chestData;
AvailableCategories = ItemDataManager.Categories.Keys.ToList();
AvailableCategories.Sort();
BuildWidgets();
SetCategory(AvailableCategories.First());
}
private void BuildWidgets()
{
Background = AddChild(new Background(Sprites.MenuBackground));
Body = AddChild(new Widget());
TopRow = Body.AddChild(new Widget());
ToggleBag = Body.AddChild(new WrapBag(MaxItemColumns * Game1.tileSize));
NextButton = TopRow.AddChild(new SpriteButton(Sprites.RightArrow));
PrevButton = TopRow.AddChild(new SpriteButton(Sprites.LeftArrow));
NextButton.OnPress += () => CycleCategory(1);
PrevButton.OnPress += () => CycleCategory(-1);
SelectAllButton = TopRow.AddChild(new LabeledCheckbox("All"));
SelectAllButton.OnChange += OnToggleSelectAll;
CloseButton = AddChild(new SpriteButton(Sprites.ExitButton));
CloseButton.OnPress += () => OnClose?.Invoke();
CategoryLabel = TopRow.AddChild(new Label("", Color.Black, HeaderFont));
}
private void PositionElements()
{
Body.Position = new Point(Background.Graphic.LeftBorderThickness, Background.Graphic.RightBorderThickness);
// Figure out width
Body.Width = ToggleBag.Width;
TopRow.Width = Body.Width;
Width = Body.Width + Background.Graphic.LeftBorderThickness + Background.Graphic.RightBorderThickness +
Padding * 2;
// Build the top row
var HeaderWidth = (int) HeaderFont.MeasureString(" Animal Product ").X; // TODO
NextButton.X = TopRow.Width / 2 + HeaderWidth / 2;
PrevButton.X = TopRow.Width / 2 - HeaderWidth / 2 - PrevButton.Width;
SelectAllButton.X = Padding;
CategoryLabel.CenterHorizontally();
TopRow.Height = TopRow.Children.Max(c => c.Height);
foreach (var child in TopRow.Children)
child.Y = TopRow.Height / 2 - child.Height / 2;
// Figure out height and vertical positioning
ToggleBag.Y = TopRow.Y + TopRow.Height + Padding;
Body.Height = ToggleBag.Y + ToggleBag.Height;
Height = Body.Height + Background.Graphic.TopBorderThickness + Background.Graphic.BottomBorderThickness +
Padding * 2;
Background.Width = Width;
Background.Height = Height;
CloseButton.Position = new Point(Width - CloseButton.Width, 0);
}
private void OnToggleSelectAll(bool on)
{
if (on)
SelectAll();
else
SelectNone();
}
private void SelectAll()
{
foreach (var toggle in ItemToggles)
{
if (!toggle.Active)
toggle.Toggle();
}
}
private void SelectNone()
{
foreach (var toggle in ItemToggles)
{
if (toggle.Active)
toggle.Toggle();
}
}
private void CycleCategory(int offset)
{
var index = AvailableCategories.FindIndex(c => c == SelectedCategory);
var newCategory = AvailableCategories[Utility.Mod(index + offset, AvailableCategories.Count)];
SetCategory(newCategory);
}
private void SetCategory(string category)
{
SelectedCategory = category;
CategoryLabel.Text = category;
RecreateItemToggles();
SelectAllButton.Checked = AreAllSelected();
PositionElements();
}
private void RecreateItemToggles()
{
ToggleBag.RemoveChildren();
var itemKeys = ItemDataManager.Categories[SelectedCategory];
foreach (var itemKey in itemKeys)
{
var toggle =
ToggleBag.AddChild(new ItemToggle(ItemDataManager, TooltipManager, itemKey, ChestData.Accepts(itemKey)));
toggle.OnToggle += () => ToggleItem(itemKey);
}
}
private void ToggleItem(ItemKey itemKey)
{
ChestData.Toggle(itemKey);
SelectAllButton.Checked = AreAllSelected();
}
private bool AreAllSelected()
{
return ItemToggles.Count(t => !t.Active) == 0;
}
public override bool ReceiveLeftClick(Point point)
{
PropagateLeftClick(point);
return true;
}
public override bool ReceiveScrollWheelAction(int amount)
{
CycleCategory(amount > 1 ? -1 : 1);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace FFTools {
public class MapForm : Form {
// Unit conversion constants.
private const int BITMAP_SIZE_IN_PIXELS = 4000;
private const int BITMAP_OFFSET_TO_ORIGIN = BITMAP_SIZE_IN_PIXELS / 2;
// Grid appearance constants.
private const int GRID_TOP_PADDING_IN_PIXELS = 80;
private const int GRID_LEFT_PADDING_IN_PIXELS = 20;
private const int GRID_RIGHT_PADDING_IN_PIXELS = 45;
private const int GRID_BOTTOM_PADDING_IN_PIXELS = 65;
private const int GRID_SPACING_IN_EILMS = 3;
private const int GRID_PIXELS_PER_ILMS = 5;
private const int GRID_INTERFACE_HEIGHT = 50;
// Grid color constants.
private const int GRID_COLOR_LINES_R = 0x30;
private const int GRID_COLOR_LINES_G = 0x30;
private const int GRID_COLOR_LINES_B = 0x30;
private const int GRID_COLOR_GATHNODE_VIS_R = 0xFF;
private const int GRID_COLOR_GATHNODE_VIS_G = 0xFF;
private const int GRID_COLOR_GATHNODE_VIS_B = 0x40;
private const int GRID_COLOR_GATHNODE_INV_R = 0x00;
private const int GRID_COLOR_GATHNODE_INV_G = 0x80;
private const int GRID_COLOR_GATHNODE_INV_B = 0x80;
private const int GRID_COLOR_GRAPHOBS_R = 0x30;
private const int GRID_COLOR_GRAPHOBS_G = 0x30;
private const int GRID_COLOR_GRAPHOBS_B = 0x30;
private System.Windows.Forms.Timer RefreshTimer;
private IContainer Components;
// Lock for all View objects.
private Object MapFormLock = new Object();
private float ViewEilmMinX;
private float ViewEilmMinY;
private List<GatheringNode> ViewGathNodeList;
private List<Location> ViewGraphObs;
private List<Location> ViewPath;
private Player ViewPlayer;
// This UI class needs access to the pathing logic for obstacle info.
private NavigatorGraph TheNavigatorGraph = null;
private Navigator TheNavigator = null;
public MapForm(NavigatorGraph theNavigatorGraph, Navigator theNavigator) {
InitializeComponent();
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.Size = new Size(500, 500);
this.MouseDown += new MouseEventHandler(MapForm_MouseDown);
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
ViewEilmMinX = 0;
ViewEilmMinY = 0;
ViewGathNodeList = new List<GatheringNode>();
ViewGraphObs = new List<Location>();
ViewPath = new List<Location>();
ViewPlayer = new Player(0, 0, 0, 0);
TheNavigatorGraph = theNavigatorGraph;
TheNavigator = theNavigator;
}
public void InitializeComponent() {
Components = new System.ComponentModel.Container();
RefreshTimer = new System.Windows.Forms.Timer(Components);
RefreshTimer.Interval = 50;
RefreshTimer.Tick += new EventHandler(timerTick);
}
protected override void Dispose(bool disposing) {
if (disposing && (Components != null)) Components.Dispose();
base.Dispose(disposing);
}
private void timerTick(object sender, System.EventArgs e) {
Refresh();
}
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
RefreshTimer.Start();
}
private void MapForm_MouseDown(object sender, MouseEventArgs e) {
if (e.Y < GRID_INTERFACE_HEIGHT) {
// Interface click.
if ( (e.X > 20) && (e.X < 100) && (e.Y > 20) && (e.Y < 50) ) {
// Save
TheNavigatorGraph.saveObstacles();
} else if ( (e.X > 120) && (e.X < 200) && (e.Y > 20) && (e.Y < 50) ) {
// Load
TheNavigatorGraph.loadObstacles();
this.setViewGraphObstacles(TheNavigatorGraph.getObstacles());
} else if ( (e.X > 220) && (e.X < 300) && (e.Y > 20) && (e.Y < 50) ) {
// Unpause
TheNavigator.navEnableToggle();
} else if ( (e.X > 320) && (e.X < 400) && (e.Y > 20) && (e.Y < 50) ) {
// Exit
Environment.Exit(0);
}
//} else if ( (e.X > GRID_LEFT_PADDING_IN_PIXELS) && (e.X < (this.Width - GRID_RIGHT_PADDING_IN_PIXELS)) &&
// (e.Y > GRID_TOP_PADDING_IN_PIXELS) && (e.Y < (this.Height - GRID_BOTTOM_PADDING_IN_PIXELS)) ) {
} else {
// Graph click.
if (e.Button == MouseButtons.Right) {
float tmpViewEilmMinX = 0;
float tmpViewEilmMinY = 0;
lock (MapFormLock) {
tmpViewEilmMinX = ViewEilmMinX;
tmpViewEilmMinY = ViewEilmMinY;
}
float obsX = tmpViewEilmMinX + e.X / GRID_PIXELS_PER_ILMS;
float obsY = tmpViewEilmMinY + e.Y / GRID_PIXELS_PER_ILMS;
TheNavigatorGraph.toggleObstacle(new Location(obsX, obsY));
this.setViewGraphObstacles(TheNavigatorGraph.getObstacles());
}
if (e.Button == MouseButtons.Left) {}
}
}
private void ButtonSave_Click(object sender, EventArgs e) {
System.Console.WriteLine("Save button pressed");
}
// Draw on a 1000px x 1000px bitmap in memory where the x-axis is at y=500px, and the y-axis is at x=500px.
// Then the section of the bitmap is shown on the form.
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
Bitmap Bmp = new Bitmap(BITMAP_SIZE_IN_PIXELS, BITMAP_SIZE_IN_PIXELS, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics gBmp = Graphics.FromImage(Bmp);
gBmp.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
// Grab a copy of semaphored view data.
List<GatheringNode> tmpViewGathNodeList = new List<GatheringNode>();
List<Location> tmpViewGraphObs = new List<Location>();
List<Location> tmpViewPath = new List<Location>();
Player tmpViewPlayer;
lock (MapFormLock) {
foreach (GatheringNode vgn in ViewGathNodeList) {
tmpViewGathNodeList.Add(new GatheringNode(vgn.vis, vgn.location));
}
}
lock (MapFormLock) {
foreach (Location gol in ViewGraphObs) {
tmpViewGraphObs.Add(new Location(gol.x, gol.y));
}
}
lock (MapFormLock) {
foreach (Location pl in ViewPath) {
tmpViewPath.Add(new Location(pl.x, pl.y));
}
}
lock (MapFormLock) {
tmpViewPlayer = new Player(ViewPlayer.location, ViewPlayer.rot);
}
paintGraphObs(gBmp, tmpViewGraphObs);
paintGrid(gBmp);
paintPath(gBmp, tmpViewPath);
paintGatheringNodes(gBmp, tmpViewGathNodeList);
paintPlayer(gBmp, tmpViewPlayer);
// Find top-left, bottom-right in aboslute ilms of mineral deposits.
// Convert to absolute pixels for bitmap.
// Resize form accoridingly and draw.
float topleftx = BITMAP_OFFSET_TO_ORIGIN / GRID_PIXELS_PER_ILMS;
float toplefty = BITMAP_OFFSET_TO_ORIGIN / GRID_PIXELS_PER_ILMS;
float botrighx = -BITMAP_OFFSET_TO_ORIGIN / GRID_PIXELS_PER_ILMS;
float botrighy = -BITMAP_OFFSET_TO_ORIGIN / GRID_PIXELS_PER_ILMS;
foreach (GatheringNode tvgn in tmpViewGathNodeList) {
if (tvgn.location.x < topleftx) topleftx = tvgn.location.x;
if (tvgn.location.y < toplefty) toplefty = tvgn.location.y;
if (tvgn.location.x > botrighx) botrighx = tvgn.location.x;
if (tvgn.location.y > botrighy) botrighy = tvgn.location.y;
}
int bitmaptopleftx = (int)Math.Round(topleftx * GRID_PIXELS_PER_ILMS) + BITMAP_OFFSET_TO_ORIGIN;
int bitmaptoplefty = (int)Math.Round(toplefty * GRID_PIXELS_PER_ILMS) + BITMAP_OFFSET_TO_ORIGIN;
int bitmapbotrighx = (int)Math.Round(botrighx * GRID_PIXELS_PER_ILMS) + BITMAP_OFFSET_TO_ORIGIN;
int bitmapbotrighy = (int)Math.Round(botrighy * GRID_PIXELS_PER_ILMS) + BITMAP_OFFSET_TO_ORIGIN;
int bitmapwidth = bitmapbotrighx - bitmaptopleftx + GRID_LEFT_PADDING_IN_PIXELS + GRID_RIGHT_PADDING_IN_PIXELS;
int bitmapheigh = bitmapbotrighy - bitmaptoplefty + GRID_TOP_PADDING_IN_PIXELS + GRID_BOTTOM_PADDING_IN_PIXELS;
this.Size = new Size(bitmapwidth, bitmapheigh);
Graphics gForm = e.Graphics;
gForm.FillRectangle(Brushes.Black, 0, 0, bitmapwidth, bitmapheigh);
RectangleF desRect = new RectangleF(0, 0, bitmapwidth, bitmapheigh);
RectangleF srcRect = new RectangleF(bitmaptopleftx - GRID_LEFT_PADDING_IN_PIXELS,
bitmaptoplefty - GRID_TOP_PADDING_IN_PIXELS,
bitmapwidth, bitmapheigh);
gForm.DrawImage(Bmp, desRect, srcRect, GraphicsUnit.Pixel);
paintInterface(gForm);
lock (MapFormLock) {
ViewEilmMinX = topleftx - GRID_LEFT_PADDING_IN_PIXELS / GRID_PIXELS_PER_ILMS;
ViewEilmMinY = toplefty - GRID_TOP_PADDING_IN_PIXELS / GRID_PIXELS_PER_ILMS;
}
Bmp.Dispose();
gBmp.Dispose();
}
private void paintGrid(Graphics gBmp) {
int pixels_per_grid_unit = GRID_SPACING_IN_EILMS * GRID_PIXELS_PER_ILMS;
Pen gridPen = new Pen(Color.FromArgb(0xFF,
GRID_COLOR_LINES_R,
GRID_COLOR_LINES_G,
GRID_COLOR_LINES_B));
// Vertical lines.
for (int x = BITMAP_OFFSET_TO_ORIGIN; x < BITMAP_SIZE_IN_PIXELS; x += pixels_per_grid_unit) {
gBmp.DrawLine(gridPen, x, 0, x, BITMAP_SIZE_IN_PIXELS);
}
for (int x = BITMAP_OFFSET_TO_ORIGIN; x > 0; x -= pixels_per_grid_unit) {
gBmp.DrawLine(gridPen, x, 0, x, BITMAP_SIZE_IN_PIXELS);
}
// Horizontal lines.
for (int y = BITMAP_OFFSET_TO_ORIGIN; y < BITMAP_SIZE_IN_PIXELS; y += pixels_per_grid_unit) {
gBmp.DrawLine(gridPen, 0, y, BITMAP_SIZE_IN_PIXELS, y);
}
for (int y = BITMAP_OFFSET_TO_ORIGIN; y > 0; y -= pixels_per_grid_unit) {
gBmp.DrawLine(gridPen, 0, y, BITMAP_SIZE_IN_PIXELS, y);
}
gridPen.Dispose();
}
private void paintGraphObs(Graphics gBmp, List<Location> tmpViewGraphObs) {
SolidBrush graphobsBrush = new SolidBrush(Color.FromArgb(0xFF,
GRID_COLOR_GRAPHOBS_R,
GRID_COLOR_GRAPHOBS_G,
GRID_COLOR_GRAPHOBS_B));
foreach (Location gol in tmpViewGraphObs) {
gBmp.FillRectangle(graphobsBrush,
(int)Math.Round((gol.x - (float)GRID_SPACING_IN_EILMS / 2) * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN),
(int)Math.Round((gol.y - (float)GRID_SPACING_IN_EILMS / 2) * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN),
GRID_SPACING_IN_EILMS * GRID_PIXELS_PER_ILMS,
GRID_SPACING_IN_EILMS * GRID_PIXELS_PER_ILMS);
}
graphobsBrush.Dispose();
}
private void paintGatheringNodes(Graphics gBmp, List<GatheringNode> tmpViewGathNodeList) {
SolidBrush gnvisBrush = new SolidBrush(Color.FromArgb(0xFF,
GRID_COLOR_GATHNODE_VIS_R,
GRID_COLOR_GATHNODE_VIS_G,
GRID_COLOR_GATHNODE_VIS_B));
SolidBrush gninvBrush = new SolidBrush(Color.FromArgb(0xFF,
GRID_COLOR_GATHNODE_INV_R,
GRID_COLOR_GATHNODE_INV_G,
GRID_COLOR_GATHNODE_INV_B));
foreach (GatheringNode tvgn in tmpViewGathNodeList) {
if (tvgn.vis) {
gBmp.FillEllipse(gnvisBrush,
(int)Math.Round(tvgn.location.x * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 2),
(int)Math.Round(tvgn.location.y * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 2),
4, 4);
} else {
gBmp.FillEllipse(gninvBrush,
(int)Math.Round(tvgn.location.x * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 2),
(int)Math.Round(tvgn.location.y * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 2),
4, 4);
}
}
}
private void paintPath(Graphics gBmp, List<Location> tmpViewPath) {
foreach (Location pl in tmpViewPath) {
gBmp.FillEllipse(Brushes.Crimson,
(int)Math.Round(pl.x * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 1),
(int)Math.Round(pl.y * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 1),
2, 2);
}
}
private void paintPlayer(Graphics gBmp, Player tmpViewPlayer) {
gBmp.FillEllipse(Brushes.Crimson,
(int)Math.Round(tmpViewPlayer.location.x * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 3),
(int)Math.Round(tmpViewPlayer.location.y * GRID_PIXELS_PER_ILMS + BITMAP_OFFSET_TO_ORIGIN - 3),
6, 6);
}
private void paintInterface(Graphics gForm) {
const int GRID_BUTTON_WIDTH = 80;
const int GRID_BUTTON_HEIGHT = 30;
const int GRID_BUTTON_TXT_OFF_Y = 4;
Pen linePen = new Pen(Color.White);
Font lineFont = new Font("Arial", 12);
// Save Button
gForm.FillRectangle(Brushes.Black, 20, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT);
gForm.DrawRectangle(linePen, new Rectangle(20, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT));
gForm.DrawString("Save", lineFont, Brushes.White, 20 + 19, 22 + GRID_BUTTON_TXT_OFF_Y, new StringFormat());
// Load Button
gForm.FillRectangle(Brushes.Black, 120, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT);
gForm.DrawRectangle(linePen, new Rectangle(120, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT));
gForm.DrawString("Load", lineFont, Brushes.White, 120 + 19, 22 + GRID_BUTTON_TXT_OFF_Y, new StringFormat());
// Un/pause Button
gForm.FillRectangle(Brushes.Black, 220, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT);
gForm.DrawRectangle(linePen, new Rectangle(220, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT));
gForm.DrawString(" Pause", lineFont, Brushes.White, 220 + 1, 22 + GRID_BUTTON_TXT_OFF_Y, new StringFormat());
// Exit Button
gForm.FillRectangle(Brushes.Black, 320, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT);
gForm.DrawRectangle(linePen, new Rectangle(320, 20, GRID_BUTTON_WIDTH, GRID_BUTTON_HEIGHT));
gForm.DrawString("Exit", lineFont, Brushes.White, 320 + 22, 22 + GRID_BUTTON_TXT_OFF_Y, new StringFormat());
linePen.Dispose();
lineFont.Dispose();
}
private void paintText(Graphics gBmp) {
Font labelFont = new Font("Century Gothic", 9);
SolidBrush labelBrush = new SolidBrush(Color.White);
gBmp.DrawString("Test", labelFont, labelBrush, new PointF(80F, 80F));
}
public void setViewGathNodeList(List<GatheringNode> newGathNodeList) {
lock (MapFormLock) {
ViewGathNodeList.Clear();
foreach (GatheringNode gn in newGathNodeList) {
ViewGathNodeList.Add(new GatheringNode(gn.vis, gn.location));
}
}
}
public void setViewGraphObstacles(List<Location> newObstacles) {
lock (MapFormLock) {
ViewGraphObs.Clear();
foreach (Location gol in newObstacles) {
ViewGraphObs.Add(new Location(gol.x, gol.y));
}
}
}
public void setViewPath(List<Location> newPath) {
lock (MapFormLock) {
ViewPath.Clear();
foreach (Location pl in newPath) {
ViewPath.Add(new Location(pl.x, pl.y));
}
}
}
public void setViewPlayer(Player newPlayer) {
lock (MapFormLock) {
ViewPlayer = new Player(newPlayer.location, newPlayer.rot);
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang.Compiler.Steps
{
using System;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler;
using Boo.Lang.Compiler.TypeSystem;
[Serializable]
public class BindBaseTypes : AbstractNamespaceSensitiveVisitorCompilerStep
{
public BindBaseTypes()
{
}
override public void Run()
{
Visit(CompileUnit.Modules);
}
override public void OnEnumDefinition(EnumDefinition node)
{
}
override public void OnClassDefinition(ClassDefinition node)
{
// Visit type definition's members to resolve base types on nested types
base.OnClassDefinition(node);
// Resolve and check base types
ResolveBaseTypes(new Boo.Lang.List(), node);
CheckBaseTypes(node);
if (!node.IsFinal)
{
if (((IType)node.Entity).IsFinal)
{
node.Modifiers |= TypeMemberModifiers.Final;
}
}
}
override public void OnInterfaceDefinition(InterfaceDefinition node)
{
ResolveBaseTypes(new Boo.Lang.List(), node);
CheckInterfaceBaseTypes(node);
}
void CheckBaseTypes(ClassDefinition node)
{
IType baseClass = null;
foreach (TypeReference baseType in node.BaseTypes)
{
IType baseInfo = GetType(baseType);
if (!baseInfo.IsInterface)
{
if (null != baseClass)
{
Error(
CompilerErrorFactory.ClassAlreadyHasBaseType(baseType,
node.Name,
baseClass.FullName)
);
}
else
{
baseClass = baseInfo;
if (baseClass.IsFinal && !TypeSystemServices.IsError(baseClass))
{
Error(
CompilerErrorFactory.CannotExtendFinalType(
baseType,
baseClass.FullName));
}
}
}
}
if (null == baseClass)
{
node.BaseTypes.Insert(0, CodeBuilder.CreateTypeReference(TypeSystemServices.ObjectType) );
}
}
void CheckInterfaceBaseTypes(InterfaceDefinition node)
{
foreach (TypeReference baseType in node.BaseTypes)
{
IType tag = GetType(baseType);
if (!tag.IsInterface)
{
Error(CompilerErrorFactory.InterfaceCanOnlyInheritFromInterface(baseType, node.FullName, tag.FullName));
}
}
}
void ResolveBaseTypes(Boo.Lang.List visited, TypeDefinition node)
{
// If type is generic, enter a special namespace to allow
// correct resolution of generic parameters
IType type = (IType)TypeSystemServices.GetEntity(node);
if (type.GenericInfo != null)
{
EnterNamespace(new GenericParametersNamespaceExtender(
type, NameResolutionService.CurrentNamespace));
}
visited.Add(node);
Boo.Lang.List visitedNonInterfaces = null;
Boo.Lang.List visitedInterfaces = null;
if (node is InterfaceDefinition)
{
visitedInterfaces = visited;
// interfaces won't have noninterface base types so visitedNonInterfaces not necessary here
}
else
{
visitedNonInterfaces = visited;
visitedInterfaces = new Boo.Lang.List();
}
int removed = 0;
int index = 0;
foreach (SimpleTypeReference baseType in node.BaseTypes.ToArray())
{
NameResolutionService.ResolveSimpleTypeReference(baseType);
AbstractInternalType internalType = baseType.Entity as AbstractInternalType;
if (null != internalType)
{
if (internalType is InternalInterface)
{
if (visitedInterfaces.Contains(internalType.TypeDefinition))
{
Error(CompilerErrorFactory.InheritanceCycle(baseType, internalType.FullName));
node.BaseTypes.RemoveAt(index - removed);
++removed;
}
else
{
ResolveBaseTypes(visitedInterfaces, internalType.TypeDefinition);
}
}
else
{
if (visitedNonInterfaces.Contains(internalType.TypeDefinition))
{
Error(CompilerErrorFactory.InheritanceCycle(baseType, internalType.FullName));
node.BaseTypes.RemoveAt(index - removed);
++removed;
}
else
{
ResolveBaseTypes(visitedNonInterfaces, internalType.TypeDefinition);
}
}
}
++index;
}
// Leave special namespace if we entered it before
if (type.GenericInfo != null)
{
LeaveNamespace();
}
}
}
/// <summary>
/// Provides a quasi-namespace that can resolve a type's generic parameters before its base types are bound.
/// </summary>
internal class GenericParametersNamespaceExtender : INamespace
{
IType _type;
INamespace _parent;
public GenericParametersNamespaceExtender(IType type, INamespace currentNamespace)
{
_type = type;
_parent = currentNamespace;
}
public INamespace ParentNamespace
{
get
{
return _parent;
}
}
public bool Resolve(List targetList, string name, EntityType filter)
{
if (_type.GenericInfo != null && filter == EntityType.Type)
{
IGenericParameter match = Array.Find(
_type.GenericInfo.GenericParameters,
delegate(IGenericParameter gp) { return gp.Name == name; });
if (match != null)
{
targetList.AddUnique(match);
return true;
}
}
return false;
}
public IEntity[] GetMembers()
{
if (_type.GenericInfo != null)
{
return _type.GenericInfo.GenericParameters;
}
return NullNamespace.EmptyEntityArray;
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using NodaTime.Calendars;
using NodaTime.Testing.TimeZones;
using NodaTime.Text;
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Test
{
/// <summary>
/// Tests for <see cref="ZonedDateTime"/>. Many of these are really testing
/// calendar and time zone functionality, but the entry point to that
/// functionality is usually through ZonedDateTime. This makes testing easier,
/// as well as serving as more useful documentation.
/// </summary>
[TestFixture]
public class ZonedDateTimeTest
{
/// <summary>
/// Changes from UTC+3 to UTC+4 at 1am local time on June 13th 2011.
/// </summary>
private static readonly SingleTransitionDateTimeZone SampleZone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 3, 4);
[Test]
public void SimpleProperties()
{
var value = SampleZone.AtStrictly(new LocalDateTime(2012, 2, 10, 8, 9, 10, 11, 12));
Assert.AreEqual(new LocalDate(2012, 2, 10), value.Date);
Assert.AreEqual(new LocalTime(8, 9, 10, 11, 12), value.TimeOfDay);
Assert.AreEqual(Era.Common, value.Era);
Assert.AreEqual(2012, value.Year);
Assert.AreEqual(2012, value.YearOfEra);
Assert.AreEqual(2, value.Month);
Assert.AreEqual(10, value.Day);
Assert.AreEqual(6, value.WeekOfWeekYear);
Assert.AreEqual(2012, value.WeekYear);
Assert.AreEqual(IsoDayOfWeek.Friday, value.IsoDayOfWeek);
Assert.AreEqual((int) IsoDayOfWeek.Friday, value.DayOfWeek);
Assert.AreEqual(41, value.DayOfYear);
Assert.AreEqual(8, value.ClockHourOfHalfDay);
Assert.AreEqual(8, value.Hour);
Assert.AreEqual(9, value.Minute);
Assert.AreEqual(10, value.Second);
Assert.AreEqual(11, value.Millisecond);
Assert.AreEqual(11 * 10000 + 12, value.TickOfSecond);
Assert.AreEqual(8 * NodaConstants.TicksPerHour +
9 * NodaConstants.TicksPerMinute +
10 * NodaConstants.TicksPerSecond +
11 * NodaConstants.TicksPerMillisecond +
12,
value.TickOfDay);
}
[Test]
public void Add_AroundTimeZoneTransition()
{
// Before the transition at 3pm...
ZonedDateTime before = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 12, 15, 0));
// 24 hours elapsed, and it's 4pm
ZonedDateTime afterExpected = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 13, 16, 0));
ZonedDateTime afterAdd = ZonedDateTime.Add(before, Duration.OneDay);
ZonedDateTime afterOperator = before + Duration.OneDay;
Assert.AreEqual(afterExpected, afterAdd);
Assert.AreEqual(afterExpected, afterOperator);
}
[Test]
public void Add_MethodEquivalents()
{
ZonedDateTime before = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 12, 15, 0));
Assert.AreEqual(before + Duration.OneDay, ZonedDateTime.Add(before, Duration.OneDay));
Assert.AreEqual(before + Duration.OneDay, before.Plus(Duration.OneDay));
}
[Test]
public void Subtract_AroundTimeZoneTransition()
{
// After the transition at 4pm...
ZonedDateTime after = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 13, 16, 0));
// 24 hours earlier, and it's 3pm
ZonedDateTime beforeExpected = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 12, 15, 0));
ZonedDateTime beforeSubtract = ZonedDateTime.Subtract(after, Duration.OneDay);
ZonedDateTime beforeOperator = after - Duration.OneDay;
Assert.AreEqual(beforeExpected, beforeSubtract);
Assert.AreEqual(beforeExpected, beforeOperator);
}
[Test]
public void SubtractDuration_MethodEquivalents()
{
ZonedDateTime after = SampleZone.AtStrictly(new LocalDateTime(2011, 6, 13, 16, 0));
Assert.AreEqual(after - Duration.OneDay, ZonedDateTime.Subtract(after, Duration.OneDay));
Assert.AreEqual(after - Duration.OneDay, after.Minus(Duration.OneDay));
}
[Test]
public void Subtraction_ZonedDateTime()
{
// Test all three approaches... not bothering to check a different calendar,
// but we'll use two different time zones.
ZonedDateTime start = new LocalDateTime(2014, 08, 14, 5, 51).InUtc();
// Sample zone is UTC+4 at this point, so this is 14:00Z.
ZonedDateTime end = SampleZone.AtStrictly(new LocalDateTime(2014, 08, 14, 18, 0));
Duration expected = Duration.FromHours(8) + Duration.FromMinutes(9);
Assert.AreEqual(expected, end - start);
Assert.AreEqual(expected, end.Minus(start));
Assert.AreEqual(expected, ZonedDateTime.Subtract(end, start));
}
[Test]
public void WithZone()
{
Instant instant = Instant.FromUtc(2012, 2, 4, 12, 35);
ZonedDateTime zoned = new ZonedDateTime(instant, SampleZone);
Assert.AreEqual(new LocalDateTime(2012, 2, 4, 16, 35, 0), zoned.LocalDateTime);
// Will be UTC-8 for our instant.
DateTimeZone newZone = new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 1, 1, 0, 0), -7, -8);
ZonedDateTime converted = zoned.WithZone(newZone);
Assert.AreEqual(new LocalDateTime(2012, 2, 4, 4, 35, 0), converted.LocalDateTime);
Assert.AreEqual(converted.ToInstant(), instant);
}
[Test]
public void IsDaylightSavings()
{
// Use a real time zone rather than a single-transition zone, so that we can get
// a savings offset.
var zone = DateTimeZoneProviders.Tzdb["Europe/London"];
var winterSummerTransition = Instant.FromUtc(2014, 3, 30, 1, 0);
var winter = (winterSummerTransition - Duration.Epsilon).InZone(zone);
var summer = winterSummerTransition.InZone(zone);
Assert.IsFalse(winter.IsDaylightSavingTime());
Assert.IsTrue(summer.IsDaylightSavingTime());
}
[Test]
public void FromDateTimeOffset()
{
DateTimeOffset dateTimeOffset = new DateTimeOffset(2011, 3, 5, 1, 0, 0, TimeSpan.FromHours(3));
DateTimeZone fixedZone = new FixedDateTimeZone(Offset.FromHours(3));
ZonedDateTime expected = fixedZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0));
ZonedDateTime actual = ZonedDateTime.FromDateTimeOffset(dateTimeOffset);
Assert.AreEqual(expected, actual);
}
[Test]
public void ToDateTimeOffset()
{
ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0));
DateTimeOffset expected = new DateTimeOffset(2011, 3, 5, 1, 0, 0, TimeSpan.FromHours(3));
DateTimeOffset actual = zoned.ToDateTimeOffset();
Assert.AreEqual(expected, actual);
}
[Test]
public void ToDateTimeUtc()
{
ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0));
// Note that this is 10pm the previous day, UTC - so 1am local time
DateTime expected = new DateTime(2011, 3, 4, 22, 0, 0, DateTimeKind.Utc);
DateTime actual = zoned.ToDateTimeUtc();
Assert.AreEqual(expected, actual);
// Kind isn't checked by Equals...
Assert.AreEqual(DateTimeKind.Utc, actual.Kind);
}
[Test]
public void ToDateTimeUnspecified()
{
ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0));
DateTime expected = new DateTime(2011, 3, 5, 1, 0, 0, DateTimeKind.Unspecified);
DateTime actual = zoned.ToDateTimeUnspecified();
Assert.AreEqual(expected, actual);
// Kind isn't checked by Equals...
Assert.AreEqual(DateTimeKind.Unspecified, actual.Kind);
}
[Test]
public void ToOffsetDateTime()
{
var local = new LocalDateTime(1911, 3, 5, 1, 0, 0); // Early interval
var zoned = SampleZone.AtStrictly(local);
var offsetDateTime = zoned.ToOffsetDateTime();
Assert.AreEqual(local, offsetDateTime.LocalDateTime);
Assert.AreEqual(SampleZone.EarlyInterval.WallOffset, offsetDateTime.Offset);
}
[Test]
public void Equality()
{
// Goes back from 2am to 1am on June 13th
SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);
var sample = zone.MapLocal(new LocalDateTime(2011, 6, 13, 1, 30)).First();
var fromUtc = Instant.FromUtc(2011, 6, 12, 21, 30).InZone(zone);
// Checks all the overloads etc: first check is that the zone matters
TestHelper.TestEqualsStruct(sample, fromUtc, Instant.FromUtc(2011, 6, 12, 21, 30).InUtc());
TestHelper.TestOperatorEquality(sample, fromUtc, Instant.FromUtc(2011, 6, 12, 21, 30).InUtc());
// Now just use a simple inequality check for other aspects...
// Different offset
var later = zone.MapLocal(new LocalDateTime(2011, 6, 13, 1, 30)).Last();
Assert.AreEqual(sample.LocalDateTime, later.LocalDateTime);
Assert.AreNotEqual(sample.Offset, later.Offset);
Assert.AreNotEqual(sample, later);
// Different local time
Assert.AreNotEqual(sample, zone.MapLocal(new LocalDateTime(2011, 6, 13, 1, 29)).First());
// Different calendar
var withOtherCalendar = zone.MapLocal(new LocalDateTime(2011, 6, 13, 1, 30, CalendarSystem.Gregorian)).First();
Assert.AreNotEqual(sample, withOtherCalendar);
}
[Test]
public void Constructor_ArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => new ZonedDateTime(Instant.FromTicksSinceUnixEpoch(1000), null));
Assert.Throws<ArgumentNullException>(() => new ZonedDateTime(Instant.FromTicksSinceUnixEpoch(1000), null, CalendarSystem.Iso));
Assert.Throws<ArgumentNullException>(() => new ZonedDateTime(Instant.FromTicksSinceUnixEpoch(1000), SampleZone, null));
}
[Test]
public void Construct_FromLocal_ValidUnambiguousOffset()
{
SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);
LocalDateTime local = new LocalDateTime(2000, 1, 2, 3, 4, 5);
ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.EarlyInterval.WallOffset);
Assert.AreEqual(zoned, local.InZoneStrictly(zone));
}
[Test]
public void Construct_FromLocal_ValidEarlierOffset()
{
SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);
LocalDateTime local = new LocalDateTime(2011, 6, 13, 1, 30);
ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.EarlyInterval.WallOffset);
// Map the local time to the earlier of the offsets in a way which is tested elsewhere.
var resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnEarlier, Resolvers.ThrowWhenSkipped);
Assert.AreEqual(zoned, local.InZone(zone, resolver));
}
[Test]
public void Construct_FromLocal_ValidLaterOffset()
{
SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);
LocalDateTime local = new LocalDateTime(2011, 6, 13, 1, 30);
ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.LateInterval.WallOffset);
// Map the local time to the later of the offsets in a way which is tested elsewhere.
var resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnLater, Resolvers.ThrowWhenSkipped);
Assert.AreEqual(zoned, local.InZone(zone, resolver));
}
[Test]
public void Construct_FromLocal_InvalidOffset()
{
SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);
// Attempt to ask for the later offset in the earlier interval
LocalDateTime local = new LocalDateTime(2000, 1, 1, 0, 0, 0);
Assert.Throws<ArgumentException>(() => new ZonedDateTime(local, zone, zone.LateInterval.WallOffset));
}
/// <summary>
/// Using the default constructor is equivalent to January 1st 1970, midnight, UTC, ISO calendar
/// </summary>
[Test]
public void DefaultConstructor()
{
var actual = new ZonedDateTime();
Assert.AreEqual(new LocalDateTime(1, 1, 1, 0, 0), actual.LocalDateTime);
Assert.AreEqual(Offset.Zero, actual.Offset);
Assert.AreEqual(DateTimeZone.Utc, actual.Zone);
}
[Test]
public void BinarySerialization_Iso()
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb;
var zone = DateTimeZoneProviders.Tzdb["America/New_York"];
var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertBinaryRoundtrip(value);
}
[Test]
public void XmlSerialization_Iso()
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb;
var zone = DateTimeZoneProviders.Tzdb["America/New_York"];
var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertXmlRoundtrip(value, "<value zone=\"America/New_York\">2013-04-12T17:53:23-04</value>");
}
#if !PCL
[Test]
public void XmlSerialization_Bcl()
{
// Skip this on Mono, which will have different BCL time zones. We can't easily
// guess which will be available :(
if (!TestHelper.IsRunningOnMono)
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Bcl;
var zone = DateTimeZoneProviders.Bcl["Eastern Standard Time"];
var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertXmlRoundtrip(value, "<value zone=\"Eastern Standard Time\">2013-04-12T17:53:23-04</value>");
}
}
[Test]
public void BinarySerialization_Bcl()
{
// Skip this on Mono, which will have different BCL time zones. We can't easily
// guess which will be available :(
if (!TestHelper.IsRunningOnMono)
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Bcl;
var zone = DateTimeZoneProviders.Bcl["Eastern Standard Time"];
var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertBinaryRoundtrip(value);
}
}
#endif
[Test]
public void XmlSerialization_NonIso()
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb;
var zone = DateTimeZoneProviders.Tzdb["America/New_York"];
var localDateTime = new LocalDateTime(2013, 6, 12, 17, 53, 23, CalendarSystem.Julian);
var value = new ZonedDateTime(localDateTime.WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertXmlRoundtrip(value,
"<value zone=\"America/New_York\" calendar=\"Julian\">2013-06-12T17:53:23-04</value>");
}
[Test]
public void BinarySerialization_NonIso()
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb;
var zone = DateTimeZoneProviders.Tzdb["America/New_York"];
var localDateTime = new LocalDateTime(2013, 6, 12, 17, 53, 23, CalendarSystem.Julian);
var value = new ZonedDateTime(localDateTime.WithOffset(Offset.FromHours(-4)), zone);
TestHelper.AssertBinaryRoundtrip(value);
}
[Test]
[TestCase("<value zone=\"America/New_York\" calendar=\"Rubbish\">2013-06-12T17:53:23-04</value>", typeof(KeyNotFoundException), Description = "Unknown calendar system")]
[TestCase("<value>2013-04-12T17:53:23-04</value>", typeof(ArgumentException), Description = "No zone")]
[TestCase("<value zone=\"Unknown\">2013-04-12T17:53:23-04</value>", typeof(DateTimeZoneNotFoundException), Description = "Unknown zone")]
[TestCase("<value zone=\"Europe/London\">2013-04-12T17:53:23-04</value>", typeof(UnparsableValueException), Description = "Incorrect offset")]
public void XmlSerialization_Invalid(string xml, Type expectedExceptionType)
{
DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb;
TestHelper.AssertXmlInvalid<ZonedDateTime>(xml, expectedExceptionType);
}
[Test]
public void ZonedDateTime_ToString()
{
var local = new LocalDateTime(2013, 7, 23, 13, 05, 20);
ZonedDateTime zoned = local.InZoneStrictly(SampleZone);
Assert.AreEqual("2013-07-23T13:05:20 Single (+04)", zoned.ToString());
}
[Test]
public void ZonedDateTime_ToString_WithFormat()
{
var local = new LocalDateTime(2013, 7, 23, 13, 05, 20);
ZonedDateTime zoned = local.InZoneStrictly(SampleZone);
Assert.AreEqual("2013/07/23 13:05:20 Single", zoned.ToString("yyyy/MM/dd HH:mm:ss z", CultureInfo.InvariantCulture));
}
[Test]
public void LocalComparer()
{
var london = DateTimeZoneProviders.Tzdb["Europe/London"];
var losAngeles = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
// LA is 8 hours behind London. So the London evening occurs before the LA afternoon.
var londonEvening = new LocalDateTime(2014, 7, 9, 20, 32).InZoneStrictly(london);
var losAngelesAfternoon = new LocalDateTime(2014, 7, 9, 14, 0).InZoneStrictly(losAngeles);
// Same local time as losAngelesAfternoon
var londonAfternoon = losAngelesAfternoon.LocalDateTime.InZoneStrictly(london);
var londonPersian = londonEvening.LocalDateTime
.WithCalendar(CalendarSystem.PersianSimple)
.InZoneStrictly(london);
TestHelper.TestComparerStruct(ZonedDateTime.Comparer.Local, losAngelesAfternoon, londonAfternoon, londonEvening);
Assert.Throws<ArgumentException>(() => ZonedDateTime.Comparer.Local.Compare(londonPersian, londonEvening));
Assert.IsFalse(ZonedDateTime.Comparer.Local.Equals(londonPersian, londonEvening));
Assert.IsFalse(ZonedDateTime.Comparer.Local.Equals(londonAfternoon, londonEvening));
Assert.IsTrue(ZonedDateTime.Comparer.Local.Equals(londonAfternoon, losAngelesAfternoon));
}
[Test]
public void InstantComparer()
{
var london = DateTimeZoneProviders.Tzdb["Europe/London"];
var losAngeles = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
// LA is 8 hours behind London. So the London evening occurs before the LA afternoon.
var londonEvening = new LocalDateTime(2014, 7, 9, 20, 32).InZoneStrictly(london);
var losAngelesAfternoon = new LocalDateTime(2014, 7, 9, 14, 0).InZoneStrictly(losAngeles);
// Same instant as londonEvening
var losAngelesLunchtime = new LocalDateTime(2014, 7, 9, 12, 32).InZoneStrictly(losAngeles);
var londonPersian = londonEvening.LocalDateTime
.WithCalendar(CalendarSystem.PersianSimple)
.InZoneStrictly(london);
TestHelper.TestComparerStruct(ZonedDateTime.Comparer.Instant, londonEvening, losAngelesLunchtime, losAngelesAfternoon);
Assert.AreEqual(0, ZonedDateTime.Comparer.Instant.Compare(londonPersian, londonEvening));
Assert.IsTrue(ZonedDateTime.Comparer.Instant.Equals(londonPersian, londonEvening));
Assert.IsTrue(ZonedDateTime.Comparer.Instant.Equals(losAngelesLunchtime, londonEvening));
Assert.IsFalse(ZonedDateTime.Comparer.Instant.Equals(losAngelesAfternoon, londonEvening));
}
}
}
| |
using System;
using System.Collections.Generic;
using CoreGraphics;
using CoreAnimation;
using Foundation;
using UIKit;
using Toggl.Phoebe.Analytics;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Models;
using Toggl.Phoebe.Data.Views;
using XPlatUtils;
using Toggl.Ross.DataSources;
using Toggl.Ross.Theme;
using Toggl.Ross.Views;
namespace Toggl.Ross.ViewControllers
{
public class ProjectSelectionViewController : UITableViewController
{
private const float CellSpacing = 4f;
private readonly TimeEntryModel model;
public ProjectSelectionViewController (TimeEntryModel model) : base (UITableViewStyle.Plain)
{
this.model = model;
Title = "ProjectTitle".Tr ();
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
View.Apply (Style.Screen);
EdgesForExtendedLayout = UIRectEdge.None;
new Source (this).Attach ();
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Select Project";
}
public Action ProjectSelected { get; set; }
private async void Finish (TaskModel task = null, ProjectModel project = null, WorkspaceModel workspace = null)
{
project = task != null ? task.Project : project;
if (project != null) {
await project.LoadAsync ();
workspace = project.Workspace;
}
if (project != null || task != null || workspace != null) {
model.Workspace = workspace;
model.Project = project;
model.Task = task;
await model.SaveAsync ();
}
var cb = ProjectSelected;
if (cb != null) {
cb ();
} else {
// Pop to previous view controller
var vc = NavigationController.ViewControllers;
var i = Array.IndexOf (vc, this) - 1;
if (i >= 0) {
NavigationController.PopToViewController (vc [i], true);
}
}
}
class Source : PlainDataViewSource<object>
{
private readonly static NSString WorkspaceHeaderId = new NSString ("SectionHeaderId");
private readonly static NSString ProjectCellId = new NSString ("ProjectCellId");
private readonly static NSString TaskCellId = new NSString ("TaskCellId");
private readonly ProjectSelectionViewController controller;
private readonly HashSet<Guid> expandedProjects = new HashSet<Guid> ();
public Source (ProjectSelectionViewController controller)
: base (controller.TableView, new ProjectAndTaskView ())
{
this.controller = controller;
}
public override void Attach ()
{
base.Attach ();
controller.TableView.RegisterClassForCellReuse (typeof (WorkspaceHeaderCell), WorkspaceHeaderId);
controller.TableView.RegisterClassForCellReuse (typeof (ProjectCell), ProjectCellId);
controller.TableView.RegisterClassForCellReuse (typeof (TaskCell), TaskCellId);
controller.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
}
private void ToggleTasksExpanded (Guid projectId)
{
SetTasksExpanded (projectId, !expandedProjects.Contains (projectId));
}
private void SetTasksExpanded (Guid projectId, bool expand)
{
if (expand && expandedProjects.Add (projectId)) {
Update ();
} else if (!expand && expandedProjects.Remove (projectId)) {
Update ();
}
}
public override nfloat EstimatedHeight (UITableView tableView, NSIndexPath indexPath)
{
return 60f;
}
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
var row = GetRow (indexPath);
if (row is ProjectAndTaskView.Workspace) {
return 42f;
}
if (row is TaskModel) {
return 49f;
}
return EstimatedHeight (tableView, indexPath);
}
public override nfloat EstimatedHeightForHeader (UITableView tableView, nint section)
{
return -1f;
}
public override nfloat GetHeightForHeader (UITableView tableView, nint section)
{
return EstimatedHeightForHeader (tableView, section);
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var row = GetRow (indexPath);
var project = row as ProjectAndTaskView.Project;
if (project != null) {
var cell = (ProjectCell)tableView.DequeueReusableCell (ProjectCellId, indexPath);
cell.Bind (project);
if (project.Data != null && project.Data.Id != Guid.Empty) {
var projectId = project.Data.Id;
cell.ToggleTasks = () => ToggleTasksExpanded (projectId);
} else {
cell.ToggleTasks = null;
}
return cell;
}
var taskData = row as TaskData;
if (taskData != null) {
var cell = (TaskCell)tableView.DequeueReusableCell (TaskCellId, indexPath);
cell.Bind ((TaskModel)taskData);
var rows = GetCachedRows (GetSection (indexPath.Section));
cell.IsFirst = indexPath.Row < 1 || ! (rows [indexPath.Row - 1] is TaskModel);
cell.IsLast = indexPath.Row >= rows.Count || ! (rows [indexPath.Row + 1] is TaskModel);
return cell;
}
var workspace = row as ProjectAndTaskView.Workspace;
if (workspace != null) {
var cell = (WorkspaceHeaderCell)tableView.DequeueReusableCell (WorkspaceHeaderId, indexPath);
cell.Bind (workspace);
return cell;
}
throw new InvalidOperationException (String.Format ("Unknown row type {0}", row.GetType ()));
}
public override UIView GetViewForHeader (UITableView tableView, nint section)
{
return new UIView ().Apply (Style.ProjectList.HeaderBackgroundView);
}
public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath)
{
return false;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var m = GetRow (indexPath);
if (m is TaskData) {
var data = (TaskData)m;
controller.Finish ((TaskModel)data);
} else if (m is ProjectAndTaskView.Project) {
var wrap = (ProjectAndTaskView.Project)m;
if (wrap.IsNoProject) {
controller.Finish (workspace: new WorkspaceModel (wrap.WorkspaceId));
} else if (wrap.IsNewProject) {
var proj = (ProjectModel)wrap.Data;
// Show create project dialog instead
var next = new NewProjectViewController (proj.Workspace, proj.Color) {
ProjectCreated = (p) => controller.Finish (project: p),
};
controller.NavigationController.PushViewController (next, true);
} else {
controller.Finish (project: (ProjectModel)wrap.Data);
}
} else if (m is ProjectAndTaskView.Workspace) {
var wrap = (ProjectAndTaskView.Workspace)m;
controller.Finish (workspace: (WorkspaceModel)wrap.Data);
}
tableView.DeselectRow (indexPath, true);
}
protected override IEnumerable<object> GetRows (string section)
{
foreach (var row in DataView.Data) {
var task = row as TaskData;
if (task != null && !expandedProjects.Contains (task.ProjectId)) {
continue;
}
yield return row;
}
}
}
private class ProjectCell : ModelTableViewCell<ProjectAndTaskView.Project>
{
private UIView textContentView;
private UILabel projectLabel;
private UILabel clientLabel;
private UIButton tasksButton;
private ProjectModel model;
public ProjectCell (IntPtr handle) : base (handle)
{
this.Apply (Style.Screen);
BackgroundView = new UIView ();
ContentView.Add (textContentView = new UIView ());
ContentView.Add (tasksButton = new UIButton ().Apply (Style.ProjectList.TasksButtons));
textContentView.Add (projectLabel = new UILabel ().Apply (Style.ProjectList.ProjectLabel));
textContentView.Add (clientLabel = new UILabel ().Apply (Style.ProjectList.ClientLabel));
var maskLayer = new CAGradientLayer () {
AnchorPoint = CGPoint.Empty,
StartPoint = new CGPoint (0.0f, 0.0f),
EndPoint = new CGPoint (1.0f, 0.0f),
Colors = new [] {
UIColor.FromWhiteAlpha (1, 1).CGColor,
UIColor.FromWhiteAlpha (1, 1).CGColor,
UIColor.FromWhiteAlpha (1, 0).CGColor,
},
Locations = new [] {
NSNumber.FromFloat (0f),
NSNumber.FromFloat (0.9f),
NSNumber.FromFloat (1f),
},
};
textContentView.Layer.Mask = maskLayer;
tasksButton.TouchUpInside += OnTasksButtonTouchUpInside;
}
protected override void OnDataSourceChanged ()
{
model = null;
if (DataSource != null) {
model = (ProjectModel)DataSource.Data;
}
base.OnDataSourceChanged ();
}
private void OnTasksButtonTouchUpInside (object sender, EventArgs e)
{
var cb = ToggleTasks;
if (cb != null) {
cb ();
}
}
public Action ToggleTasks { get; set; }
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
var contentFrame = new CGRect (0, CellSpacing / 2, Frame.Width, Frame.Height - CellSpacing);
SelectedBackgroundView.Frame = BackgroundView.Frame = ContentView.Frame = contentFrame;
if (!tasksButton.Hidden) {
var virtualWidth = contentFrame.Height;
var buttonWidth = tasksButton.CurrentBackgroundImage.Size.Width;
var extraPadding = (virtualWidth - buttonWidth) / 2f;
tasksButton.Frame = new CGRect (
contentFrame.Width - virtualWidth + extraPadding, extraPadding,
buttonWidth, buttonWidth);
contentFrame.Width -= virtualWidth;
}
contentFrame.X += 13f;
contentFrame.Width -= 13f;
textContentView.Frame = contentFrame;
textContentView.Layer.Mask.Bounds = contentFrame;
contentFrame = new CGRect (CGPoint.Empty, contentFrame.Size);
if (clientLabel.Hidden) {
// Only display single item, so make it fill the whole text frame
var bounds = GetBoundingRect (projectLabel);
projectLabel.Frame = new CGRect (
x: 0,
y: (contentFrame.Height - bounds.Height + projectLabel.Font.Descender) / 2f,
width: contentFrame.Width,
height: bounds.Height
);
} else {
// Carefully craft the layout
var bounds = GetBoundingRect (projectLabel);
projectLabel.Frame = new CGRect (
x: 0,
y: (contentFrame.Height - bounds.Height + projectLabel.Font.Descender) / 2f,
width: bounds.Width,
height: bounds.Height
);
const float clientLeftMargin = 7.5f;
bounds = GetBoundingRect (clientLabel);
clientLabel.Frame = new CGRect (
x: projectLabel.Frame.X + projectLabel.Frame.Width + clientLeftMargin,
y: (float)Math.Floor (projectLabel.Frame.Y + projectLabel.Font.Ascender - clientLabel.Font.Ascender),
width: bounds.Width,
height: bounds.Height
);
}
}
private static CGRect GetBoundingRect (UILabel view)
{
var attrs = new UIStringAttributes () {
Font = view.Font,
};
var rect = ((NSString) (view.Text ?? String.Empty)).GetBoundingRect (
new CGSize (Single.MaxValue, Single.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
attrs, null);
rect.Height = (float)Math.Ceiling (rect.Height);
return rect;
}
protected override void ResetTrackedObservables ()
{
Tracker.MarkAllStale ();
if (model != null) {
Tracker.Add (model, HandleProjectPropertyChanged);
if (model.Client != null) {
Tracker.Add (model.Client, HandleClientPropertyChanged);
}
}
Tracker.ClearStale ();
}
private void HandleProjectPropertyChanged (string prop)
{
if (prop == ProjectModel.PropertyClient
|| prop == ProjectModel.PropertyName
|| prop == ProjectModel.PropertyColor) {
Rebind ();
}
}
private void HandleClientPropertyChanged (string prop)
{
if (prop == ClientModel.PropertyName) {
Rebind ();
}
}
protected override void Rebind ()
{
ResetTrackedObservables ();
UIColor projectColor;
string projectName;
string clientName = String.Empty;
int taskCount = 0;
if (DataSource.IsNoProject) {
projectColor = Color.Gray;
projectName = "ProjectNoProject".Tr ();
projectLabel.Apply (Style.ProjectList.NoProjectLabel);
} else if (DataSource.IsNewProject) {
projectColor = Color.LightestGray;
projectName = "ProjectNewProject".Tr ();
projectLabel.Apply (Style.ProjectList.NewProjectLabel);
} else if (model != null) {
projectColor = UIColor.Clear.FromHex (model.GetHexColor ());
projectName = model.Name;
clientName = model.Client != null ? model.Client.Name : String.Empty;
taskCount = DataSource.Tasks.Count;
projectLabel.Apply (Style.ProjectList.ProjectLabel);
} else {
return;
}
if (String.IsNullOrWhiteSpace (projectName)) {
projectName = "ProjectNoNameProject".Tr ();
clientName = String.Empty;
}
if (!String.IsNullOrWhiteSpace (projectName)) {
projectLabel.Text = projectName;
projectLabel.Hidden = false;
if (!String.IsNullOrEmpty (clientName)) {
clientLabel.Text = clientName;
clientLabel.Hidden = false;
} else {
clientLabel.Hidden = true;
}
} else {
projectLabel.Hidden = true;
clientLabel.Hidden = true;
}
tasksButton.Hidden = taskCount < 1;
if (!tasksButton.Hidden) {
tasksButton.SetTitle (taskCount.ToString (), UIControlState.Normal);
tasksButton.SetTitleColor (projectColor, UIControlState.Normal);
}
BackgroundView.BackgroundColor = projectColor;
}
}
private class TaskCell : ModelTableViewCell<TaskModel>
{
private readonly UILabel nameLabel;
private readonly UIView separatorView;
private bool isFirst;
private bool isLast;
public TaskCell (IntPtr handle) : base (handle)
{
this.Apply (Style.Screen);
ContentView.Add (nameLabel = new UILabel ().Apply (Style.ProjectList.TaskLabel));
ContentView.Add (separatorView = new UIView ().Apply (Style.ProjectList.TaskSeparator));
BackgroundView = new UIView ().Apply (Style.ProjectList.TaskBackground);
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
var contentFrame = new CGRect (0, 0, Frame.Width, Frame.Height);
if (isFirst) {
contentFrame.Y += CellSpacing / 2;
contentFrame.Height -= CellSpacing / 2;
}
if (isLast) {
contentFrame.Height -= CellSpacing / 2;
}
SelectedBackgroundView.Frame = BackgroundView.Frame = ContentView.Frame = contentFrame;
// Add padding
contentFrame.X = 15f;
contentFrame.Y = 0;
contentFrame.Width -= 15f;
nameLabel.Frame = contentFrame;
separatorView.Frame = new CGRect (
contentFrame.X, contentFrame.Y + contentFrame.Height - 1f,
contentFrame.Width, 1f);
}
protected override void Rebind ()
{
ResetTrackedObservables ();
var taskName = DataSource.Name;
if (String.IsNullOrWhiteSpace (taskName)) {
taskName = "ProjectNoNameTask".Tr ();
}
nameLabel.Text = taskName;
}
protected override void ResetTrackedObservables ()
{
Tracker.MarkAllStale ();
if (DataSource != null) {
Tracker.Add (DataSource, HandleTaskPropertyChanged);
}
Tracker.ClearStale ();
}
private void HandleTaskPropertyChanged (string prop)
{
if (prop == TaskModel.PropertyName) {
Rebind ();
}
}
public bool IsFirst
{
get { return isFirst; }
set {
if (isFirst == value) {
return;
}
isFirst = value;
SetNeedsLayout ();
}
}
public bool IsLast
{
get { return isLast; }
set {
if (isLast == value) {
return;
}
isLast = value;
SetNeedsLayout ();
separatorView.Hidden = isLast;
}
}
}
private class WorkspaceHeaderCell : ModelTableViewCell<ProjectAndTaskView.Workspace>
{
private const float HorizSpacing = 15f;
private readonly UILabel nameLabel;
private WorkspaceModel model;
public WorkspaceHeaderCell (IntPtr handle) : base (handle)
{
this.Apply (Style.Screen);
nameLabel = new UILabel ().Apply (Style.ProjectList.HeaderLabel);
ContentView.AddSubview (nameLabel);
BackgroundView = new UIView ().Apply (Style.ProjectList.HeaderBackgroundView);
UserInteractionEnabled = false;
}
protected override void OnDataSourceChanged ()
{
model = null;
if (DataSource != null) {
model = (WorkspaceModel)DataSource.Data;
}
base.OnDataSourceChanged ();
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
var contentFrame = ContentView.Frame;
nameLabel.Frame = new CGRect (
x: HorizSpacing,
y: 0,
width: contentFrame.Width - 2 * HorizSpacing,
height: contentFrame.Height
);
}
protected override void ResetTrackedObservables ()
{
Tracker.MarkAllStale ();
if (model != null) {
Tracker.Add (model, HandleClientPropertyChanged);
}
Tracker.ClearStale ();
}
private void HandleClientPropertyChanged (string prop)
{
if (prop == WorkspaceModel.PropertyName) {
Rebind ();
}
}
protected override void Rebind ()
{
ResetTrackedObservables ();
if (model != null) {
nameLabel.Text = model.Name;
}
}
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Transactions;
using NUnit.Framework;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Job;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Xml;
using Rhino.Mocks;
using Is = NUnit.Framework.Is;
namespace Quartz.Tests.Unit.Xml
{
/// <summary>
/// Tests for <see cref="XMLSchedulingDataProcessor" />.
/// </summary>
/// <author>Marko Lahma (.NET)</author>
[TestFixture]
public class XMLSchedulingDataProcessorTest
{
private XMLSchedulingDataProcessor processor;
private IScheduler mockScheduler;
private TransactionScope scope;
[SetUp]
public void SetUp()
{
processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
mockScheduler = MockRepository.GenerateMock<IScheduler>();
scope = new TransactionScope();
}
[TearDown]
public void TearDown()
{
if (scope != null)
{
scope.Dispose();
}
}
[Test]
public void TestScheduling_RichConfiguration()
{
Stream s = ReadJobXmlFromEmbeddedResource("RichConfiguration_20.xml");
processor.ProcessStream(s, null);
Assert.IsFalse(processor.OverWriteExistingData);
Assert.IsTrue(processor.IgnoreDuplicates);
processor.ScheduleJobs(mockScheduler);
mockScheduler.AssertWasCalled(x => x.ScheduleJob(Arg<ITrigger>.Is.NotNull), options => options.Repeat.Times(5));
}
[Test]
public void TestScheduling_MinimalConfiguration()
{
Stream s = ReadJobXmlFromEmbeddedResource("MinimalConfiguration_20.xml");
processor.ProcessStream(s, null);
Assert.IsFalse(processor.OverWriteExistingData);
processor.ScheduleJobs(mockScheduler);
}
[Test]
public void TestScheduling_QuartzNet250()
{
Stream s = ReadJobXmlFromEmbeddedResource("QRTZNET250.xml");
processor.ProcessStreamAndScheduleJobs(s, mockScheduler);
mockScheduler.AssertWasCalled(x => x.AddJob(Arg<IJobDetail>.Is.NotNull, Arg<bool>.Is.Anything, Arg<bool>.Is.Equal(true)), constraints => constraints.Repeat.Twice());
mockScheduler.AssertWasCalled(x => x.ScheduleJob(Arg<ITrigger>.Is.NotNull), constraints => constraints.Repeat.Twice());
}
[Test]
public void TestSchedulingWhenUpdatingScheduleBasedOnExistingTrigger()
{
DateTimeOffset startTime = new DateTimeOffset(2012, 12, 30, 1, 0, 0, TimeSpan.Zero);
DateTimeOffset previousFireTime = new DateTimeOffset(2013, 2, 15, 15, 0, 0, TimeSpan.Zero);
SimpleTriggerImpl existing = new SimpleTriggerImpl("triggerToReplace", "groupToReplace", startTime, null, SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromHours(1));
existing.JobKey = new JobKey("jobName1", "jobGroup1");
existing.SetPreviousFireTimeUtc(previousFireTime);
existing.GetNextFireTimeUtc();
mockScheduler.Stub(x => x.GetTrigger(existing.Key)).Return(existing);
Stream s = ReadJobXmlFromEmbeddedResource("ScheduleRelativeToOldTrigger.xml");
processor.ProcessStream(s, null);
processor.ScheduleJobs(mockScheduler);
// check that last fire time was taken from existing trigger
mockScheduler.Stub(x => x.RescheduleJob(null, null)).IgnoreArguments();
var args = mockScheduler.GetArgumentsForCallsMadeOn(x => x.RescheduleJob(null, null));
ITrigger argumentTrigger = (ITrigger) args[0][1];
// replacement trigger should have same start time and next fire relative to old trigger's last fire time
Assert.That(argumentTrigger, Is.Not.Null);
Assert.That(argumentTrigger.StartTimeUtc, Is.EqualTo(startTime));
Assert.That(argumentTrigger.GetNextFireTimeUtc(), Is.EqualTo(previousFireTime.AddSeconds(10)));
}
/// <summary>
/// The default XMLSchedulingDataProcessor will setOverWriteExistingData(true), and we want to
/// test programmatically overriding this value.
/// </summary>
/// <remarks>
/// Note that XMLSchedulingDataProcessor#processFileAndScheduleJobs(Scheduler,boolean) will only
/// read default "quartz_data.xml" in current working directory. So to test this, we must create
/// this file. If this file already exist, it will be overwritten!
/// </remarks>
[Test]
public void TestOverwriteFlag()
{
// create temp file
string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName;
using (TextWriter writer = new StreamWriter(tempFileName, false))
{
using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("SimpleJobTrigger.xml")))
{
writer.Write(reader.ReadToEnd());
writer.Flush();
writer.Close();
}
}
IScheduler scheduler = null;
try
{
StdSchedulerFactory factory = new StdSchedulerFactory();
scheduler = StdSchedulerFactory.GetDefaultScheduler();
// Let's setup a fixture job data that we know test is not going modify it.
IJobDetail job = JobBuilder.Create<NoOpJob>()
.WithIdentity("job1").UsingJobData("foo", "dont_chg_me").Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
scheduler.ScheduleJob(job, trigger);
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
try
{
processor.ProcessFileAndScheduleJobs(scheduler, false);
Assert.Fail("OverWriteExisting flag didn't work. We should get Exception when overwrite is set to false.");
}
catch (ObjectAlreadyExistsException)
{
// This is expected. Do nothing.
}
// We should still have what we start with.
Assert.AreEqual(1, scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count);
Assert.AreEqual(1, scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count);
job = scheduler.GetJobDetail(JobKey.Create("job1"));
String fooValue = job.JobDataMap.GetString("foo");
Assert.AreEqual("dont_chg_me", fooValue);
}
finally
{
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
// shutdown scheduler
if (scheduler != null)
{
scheduler.Shutdown();
}
}
}
/** QTZ-187 */
[Test]
public void TesDirectivesNoOverwriteWithIgnoreDups()
{
// create temp file
string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName;
using (TextWriter writer = new StreamWriter(tempFileName, false))
{
using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml")))
{
writer.Write(reader.ReadToEnd());
writer.Flush();
writer.Close();
}
}
IScheduler scheduler = null;
try
{
StdSchedulerFactory factory = new StdSchedulerFactory();
scheduler = StdSchedulerFactory.GetDefaultScheduler();
// Setup existing job with same names as in xml data.
IJobDetail job = JobBuilder.Create<NoOpJob>()
.WithIdentity("job1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("job1")
.WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
scheduler.ScheduleJob(job, trigger);
job = JobBuilder.Create<NoOpJob>()
.WithIdentity("job2")
.Build();
trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
scheduler.ScheduleJob(job, trigger);
// Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true
ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper();
loadHelper.Initialize();
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper);
processor.ProcessFileAndScheduleJobs(tempFileName, scheduler);
Assert.AreEqual(2, scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count);
Assert.AreEqual(2, scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count);
}
finally
{
if (scheduler != null)
{
scheduler.Shutdown();
}
}
}
[Test]
public void MultipleScheduleElementsShouldBeSupported()
{
Stream s = ReadJobXmlFromEmbeddedResource("RichConfiguration_20.xml");
processor.ProcessStream(s, null);
processor.ScheduleJobs(mockScheduler);
mockScheduler.AssertWasCalled(x => x.ScheduleJob(Arg<IJobDetail>.Matches(p => p.Key.Name == "sched2_job"), Arg<ITrigger>.Is.Anything));
mockScheduler.AssertWasCalled(x => x.ScheduleJob(Arg<ITrigger>.Matches(p => p.Key.Name == "sched2_trig")));
}
[Test]
public void TestSimpleTriggerNoRepeat()
{
IScheduler scheduler = CreateDbBackedScheduler();
try
{
processor.ProcessStreamAndScheduleJobs(ReadJobXmlFromEmbeddedResource("SimpleTriggerNoRepeat.xml"), scheduler);
Assert.That(scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count, Is.EqualTo(1));
Assert.That(scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count, Is.EqualTo(1));
}
finally
{
if (scheduler != null)
{
scheduler.Shutdown();
}
}
}
private static Stream ReadJobXmlFromEmbeddedResource(string resourceName)
{
string fullName = "Quartz.Tests.Unit.Xml.TestData." + resourceName;
Stream stream = typeof (XMLSchedulingDataProcessorTest).Assembly.GetManifestResourceStream(fullName);
Assert.That(stream, Is.Not.Null, "resource " + resourceName + " not found");
return new StreamReader(stream).BaseStream;
}
[Test]
public void TestRemoveJobTypeNotFound()
{
var scheduler = CreateDbBackedScheduler();
try
{
string jobName = "testjob1";
IJobDetail jobDetail = JobBuilder.Create<NoOpJob>()
.WithIdentity(jobName, "DEFAULT")
.UsingJobData("foo", "foo")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(jobName, "DEFAULT")
.WithSchedule(CronScheduleBuilder.CronSchedule("* * * * * ?"))
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
IJobDetail jobDetail2 = scheduler.GetJobDetail(jobDetail.Key);
ITrigger trigger2 = scheduler.GetTrigger(trigger.Key);
Assert.That(jobDetail2.JobDataMap.GetString("foo"), Is.EqualTo("foo"));
Assert.That(trigger2, Is.InstanceOf<ICronTrigger>());
ModifyStoredJobType();
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
// when
processor.ProcessStreamAndScheduleJobs(ReadJobXmlFromEmbeddedResource("delete-no-job-class.xml"), scheduler);
jobDetail2 = scheduler.GetJobDetail(jobDetail.Key);
trigger2 = scheduler.GetTrigger(trigger.Key);
Assert.That(trigger2, Is.Null);
Assert.That(jobDetail2, Is.Null);
jobDetail2 = scheduler.GetJobDetail(new JobKey("job1", "DEFAULT"));
trigger2 = scheduler.GetTrigger(new TriggerKey("job1", "DEFAULT"));
Assert.That(jobDetail2.JobDataMap.GetString("foo"), Is.EqualTo("bar"));
Assert.That(trigger2, Is.InstanceOf<ISimpleTrigger>());
}
finally
{
scheduler.Shutdown(false);
}
}
private static IScheduler CreateDbBackedScheduler()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "AUTO";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;";
properties["quartz.dataSource.default.provider"] = "SqlServer-20";
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler scheduler = sf.GetScheduler();
scheduler.Clear();
return scheduler;
}
[Test]
public void TestOverwriteJobTypeNotFound()
{
IScheduler scheduler = CreateDbBackedScheduler();
try
{
string jobName = "job1";
IJobDetail jobDetail = JobBuilder.Create<NoOpJob>()
.WithIdentity(jobName, "DEFAULT")
.UsingJobData("foo", "foo")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(jobName, "DEFAULT")
.WithSchedule(CronScheduleBuilder.CronSchedule("* * * * * ?"))
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
IJobDetail jobDetail2 = scheduler.GetJobDetail(jobDetail.Key);
ITrigger trigger2 = scheduler.GetTrigger(trigger.Key);
Assert.That(jobDetail2.JobDataMap.GetString("foo"), Is.EqualTo("foo"));
Assert.That(trigger2, Is.InstanceOf<ICronTrigger>());
ModifyStoredJobType();
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
processor.ProcessStreamAndScheduleJobs(ReadJobXmlFromEmbeddedResource("overwrite-no-jobclass.xml"), scheduler);
jobDetail2 = scheduler.GetJobDetail(jobDetail.Key);
trigger2 = scheduler.GetTrigger(trigger.Key);
Assert.That(jobDetail2.JobDataMap.GetString("foo"), Is.EqualTo("bar"));
Assert.That(trigger2, Is.InstanceOf<ISimpleTrigger>());
}
finally
{
scheduler.Shutdown(false);
}
}
private void ModifyStoredJobType()
{
using (var conn = DBConnectionManager.Instance.GetConnection("default"))
{
conn.Open();
using (IDbCommand dbCommand = conn.CreateCommand())
{
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "update qrtz_job_details set job_class_name='com.FakeNonExistsJob'";
dbCommand.ExecuteNonQuery();
}
conn.Close();
}
}
[Test]
public void TestDirectivesOverwriteWithNoIgnoreDups()
{
IScheduler scheduler = null;
try
{
StdSchedulerFactory factory = new StdSchedulerFactory();
scheduler = factory.GetScheduler();
// Setup existing job with same names as in xml data.
string job1 = Guid.NewGuid().ToString();
IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity(job1).Build();
ITrigger trigger = TriggerBuilder.Create().WithIdentity(job1).WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
scheduler.ScheduleJob(job, trigger);
string job2 = Guid.NewGuid().ToString();
job = JobBuilder.Create<NoOpJob>().WithIdentity(job2).Build();
trigger = TriggerBuilder.Create().WithIdentity(job2).WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
scheduler.ScheduleJob(job, trigger);
// Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
processor.ProcessStream(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml"), "temp");
Assert.That(scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count, Is.EqualTo(2));
Assert.That(scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count, Is.EqualTo(2));
}
finally
{
if (scheduler != null)
{
scheduler.Shutdown();
}
}
}
}
}
| |
using System;
namespace GXPEngine
{
/// <summary>
/// Contains several functions for doing floating point Math
/// </summary>
public static class Mathf
{
/// <summary>
/// Constant PI
/// </summary>
public const float PI = (float)Math.PI;
/// <summary>
/// Returns the absolute value of specified number
/// </summary>
public static int Abs (int value) {
return (value<0)?-value:value;
}
/// <summary>
/// Returns the absolute value of specified number
/// </summary>
public static float Abs(float value) {
return (value<0)?-value:value;
}
/// <summary>
/// Returns the acosine of the specified number
/// </summary>
public static float Acos(float f) {
return (float)Math.Acos(f);
}
/// <summary>
/// Returns the arctangent of the specified number
/// </summary>
public static float Atan(float f) {
return (float)Math.Atan (f);
}
/// <summary>
/// Returns the angle whose tangent is the quotent of the specified values
/// </summary>
public static float Atan2(float y, float x) {
return (float)Math.Atan2 (y, x);
}
/// <summary>
/// Returns the smallest integer bigger greater than or equal to the specified number
/// </summary>
public static int Ceiling(float a) {
return (int)Math.Ceiling (a);
}
/// <summary>
/// Returns the cosine of the specified number
/// </summary>
public static float Cos(float f) {
return (float)Math.Cos (f);
}
/// <summary>
/// Returns the hyperbolic cosine of the specified number
/// </summary>
public static float Cosh(float value) {
return (float)Math.Cosh (value);
}
/// <summary>
/// Returns e raised to the given number
/// </summary>
public static float Exp(float f) {
return (float)Math.Exp (f);
}
/// <summary>
/// Returns the largest integer less than or equal to the specified value
/// </summary>
public static int Floor(float f) {
return (int)Math.Floor (f);
}
/// <summary>
/// Returns the natural logarithm of the specified number
/// </summary>
public static float Log(float f) {
return (float)Math.Log (f);
}
/// <summary>
/// Returns the log10 of the specified number
/// </summary>
public static float Log10(float f) {
return (float)Math.Log10(f);
}
/// <summary>
/// Returns the biggest of the two specified values
/// </summary>
public static float Max(float value1, float value2) {
return (value2 > value1)?value2:value1;
}
/// <summary>
/// Returns the biggest of the two specified values
/// </summary>
public static int Max(int value1, int value2) {
return (value2 > value1)?value2:value1;
}
/// <summary>
/// Returns the smallest of the two specified values
/// </summary>
public static float Min(float value1, float value2) {
return (value2<value1)?value2:value1;
}
/// <summary>
/// Returns the smallest of the two specified values
/// </summary>
public static int Min(int value1, int value2) {
return (value2<value1)?value2:value1;
}
/// <summary>
/// Returns x raised to the power of y
/// </summary>
public static float Pow(float x, float y) {
return (float)Math.Pow (x, y);
}
/// <summary>
/// Returns the nearest integer to the specified value
/// </summary>
public static int Round(float f) {
return (int)Math.Round (f);
}
/// <summary>
/// Returns a value indicating the sign of the specified number (-1=negative, 0=zero, 1=positive)
/// </summary>
public static int Sign(float f) {
if (f < 0) return -1;
if (f > 0) return 1;
return 0;
}
/// <summary>
/// Returns a value indicating the sign of the specified number (-1=negative, 0=zero, 1=positive)
/// </summary>
public static int Sign(int f) {
if (f < 0) return -1;
if (f > 0) return 1;
return 0;
}
/// <summary>
/// Returns the sine of the specified number
/// </summary>
public static float Sin(float f) {
return (float)Math.Sin (f);
}
/// <summary>
/// Returns the hyperbolic sine of the specified number
/// </summary>
public static float Sinh(float value) {
return (float)Math.Sinh (value);
}
/// <summary>
/// Returns the square root of the specified number
/// </summary>
public static float Sqrt(float f) {
return (float)Math.Sqrt (f);
}
/// <summary>
/// Returns the tangent of the specified number
/// </summary>
public static float Tan(float f) {
return (float)Math.Tan (f);
}
/// <summary>
/// Returns the hyperbolic tangent of the specified number
/// </summary>
public static float Tanh(float value) {
return (float)Math.Tanh (value);
}
/// <summary>
/// Calculates the integral part of the specified number
/// </summary>
public static float Truncate(float f) {
return (float)Math.Truncate (f);
}
}
}
| |
// 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="ConversionCustomVariableServiceClient"/> instances.</summary>
public sealed partial class ConversionCustomVariableServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ConversionCustomVariableServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ConversionCustomVariableServiceSettings"/>.</returns>
public static ConversionCustomVariableServiceSettings GetDefault() => new ConversionCustomVariableServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionCustomVariableServiceSettings"/> object with default settings.
/// </summary>
public ConversionCustomVariableServiceSettings()
{
}
private ConversionCustomVariableServiceSettings(ConversionCustomVariableServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetConversionCustomVariableSettings = existing.GetConversionCustomVariableSettings;
MutateConversionCustomVariablesSettings = existing.MutateConversionCustomVariablesSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionCustomVariableServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionCustomVariableServiceClient.GetConversionCustomVariable</c> and
/// <c>ConversionCustomVariableServiceClient.GetConversionCustomVariableAsync</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 GetConversionCustomVariableSettings { 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>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionCustomVariableServiceClient.MutateConversionCustomVariables</c> and
/// <c>ConversionCustomVariableServiceClient.MutateConversionCustomVariablesAsync</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 MutateConversionCustomVariablesSettings { 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="ConversionCustomVariableServiceSettings"/> object.</returns>
public ConversionCustomVariableServiceSettings Clone() => new ConversionCustomVariableServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionCustomVariableServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class ConversionCustomVariableServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionCustomVariableServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionCustomVariableServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionCustomVariableServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionCustomVariableServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionCustomVariableServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionCustomVariableServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionCustomVariableServiceClient Build()
{
ConversionCustomVariableServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionCustomVariableServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionCustomVariableServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionCustomVariableServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionCustomVariableServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionCustomVariableServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionCustomVariableServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionCustomVariableServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
ConversionCustomVariableServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionCustomVariableServiceClient.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>ConversionCustomVariableService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion custom variables.
/// </remarks>
public abstract partial class ConversionCustomVariableServiceClient
{
/// <summary>
/// The default endpoint for the ConversionCustomVariableService 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 ConversionCustomVariableService scopes.</summary>
/// <remarks>
/// The default ConversionCustomVariableService 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="ConversionCustomVariableServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionCustomVariableServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionCustomVariableServiceClient"/>.</returns>
public static stt::Task<ConversionCustomVariableServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionCustomVariableServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionCustomVariableServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionCustomVariableServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionCustomVariableServiceClient"/>.</returns>
public static ConversionCustomVariableServiceClient Create() =>
new ConversionCustomVariableServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionCustomVariableServiceClient"/> 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="ConversionCustomVariableServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionCustomVariableServiceClient"/>.</returns>
internal static ConversionCustomVariableServiceClient Create(grpccore::CallInvoker callInvoker, ConversionCustomVariableServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient = new ConversionCustomVariableService.ConversionCustomVariableServiceClient(callInvoker);
return new ConversionCustomVariableServiceClientImpl(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 ConversionCustomVariableService client</summary>
public virtual ConversionCustomVariableService.ConversionCustomVariableServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion custom variable.
///
/// 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::ConversionCustomVariable GetConversionCustomVariable(GetConversionCustomVariableRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion custom variable.
///
/// 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::ConversionCustomVariable> GetConversionCustomVariableAsync(GetConversionCustomVariableRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion custom variable.
///
/// 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::ConversionCustomVariable> GetConversionCustomVariableAsync(GetConversionCustomVariableRequest request, st::CancellationToken cancellationToken) =>
GetConversionCustomVariableAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionCustomVariable GetConversionCustomVariable(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionCustomVariable(new GetConversionCustomVariableRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable 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::ConversionCustomVariable> GetConversionCustomVariableAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionCustomVariableAsync(new GetConversionCustomVariableRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable 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::ConversionCustomVariable> GetConversionCustomVariableAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetConversionCustomVariableAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionCustomVariable GetConversionCustomVariable(gagvr::ConversionCustomVariableName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionCustomVariable(new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable 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::ConversionCustomVariable> GetConversionCustomVariableAsync(gagvr::ConversionCustomVariableName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionCustomVariableAsync(new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion custom variable.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion custom variable 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::ConversionCustomVariable> GetConversionCustomVariableAsync(gagvr::ConversionCustomVariableName resourceName, st::CancellationToken cancellationToken) =>
GetConversionCustomVariableAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [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 MutateConversionCustomVariablesResponse MutateConversionCustomVariables(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [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<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [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<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, st::CancellationToken cancellationToken) =>
MutateConversionCustomVariablesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion custom variables are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion custom
/// variables.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionCustomVariablesResponse MutateConversionCustomVariables(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionCustomVariables(new MutateConversionCustomVariablesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion custom variables are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion custom
/// variables.
/// </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<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionCustomVariablesAsync(new MutateConversionCustomVariablesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion custom variables are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion custom
/// variables.
/// </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<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, st::CancellationToken cancellationToken) =>
MutateConversionCustomVariablesAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionCustomVariableService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion custom variables.
/// </remarks>
public sealed partial class ConversionCustomVariableServiceClientImpl : ConversionCustomVariableServiceClient
{
private readonly gaxgrpc::ApiCall<GetConversionCustomVariableRequest, gagvr::ConversionCustomVariable> _callGetConversionCustomVariable;
private readonly gaxgrpc::ApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse> _callMutateConversionCustomVariables;
/// <summary>
/// Constructs a client wrapper for the ConversionCustomVariableService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionCustomVariableServiceSettings"/> used within this client.
/// </param>
public ConversionCustomVariableServiceClientImpl(ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient, ConversionCustomVariableServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionCustomVariableServiceSettings effectiveSettings = settings ?? ConversionCustomVariableServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetConversionCustomVariable = clientHelper.BuildApiCall<GetConversionCustomVariableRequest, gagvr::ConversionCustomVariable>(grpcClient.GetConversionCustomVariableAsync, grpcClient.GetConversionCustomVariable, effectiveSettings.GetConversionCustomVariableSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetConversionCustomVariable);
Modify_GetConversionCustomVariableApiCall(ref _callGetConversionCustomVariable);
_callMutateConversionCustomVariables = clientHelper.BuildApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse>(grpcClient.MutateConversionCustomVariablesAsync, grpcClient.MutateConversionCustomVariables, effectiveSettings.MutateConversionCustomVariablesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateConversionCustomVariables);
Modify_MutateConversionCustomVariablesApiCall(ref _callMutateConversionCustomVariables);
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_GetConversionCustomVariableApiCall(ref gaxgrpc::ApiCall<GetConversionCustomVariableRequest, gagvr::ConversionCustomVariable> call);
partial void Modify_MutateConversionCustomVariablesApiCall(ref gaxgrpc::ApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse> call);
partial void OnConstruction(ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient, ConversionCustomVariableServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionCustomVariableService client</summary>
public override ConversionCustomVariableService.ConversionCustomVariableServiceClient GrpcClient { get; }
partial void Modify_GetConversionCustomVariableRequest(ref GetConversionCustomVariableRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateConversionCustomVariablesRequest(ref MutateConversionCustomVariablesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested conversion custom variable.
///
/// 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::ConversionCustomVariable GetConversionCustomVariable(GetConversionCustomVariableRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionCustomVariableRequest(ref request, ref callSettings);
return _callGetConversionCustomVariable.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested conversion custom variable.
///
/// 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::ConversionCustomVariable> GetConversionCustomVariableAsync(GetConversionCustomVariableRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionCustomVariableRequest(ref request, ref callSettings);
return _callGetConversionCustomVariable.Async(request, callSettings);
}
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [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 MutateConversionCustomVariablesResponse MutateConversionCustomVariables(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionCustomVariablesRequest(ref request, ref callSettings);
return _callMutateConversionCustomVariables.Sync(request, callSettings);
}
/// <summary>
/// Creates or updates conversion custom variables. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionCustomVariableError]()
/// [DatabaseError]()
/// [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<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionCustomVariablesRequest(ref request, ref callSettings);
return _callMutateConversionCustomVariables.Async(request, callSettings);
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
//#define USE_ACTIVE_CONTACT_SET
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Contacts
{
/// <summary>
/// A contact edge is used to connect bodies and contacts together
/// in a contact graph where each body is a node and each contact
/// is an edge. A contact edge belongs to a doubly linked list
/// maintained in each attached body. Each contact has two contact
/// nodes, one for each attached body.
/// </summary>
public sealed class ContactEdge
{
/// <summary>
/// The contact
/// </summary>
public Contact contact;
/// <summary>
/// The next contact edge in the body's contact list
/// </summary>
public ContactEdge next;
/// <summary>
/// Provides quick access to the other body attached.
/// </summary>
public Body other;
/// <summary>
/// The previous contact edge in the body's contact list
/// </summary>
public ContactEdge prev;
}
/// <summary>
/// The class manages contact between two shapes. A contact exists for each overlapping
/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
/// that has no contact points.
/// </summary>
public class Contact
{
#region Properties/Fields
public Fixture fixtureA;
public Fixture fixtureB;
public float friction;
public float restitution;
/// <summary>
/// Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D.
/// </summary>
public Manifold manifold;
/// Get or set the desired tangent speed for a conveyor belt behavior. In meters per second.
public float tangentSpeed;
/// <summary>
/// Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current
/// time step (or sub-step in continuous collisions).
/// NOTE: If you are setting Enabled to a constant true or false, use the explicit Enable() or Disable() functions instead to
/// save the CPU from doing a branch operation.
/// </summary>
public bool enabled;
/// <summary>
/// Get the child primitive index for fixture A.
/// </summary>
/// <value>The child index A.</value>
public int childIndexA { get; internal set; }
/// <summary>
/// Get the child primitive index for fixture B.
/// </summary>
/// <value>The child index B.</value>
public int childIndexB { get; internal set; }
/// <summary>
/// Determines whether this contact is touching.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is touching; otherwise, <c>false</c>.
/// </returns>
public bool isTouching { get; set; }
internal bool islandFlag;
internal bool toiFlag;
internal bool filterFlag;
ContactType _type;
static EdgeShape _edge = new EdgeShape();
static ContactType[,] _contactRegisters = new[,]
{
{
ContactType.Circle,
ContactType.EdgeAndCircle,
ContactType.PolygonAndCircle,
ContactType.ChainAndCircle,
},
{
ContactType.EdgeAndCircle,
ContactType.NotSupported,
// 1,1 is invalid (no ContactType.Edge)
ContactType.EdgeAndPolygon,
ContactType.NotSupported,
// 1,3 is invalid (no ContactType.EdgeAndLoop)
},
{
ContactType.PolygonAndCircle,
ContactType.EdgeAndPolygon,
ContactType.Polygon,
ContactType.ChainAndPolygon,
},
{
ContactType.ChainAndCircle,
ContactType.NotSupported,
// 3,1 is invalid (no ContactType.EdgeAndLoop)
ContactType.ChainAndPolygon,
ContactType.NotSupported,
// 3,3 is invalid (no ContactType.Loop)
},
};
// Nodes for connecting bodies.
internal ContactEdge _nodeA = new ContactEdge();
internal ContactEdge _nodeB = new ContactEdge();
internal int _toiCount;
internal float _toi;
#endregion
Contact( Fixture fA, int indexA, Fixture fB, int indexB )
{
reset( fA, indexA, fB, indexB );
}
public void resetRestitution()
{
restitution = Settings.mixRestitution( fixtureA.restitution, fixtureB.restitution );
}
public void resetFriction()
{
friction = Settings.mixFriction( fixtureA.friction, fixtureB.friction );
}
/// <summary>
/// Gets the world manifold.
/// </summary>
public void getWorldManifold( out Vector2 normal, out FixedArray2<Vector2> points )
{
var bodyA = fixtureA.body;
var bodyB = fixtureB.body;
var shapeA = fixtureA.shape;
var shapeB = fixtureB.shape;
ContactSolver.WorldManifold.initialize( ref manifold, ref bodyA._xf, shapeA.radius, ref bodyB._xf, shapeB.radius, out normal, out points );
}
void reset( Fixture fA, int indexA, Fixture fB, int indexB )
{
enabled = true;
isTouching = false;
islandFlag = false;
filterFlag = false;
toiFlag = false;
fixtureA = fA;
fixtureB = fB;
childIndexA = indexA;
childIndexB = indexB;
manifold.pointCount = 0;
_nodeA.contact = null;
_nodeA.prev = null;
_nodeA.next = null;
_nodeA.other = null;
_nodeB.contact = null;
_nodeB.prev = null;
_nodeB.next = null;
_nodeB.other = null;
_toiCount = 0;
//FPE: We only set the friction and restitution if we are not destroying the contact
if( fixtureA != null && fixtureB != null )
{
friction = Settings.mixFriction( fixtureA.friction, fixtureB.friction );
restitution = Settings.mixRestitution( fixtureA.restitution, fixtureB.restitution );
}
tangentSpeed = 0;
}
/// <summary>
/// Update the contact manifold and touching status.
/// Note: do not assume the fixture AABBs are overlapping or are valid.
/// </summary>
/// <param name="contactManager">The contact manager.</param>
internal void update( ContactManager contactManager )
{
var bodyA = fixtureA.body;
var bodyB = fixtureB.body;
if( fixtureA == null || fixtureB == null )
return;
var oldManifold = manifold;
// Re-enable this contact.
enabled = true;
bool touching;
var wasTouching = isTouching;
var sensor = fixtureA.isSensor || fixtureB.isSensor;
// Is this contact a sensor?
if( sensor )
{
var shapeA = fixtureA.shape;
var shapeB = fixtureB.shape;
touching = Collision.Collision.testOverlap( shapeA, childIndexA, shapeB, childIndexB, ref bodyA._xf, ref bodyB._xf );
// Sensors don't generate manifolds.
manifold.pointCount = 0;
}
else
{
evaluate( ref manifold, ref bodyA._xf, ref bodyB._xf );
touching = manifold.pointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for( int i = 0; i < manifold.pointCount; ++i )
{
var mp2 = manifold.points[i];
mp2.normalImpulse = 0.0f;
mp2.tangentImpulse = 0.0f;
var id2 = mp2.id;
for( int j = 0; j < oldManifold.pointCount; ++j )
{
var mp1 = oldManifold.points[j];
if( mp1.id.key == id2.key )
{
mp2.normalImpulse = mp1.normalImpulse;
mp2.tangentImpulse = mp1.tangentImpulse;
break;
}
}
manifold.points[i] = mp2;
}
if( touching != wasTouching )
{
bodyA.isAwake = true;
bodyB.isAwake = true;
}
}
isTouching = touching;
if( wasTouching == false )
{
if( touching )
{
if( Settings.allCollisionCallbacksAgree )
{
bool enabledA = true, enabledB = true;
// Report the collision to both participants. Track which ones returned true so we can
// later call OnSeparation if the contact is disabled for a different reason.
if( fixtureA.onCollision != null )
foreach( OnCollisionEventHandler handler in fixtureA.onCollision.GetInvocationList() )
enabledA = handler( fixtureA, fixtureB, this ) && enabledA;
// Reverse the order of the reported fixtures. The first fixture is always the one that the
// user subscribed to.
if( fixtureB.onCollision != null )
foreach( OnCollisionEventHandler handler in fixtureB.onCollision.GetInvocationList() )
enabledB = handler( fixtureB, fixtureA, this ) && enabledB;
enabled = enabledA && enabledB;
// BeginContact can also return false and disable the contact
if( enabledA && enabledB && contactManager.onBeginContact != null )
enabled = contactManager.onBeginContact( this );
}
else
{
// Report the collision to both participants:
if( fixtureA.onCollision != null )
foreach( OnCollisionEventHandler handler in fixtureA.onCollision.GetInvocationList() )
enabled = handler( fixtureA, fixtureB, this );
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
if( fixtureB.onCollision != null )
foreach( OnCollisionEventHandler handler in fixtureB.onCollision.GetInvocationList() )
enabled = handler( fixtureB, fixtureA, this );
//BeginContact can also return false and disable the contact
if( contactManager.onBeginContact != null )
enabled = contactManager.onBeginContact( this );
}
// If the user disabled the contact (needed to exclude it in TOI solver) at any point by
// any of the callbacks, we need to mark it as not touching and call any separation
// callbacks for fixtures that didn't explicitly disable the collision.
if( !enabled )
isTouching = false;
}
}
else
{
if( touching == false )
{
// Report the separation to both participants:
if( fixtureA != null && fixtureA.onSeparation != null )
fixtureA.onSeparation( fixtureA, fixtureB );
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
if( fixtureB != null && fixtureB.onSeparation != null )
fixtureB.onSeparation( fixtureB, fixtureA );
if( contactManager.onEndContact != null )
contactManager.onEndContact( this );
}
}
if( sensor )
return;
if( contactManager.onPreSolve != null )
contactManager.onPreSolve( this, ref oldManifold );
}
/// <summary>
/// Evaluate this contact with your own manifold and transforms.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="transformA">The first transform.</param>
/// <param name="transformB">The second transform.</param>
void evaluate( ref Manifold manifold, ref Transform transformA, ref Transform transformB )
{
switch( _type )
{
case ContactType.Polygon:
Collision.Collision.collidePolygons( ref manifold, (PolygonShape)fixtureA.shape, ref transformA, (PolygonShape)fixtureB.shape, ref transformB );
break;
case ContactType.PolygonAndCircle:
Collision.Collision.collidePolygonAndCircle( ref manifold, (PolygonShape)fixtureA.shape, ref transformA, (CircleShape)fixtureB.shape, ref transformB );
break;
case ContactType.EdgeAndCircle:
Collision.Collision.collideEdgeAndCircle( ref manifold, (EdgeShape)fixtureA.shape, ref transformA, (CircleShape)fixtureB.shape, ref transformB );
break;
case ContactType.EdgeAndPolygon:
Collision.Collision.collideEdgeAndPolygon( ref manifold, (EdgeShape)fixtureA.shape, ref transformA, (PolygonShape)fixtureB.shape, ref transformB );
break;
case ContactType.ChainAndCircle:
var chain = (ChainShape)fixtureA.shape;
chain.getChildEdge( _edge, childIndexA );
Collision.Collision.collideEdgeAndCircle( ref manifold, _edge, ref transformA, (CircleShape)fixtureB.shape, ref transformB );
break;
case ContactType.ChainAndPolygon:
var loop2 = (ChainShape)fixtureA.shape;
loop2.getChildEdge( _edge, childIndexA );
Collision.Collision.collideEdgeAndPolygon( ref manifold, _edge, ref transformA, (PolygonShape)fixtureB.shape, ref transformB );
break;
case ContactType.Circle:
Collision.Collision.collideCircles( ref manifold, (CircleShape)fixtureA.shape, ref transformA, (CircleShape)fixtureB.shape, ref transformB );
break;
}
}
internal static Contact create( Fixture fixtureA, int indexA, Fixture fixtureB, int indexB )
{
var type1 = fixtureA.shape.shapeType;
var type2 = fixtureB.shape.shapeType;
Debug.Assert( ShapeType.Unknown < type1 && type1 < ShapeType.TypeCount );
Debug.Assert( ShapeType.Unknown < type2 && type2 < ShapeType.TypeCount );
Contact c;
var pool = fixtureA.body._world._contactPool;
if( pool.Count > 0 )
{
c = pool.Dequeue();
if( ( type1 >= type2 || ( type1 == ShapeType.Edge && type2 == ShapeType.Polygon ) ) && !( type2 == ShapeType.Edge && type1 == ShapeType.Polygon ) )
c.reset( fixtureA, indexA, fixtureB, indexB );
else
c.reset( fixtureB, indexB, fixtureA, indexA );
}
else
{
// Edge+Polygon is non-symetrical due to the way Erin handles collision type registration.
if( ( type1 >= type2 || ( type1 == ShapeType.Edge && type2 == ShapeType.Polygon ) ) && !( type2 == ShapeType.Edge && type1 == ShapeType.Polygon ) )
c = new Contact( fixtureA, indexA, fixtureB, indexB );
else
c = new Contact( fixtureB, indexB, fixtureA, indexA );
}
c._type = _contactRegisters[(int)type1, (int)type2];
return c;
}
internal void destroy()
{
#if USE_ACTIVE_CONTACT_SET
FixtureA.Body.World.ContactManager.RemoveActiveContact(this);
#endif
fixtureA.body._world._contactPool.Enqueue( this );
if( manifold.pointCount > 0 && fixtureA.isSensor == false && fixtureB.isSensor == false )
{
fixtureA.body.isAwake = true;
fixtureB.body.isAwake = true;
}
reset( null, 0, null, 0 );
}
#region Nested type: ContactType
public enum ContactType
{
NotSupported,
Polygon,
PolygonAndCircle,
Circle,
EdgeAndPolygon,
EdgeAndCircle,
ChainAndPolygon,
ChainAndCircle,
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using EmergeTk.Model;
using EmergeTk.Model.Security;
using System.Text;
using System.Collections;
using SimpleJson;
namespace EmergeTk.WebServices
{
public static class RecordSerializer
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(RecordSerializer));
public readonly static string[] IdFieldSet = new string[] { "id" };
public readonly static string[] WildcardFieldSet = new string[] { "*" };
private static Regex simpleJsonRegex = new Regex(@"[\w\*]+",RegexOptions.Compiled);
private static Dictionary<string,JsonArray> jsonParameters = new Dictionary<string, JsonArray>();
public static JsonArray GetWildcardFields(Type type)
{
JsonArray fields = new JsonArray ();
foreach( ColumnInfo ci in ColumnInfoManager.RequestColumns(type))
{
fields.Add( Util.PascalToCamel(ci.Name) );
}
return fields;
}
public static JsonArray SetupFields(string fields, Type rType)
{
//strip out spaces
if (fields == null) fields = "id";
fields = fields.Replace(" ", "");
JsonArray fieldArray;
if( fields.StartsWith("[") )
{
if( jsonParameters.ContainsKey(fields) )
fieldArray = jsonParameters[fields];
else
{
string simpleJsonString = fields;
if( !fields.Contains('"') )
simpleJsonString = simpleJsonRegex.Replace(fields,"\"$0\"");
//log.Debug(simpleJsonString);
fieldArray = JSON.Deserialize<JsonArray> (simpleJsonString);
jsonParameters[fields] = fieldArray;
}
}
else if( fields == "*" )
fieldArray = GetWildcardFields(rType);
else
{
fieldArray = new JsonArray ();
foreach (var item in fields.Split(','))
fieldArray.Add (item);
}
return fieldArray;
}
public static void Serialize(AbstractRecord record, string fields, IMessageWriter writer)
{
if( record != null )
Serialize(record,SetupFields(fields, record.GetType()), writer);
}
public static void Serialize(AbstractRecord record, string explicitName, string fields, IMessageWriter writer)
{
if( record != null )
Serialize(record, explicitName, SetupFields(fields, record.GetType()), writer);
}
public static void Serialize(AbstractRecord record, JsonArray fields, IMessageWriter writer)
{
Serialize(record, String.Empty, fields, writer);
}
public static void Serialize(AbstractRecord record, String explicitName, JsonArray fields, IMessageWriter writer )
{
if (record == null)
return;
Type rType = record.GetType();
IRestServiceManager serviceManager = WebServiceManager.Manager.GetRestServiceManager(rType);
if (WebServiceManager.DoAuth() && serviceManager == null)
return;
if( WebServiceManager.DoAuth() )
serviceManager.Authorize( RestOperation.Get, null, record );
// the original MessageNode based code sets the name of the object here. So, it seems counter-intuitive to me,
// but we're going to try to simulate the same thing with an
// OpenProperty()/OpenObject()/CloseObject()/CloseProperty() bracketing.
var restTypeDescription = WebServiceManager.Manager.GetRestTypeDescription(rType);
if (String.IsNullOrEmpty(explicitName))
writer.OpenProperty(restTypeDescription.ModelName);
else
writer.OpenProperty(explicitName);
writer.OpenObject();
writer.WriteProperty("id", record.Id);
if (record is IVersioned)
writer.WriteProperty ("version", record.Version);
if (record is IDerived || fields.Contains ("_type"))
{
writer.WriteProperty ("_type", restTypeDescription.ModelName);
}
if (fields.Count == 1 && fields[0] is string && (string)fields[0] == "*")
{
fields = SetupFields (fields[0] as string, rType);
}
foreach( object o in fields )
{
SerializeField (o, record, rType, serviceManager, writer);
}
writer.CloseObject();
writer.CloseProperty();
}
public static void Serialize(object source, String explicitName, string fields, IMessageWriter writer )
{
if (source == null)
return;
Type rType = source.GetType();
var f = SetupFields (fields, rType);
Serialize (source, explicitName, f, writer);
}
public static void Serialize(object source, String explicitName, JsonArray fields, IMessageWriter writer )
{
if (source == null)
return;
Type rType = source.GetType();
if (String.IsNullOrEmpty(explicitName))
writer.OpenProperty(rType.Name);
else
writer.OpenProperty(explicitName);
writer.OpenObject();
foreach( object o in fields )
{
SerializeField (o, source, rType, null, writer);
}
writer.CloseObject();
writer.CloseProperty();
}
public static void SerializeField (object o, object source, Type rType, IRestServiceManager serviceManager, IMessageWriter writer)
{
var sourceRecord = source as AbstractRecord;
if( o is JsonObject)
{
var values = o as JsonObject;
foreach( string key in values.Keys )
{
string Key = Util.CamelToPascal (key);
object val = null;
Type valueType = null;
if (sourceRecord != null)
{
var fieldInfo = sourceRecord.GetFieldInfoFromName (Key);
if (fieldInfo == null)
continue;
valueType = fieldInfo.Type;
val = sourceRecord[Util.CamelToPascal(key)];
}
else
{
var prop = rType.GetProperty (Key);
if (prop == null)
continue;
valueType = prop.PropertyType;
val = prop.GetValue (source, null);
}
if (valueType.IsSubclassOf (typeof(AbstractRecord)))
{
Serialize(val as AbstractRecord, key, values[key] as JsonArray, writer);
}
else if (valueType.GetInterface ("IRecordList") != null)
{
Serialize(val as IRecordList, key, values[key] as JsonArray, writer);
}
else if (valueType.GetInterface ("IEnumerable") != null &&
valueType.IsGenericType)
{
if (valueType.GetGenericArguments()[0].IsSubclassOf (typeof(AbstractRecord)))
Serialize (val as IEnumerable, valueType.GetGenericArguments()[0], key, values[key] as JsonArray, writer);
else
SerializeObjectList (val as IEnumerable, key, values[key] as JsonArray, valueType.GetGenericArguments()[0], writer);
}
else if (val == null)
{
writer.WriteProperty(key, (String)null);
}
else
Serialize (val, key, values[key] as JsonArray, writer);
}
return;
}
string f = (string)o;
string uField = Util.CamelToPascal(f);
string lField = Util.PascalToCamel(f);
if (source != null && sourceRecord == null)
{
var prop = rType.GetProperty (uField);
if (prop == null)
return;
object obj = prop.GetValue(source, null);
writer.OpenProperty (lField);
if (obj is AbstractRecord)
writer.WriteScalar ((obj as AbstractRecord).Id);
else
writer.WriteRaw (JSON.Serialize (obj));
writer.CloseProperty ();
return;
}
if (f == "*")
{
foreach (var field in GetWildcardFields (rType))
SerializeField (field, sourceRecord, rType, serviceManager, writer);
return;
}
if( serviceManager != null && WebServiceManager.DoAuth() && ! serviceManager.AuthorizeField(RestOperation.Get,sourceRecord,f) )
return;
if( lField.EndsWith("__count") )
{
string propName = uField.Substring(0,f.Length-"__count".Length);
List<int> ids = sourceRecord.LoadChildrenIds(sourceRecord.GetFieldInfoFromName(propName));
if (ids != null && ids.Count > 0)
writer.WriteProperty(lField, ids.Count);
else
writer.WriteProperty(lField, (sourceRecord[propName] as IRecordList).Count);
return;
}
ColumnInfo fi = sourceRecord.GetFieldInfoFromName(uField);
if( fi == null )
return;
if( fi.IsList )
{
List<int> ids = sourceRecord.LoadChildrenIds(fi);
if (ids != null && ids.Count > 0)
{
SerializeIntsList(ids, lField, null, null, fi.ListRecordType, writer);
}
else
{
object recordList = sourceRecord[uField];
if (recordList == null)
{
writer.OpenProperty(lField);
writer.WriteScalar((string) null);
writer.CloseProperty();
return;
}
Serialize((recordList as IRecordList).GetEnumerable(), lField, (JsonArray)null, fi.ListRecordType, writer);
}
}
else if (fi.IsRecord)
{
// we're just trying to get the ID. If we *can* get this field
// without having to load from another table, then do so.
// Add IsPropertyLoaded to AbstractRecord. If it's not loaded, execute this code.
if (!sourceRecord.PropertyLoaded(uField) && sourceRecord.OriginalValues != null && sourceRecord.OriginalValues.ContainsKey(uField) && sourceRecord.OriginalValues[uField] != null )
{
StreamLineWriteProperty(fi.Type, writer, sourceRecord.OriginalValues, lField, uField);
}
else
{
// OK, so we have to do an AbstractRecord.Load()
object rec = sourceRecord[uField];
writer.OpenProperty(lField);
if (rec != null)
writer.WriteScalar(((AbstractRecord)rec).Id);
else
writer.WriteScalar(null);
writer.CloseProperty();
}
}
else if (fi.DataType == DataType.Json)
{
object obj = sourceRecord[uField];
writer.OpenProperty (lField);
writer.WriteRaw (JSON.Serialize (obj));
writer.CloseProperty ();
}
else
{
StreamLineWriteProperty(fi.Type, writer, sourceRecord, lField, uField);
}
}
public static void StreamLineWriteProperty(Type t, IMessageWriter writer, AbstractRecord record, String lField, String uField)
{
if (t == typeof(int))
{
writer.WriteProperty(lField, (int)record[uField]);
}
else if (t == typeof(String))
{
writer.WriteProperty(lField, (String)record[uField]);
}
else
{
writer.OpenProperty(lField);
if (t == typeof(bool))
writer.WriteScalar((bool)record[uField]);
else if (t == typeof(double))
writer.WriteScalar((double)record[uField]);
else if (t == typeof(float))
writer.WriteScalar((float)record[uField]);
else if (t == typeof(decimal))
writer.WriteScalar((decimal)record[uField]);
else if (t == typeof(DateTime))
writer.WriteScalar((DateTime)record[uField]);
else
writer.WriteScalar(record[uField]);
writer.CloseProperty();
}
}
public static void StreamLineWriteProperty(Type t, IMessageWriter writer, Dictionary<String, object> originalValues, String lField, String uField)
{
if (t == typeof(int))
{
writer.WriteProperty(lField, (int)originalValues[uField]);
}
else if (t == typeof(String))
{
writer.WriteProperty(lField, (String)originalValues[uField]);
}
else
{
writer.OpenProperty(lField);
writer.WriteScalar(originalValues[uField]);
writer.CloseProperty();
}
}
public static void Serialize (IRecordList list,string fields, IMessageWriter writer)
{
if( list != null )
Serialize<AbstractRecord>(list.GetEnumerable(),SetupFields(fields,list.RecordType),list.RecordType, writer);
}
public static void Serialize(IRecordList list, String listName, string fields, IMessageWriter writer)
{
if (list != null)
Serialize<AbstractRecord>(list.GetEnumerable(), listName, SetupFields(fields, list.RecordType), list.RecordType, writer);
}
public static void Serialize(IRecordList list, String listName, JsonArray fields, IMessageWriter writer)
{
if (list != null)
Serialize(list.GetEnumerable(), listName, fields, list.RecordType, writer);
}
public static void Serialize (IRecordList list, JsonArray fields, IMessageWriter writer)
{
if( list != null )
Serialize<AbstractRecord>(list.GetEnumerable(),fields,list.RecordType, writer);
}
public static void Serialize<T> (IEnumerable<T> items, string fields, Type recordType, IMessageWriter writer) where T : AbstractRecord
{
Serialize<T>(items, SetupFields(fields,recordType),recordType, writer );
}
public static void Serialize<T> (IEnumerable<T> items, string fields, IMessageWriter writer) where T : AbstractRecord
{
Serialize<T>(items, SetupFields(fields,typeof(T)), typeof(T), writer );
}
public static void Serialize<T>(IEnumerable<T> items, string listName, string fields, Type recordType, IMessageWriter writer) where T : AbstractRecord
{
Serialize<T>(items, listName, SetupFields(fields, recordType), recordType, writer);
}
public static void
Serialize<T>(
IEnumerable<T> items,
String listName,
JsonArray fields,
Type recordType,
IMessageWriter writer) where T : AbstractRecord
{
RestTypeDescription att = WebServiceManager.Manager.GetRestTypeDescription(recordType);
if (att.RestType == null || items == null)
{
log.Warn("No attribute for type " + recordType);
return;
}
if (String.IsNullOrEmpty(listName))
writer.OpenProperty(att.ModelPluralName);
else
writer.OpenProperty(listName);
writer.OpenList(att.ModelName);
if (fields == null)
{
foreach (AbstractRecord r in items)
{
writer.WriteScalar(r.Id);
}
}
else
{
foreach (AbstractRecord r in items)
{
if (r != null)
{
//log.Debug("Serializing " + r);
Serialize(r, fields, writer);
}
}
}
writer.CloseList();
writer.CloseProperty();
}
public static void
SerializeObjectList (
IEnumerable items,
String listName,
string fields,
Type type,
IMessageWriter writer)
{
JsonArray fieldArray = SetupFields (fields, type);
SerializeObjectList (items, listName, fieldArray, type, writer);
}
public static void
SerializeObjectList(
IEnumerable items,
String listName,
JsonArray fields,
Type type,
IMessageWriter writer)
{
listName = listName ?? type.Name + "s";
writer.OpenProperty(listName);
writer.OpenList(listName);
if (fields == null)
{
foreach (object o in items)
{
writer.WriteScalar (o);
}
}
else
{
foreach (object o in items)
{
if (o != null)
{
//log.Debug("Serializing " + r);
Serialize(o, listName, fields, writer);
}
}
}
writer.CloseList();
writer.CloseProperty();
}
public static void Serialize<T> (IEnumerable<T> items, JsonArray fields, Type recordType, IMessageWriter writer) where T : AbstractRecord
{
Serialize<T>(items, String.Empty, fields, recordType, writer);
}
public static void SerializeT<T> (IEnumerable<T> items, string listName, JsonArray fields, Type recordType, IMessageWriter writer) where T : AbstractRecord
{
Serialize<T>(items, listName, fields, recordType, writer);
}
public static void Serialize (IEnumerable items, Type recordType, string listName, JsonArray fields, IMessageWriter writer)
{
if (items == null)
{
writer.OpenProperty (listName);
writer.WriteScalar (null);
writer.CloseProperty ();
}
TypeLoader.InvokeGenericMethod (typeof(RecordSerializer), "SerializeT", new Type[] {recordType}, null, new object[] {
items, listName, fields, recordType, writer});
}
public static void SerializeIntsList (IEnumerable<int> items, string name, string fields, string sortBy, Type recordType, IMessageWriter writer)
{
TypeLoader.InvokeGenericMethod(typeof(RecordSerializer),"SerializeIntsListT",new Type[]{recordType},null,new object[]{items,name,fields,sortBy,recordType, writer});
}
public static Dictionary<int, String> fieldHashes = new Dictionary<int, String>();
public static IRecordList<T> FastLoadScalarList<T>(IEnumerable<int> items, String sortBy, String fields) where T : AbstractRecord, new()
{
int hashFields = fields.GetHashCode();
String sqlSelCols = null;
if (!fieldHashes.ContainsKey(hashFields))
{
// if the fields are scalar, sqlSelCols will come out non-null
// if one of the fields are non-scalar, sqlSelCols will be null,
// and we store it either way.
AllFieldsAreScalar<T>(fields, out sqlSelCols);
lock (fieldHashes)
{
// store it, null or non-null.
fieldHashes[hashFields] = sqlSelCols;
}
}
else
{
// we've seen this hash before, return out the
// selection column string (or NULL).
sqlSelCols = fieldHashes[hashFields];
}
if (sqlSelCols == null)
return null;
return DataProvider.DefaultProvider.Load<T>(
String.Format("ROWID IN ({0})", Util.JoinToString<int>(items, ",")),
sortBy,
sqlSelCols);
}
public static void
SerializeIntsListT<T> (
IEnumerable<int> items,
string name,
string fields,
string sortBy,
Type recordType,
IMessageWriter writer) where T : AbstractRecord, new()
{
RestTypeDescription att = WebServiceManager.Manager.GetRestTypeDescription(recordType);
if (att.RestType == null)
{
log.WarnFormat("Could not find RestServiceAttribute for type {0}", recordType);
return;
}
if( fields == null )
{
writer.OpenProperty(name ?? att.ModelPluralName);
writer.OpenList(att.ModelName);
foreach(int id in items )
{
writer.WriteScalar(id);
}
writer.CloseList();
writer.CloseProperty();
}
else
{
IRecordList<T> records = FastLoadScalarList<T>(items, sortBy, fields);
if (records == null)
{
records = new RecordList<T>();
foreach (int id in items)
{
AbstractRecord r = AbstractRecord.Load<T>(id);
if (r == null)
continue;
records.Add(r);
}
if (!String.IsNullOrEmpty(sortBy))
{
SortDirection sortDir = SortDirection.Ascending;
String[] tokens = sortBy.Split(' ');
if (tokens.Length > 1)
{
if (tokens[1] == "desc")
sortDir = SortDirection.Descending;
}
string uField = Util.CamelToPascal(tokens[0]);
records.Sort(new SortInfo(uField, sortDir));
}
}
Serialize(records, name, fields, recordType, writer);
}
}
private static bool AllFieldsAreScalar<T>(String fields, out String fieldString) where T : AbstractRecord, new()
{
ColumnInfo[] cols = ColumnInfoManager.RequestColumns<T>();
StringBuilder sb = new StringBuilder();
fieldString = null;
foreach (String field in fields.Split(','))
{
try
{
if (field == "id")
continue;
ColumnInfo col = cols.FirstOrDefault(ci => ci.Name == Util.CamelToPascal(field));
if (col == null || col.IsList)
return false; // incorrect field name or there's a list.
sb.AppendFormat("{0},", field);
}
catch (Exception ex)
{
throw new Exception(String.Format("Error getting columnInfo for field name = {0}, type = {1}", field, typeof (T).Name), ex);
}
}
if (sb.Length > 0)
{
fieldString = sb.ToString().Trim(',');
return true;
}
return false;
}
public static AbstractRecord DeserializeRecordType (Type t, JsonObject node, DeserializationContext context)
{
return (AbstractRecord) TypeLoader.InvokeGenericMethod (typeof(RecordSerializer), "DeserializeRecord", new Type[] {t},
null, new object[] {node, context});
}
public static T DeserializeRecord<T>(JsonObject node, DeserializationContext context) where T : AbstractRecord, new()
{
IRestServiceManager serviceManager = WebServiceManager.Manager.GetRestServiceManager(typeof(T));
if( serviceManager == null )
throw new Exception("No IRestServiceManager defined. Cannot deserialize objects of type " + typeof(T) );
//TODO: we need to provide feedback on errors. i.e. "expecting integer for child id, but found 'name' instead."
T record = null;
RestOperation op = RestOperation.Post;
if( node.ContainsKey( "id" ) )
{
//log.Debug("loading with id", node["id"]);
record = AbstractRecord.Load<T>(node["id"]);
if( WebServiceManager.DoAuth() )
serviceManager.Authorize(RestOperation.Put,node,record);
op = RestOperation.Put;
if (record is IVersioned)
{
if (!node.ContainsKey ("version"))
throw new ArgumentNullException ("version");
if (record.Version != Convert.ToInt32 (node["version"]))
{
throw new VersionOutOfDateException (string.Format ("Version mismatch - actual: {0}. supplied: {1}", record.Version,
node["version"]));
}
}
if( record == null )
{
throw new RecordNotFoundException(string.Format("Record: {0}, {1} does not exist.", typeof(T), node["id"] ) );
}
//now create a writable copy to avoid modification collisions / corrupting good data with a bad operation.
record = AbstractRecord.CreateFromRecord<T>(record);
}
else
{
if( WebServiceManager.DoAuth() )
serviceManager.Authorize(RestOperation.Post,node,null);
record = new T();
}
foreach( string k in node.Keys )
{
if( k == "id" || k == "version")
{
continue;
}
if( (WebServiceManager.DoAuth() && ! serviceManager.AuthorizeField(op,record,k) ) )
{
log.WarnFormat("Column {0} failed authorization.", k);
continue;
}
object val = node[k];
//log.DebugFormat("deserializing key: {0} value: {1} ", k, val );
string recordFieldName = Util.CamelToPascal(k);
ColumnInfo field = ColumnInfoManager.RequestColumn<T>(recordFieldName);
if( field == null )
throw new InvalidOperationException("Invalid field specified: " + recordFieldName);
if( field.IsList )
{
if (val != null)
{
//need to deserialize a list.
//TODO: we may be able to avoid generic methods here, if we just use Activator.CreateInstance
JsonArray list = (JsonArray)val;
IRecordList newList = (IRecordList)TypeLoader.InvokeGenericMethod
(typeof(RecordSerializer), "DeserializeList", new Type[] { field.Type.GetGenericArguments()[0] }, null, new object[] { list, context });
IRecordList oldList = (IRecordList)record[recordFieldName];
if (oldList != null)
newList.RecordSnapshot = oldList.RecordSnapshot;
record[recordFieldName] = newList;
if (context.Lists == null)
context.Lists = new List<RecordPropertyList>();
context.Lists.Add(new RecordPropertyList(record, recordFieldName));
}
else
{
record[recordFieldName] = null;
}
}
else if( field.IsRecord )
{
if (val == null)
{
record[recordFieldName] = null;
}
else if( val is string )
{
Type loadType = field.Type;
int id = int.Parse ((string)val);
if (AbstractRecord.IsDerived (field.Type))
{
loadType = DataProvider.DefaultProvider.GetTypeForId (id);
}
record[recordFieldName] = AbstractRecord.Load(loadType, id);
}
else if (val is long)
{
Type loadType = field.Type;
int id = Convert.ToInt32(val);
if (AbstractRecord.IsDerived (field.Type))
{
loadType = DataProvider.DefaultProvider.GetTypeForId (id);
}
record[recordFieldName] = AbstractRecord.Load(loadType, id);
}
else if( val is JsonObject )
{
JsonObject propNode = (JsonObject)val;
Type loadType = field.Type;
if (AbstractRecord.IsDerived (field.Type))
{
loadType = TypeLoader.GetType (propNode["type"].ToString ());
}
record[recordFieldName] = TypeLoader.InvokeGenericMethod(typeof(RecordSerializer),"DeserializeRecord", new Type[] { loadType }, null, new object[]{propNode,context});
}
}
else if( field.Type == typeof( Dictionary<string,string> ) )
{
if (val != null)
{
JsonObject inNode = (JsonObject)node[k];
Dictionary<string, string> stringDict = new Dictionary<string, string>();
foreach (string key in inNode.Keys)
stringDict.Add(key, Convert.ToString(inNode[key]));
record[recordFieldName] = stringDict;
}
else
{
record[recordFieldName] = null;
}
}
else if (field.DataType == DataType.Json)
{
//log.Debug ("JSON serialize", val.GetType (), val);
if (val is string)
{
var deser = JSON.DeserializeObject(field.Type, (string)val);
record[recordFieldName] = deser;
}
else if (val is JsonObject)
{
JsonObject obj = val as JsonObject;
IDictionary dict = Activator.CreateInstance(field.Type) as IDictionary;
Type valueType = null;
if (field.Type.IsGenericType)
valueType = field.Type.GetGenericArguments()[1];
foreach (var kvp in obj)
{
if (valueType != null)
{
dict[kvp.Key] = PropertyConverter.Convert (kvp.Value, valueType);
}
else
{
dict[kvp.Key] = kvp.Value;
}
}
record[recordFieldName] = dict;
}
else if (val is JsonArray)
{
var listType = field.Type;
var itemType = listType.IsGenericType ? listType.GetGenericArguments () [0] : typeof(object);
record[recordFieldName] = JSON.DeserializeArray (field.Type, itemType, val as JsonArray);
}
else
{
record[recordFieldName] = null;
}
}
else //scalar.
{
if (val == null && field.Type.IsValueType)
continue;
record[recordFieldName] = val;
}
// check for field authorization (after value copied into record)
if (WebServiceManager.DoAuth())
serviceManager.AuthorizeField(op, record, k);
}
if( context.Records == null )
context.Records = new List<AbstractRecord>();
context.Records.Add(record);
return record;
}
private static bool DoAuth()
{
return System.Web.HttpContext.Current != null && ! User.IsRoot;
}
public static IRecordList DeserializeNonGenericList(Type recordType, JsonArray list, DeserializationContext context)
{
return (IRecordList)TypeLoader.InvokeGenericMethod(typeof(RecordSerializer),"DeserializeList",new Type[]{recordType},null,new object[]{list,context});
}
public static IRecordList<T> DeserializeList<T>(JsonArray list, DeserializationContext context) where T : AbstractRecord, new()
{
//TODO: we need to provide feedback on errors. i.e. "expecting integer for child id, but found 'name' instead."
//log.Debug("calling deserialize list", list );
RecordList<T> records = new RecordList<T>();
foreach( object item in list )
{
int id = 0;
if( item is long ) //scalars must be ints.
{
id = Convert.ToInt32 (item);
T c = AbstractRecord.Load<T>(id);
if( c != null )
records.Add(c);
}
else if( item is string ) //scalars must be ints.
{
id = int.Parse((string)item);
T c = AbstractRecord.Load<T>(id);
if( c != null )
records.Add(c);
}
else if( item is JsonObject )
{
records.Add( DeserializeRecord<T>(item as JsonObject, context) );
}
}
return records;
}
}
public struct RecordPropertyList
{
public AbstractRecord Record;
public string Property;
public RecordPropertyList(AbstractRecord record, string property)
{
this.Record = record;
this.Property = property;
}
}
public class DeserializationContext
{
public List<AbstractRecord> Records;
public List<RecordPropertyList> Lists;
public void SaveChanges()
{
if (Records != null)
{
foreach( AbstractRecord r in Records )
{
r.Save();
}
}
if (Lists != null)
{
foreach( RecordPropertyList rpl in Lists )
{
rpl.Record.SaveRelations(rpl.Property);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition
{
using System.Collections.Generic;
using Microsoft.Azure.Management.AppService.Fluent.Models;
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
/// <summary>
/// A web app definition stage allowing setting if SCM site is also stopped when the web app is stopped.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithScmSiteAlsoStopped<FluentT>
{
/// <summary>
/// Specifies if SCM site is also stopped when the web app is stopped.
/// </summary>
/// <param name="scmSiteAlsoStopped">True if SCM site is also stopped.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithScmSiteAlsoStopped(bool scmSiteAlsoStopped);
}
/// <summary>
/// A web app definition stage allowing diagnostic logging to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithDiagnosticLogging<FluentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Gets Specifies the definition of a new diagnostic logs configuration.
/// </summary>
/// <summary>
/// Gets the first stage of an diagnostic logs definition.
/// </summary>
Microsoft.Azure.Management.AppService.Fluent.WebAppDiagnosticLogs.Definition.IBlank<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>> DefineDiagnosticLogsConfiguration();
/// <summary>
/// Disable the container logging for Linux web apps.
/// </summary>
/// <return>The next stage of the web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithContainerLoggingDisabled();
/// <summary>
/// Specifies the configuration for container logging for Linux web apps.
/// </summary>
/// <param name="quotaInMB">The limit that restricts file system usage by app diagnostics logs. Value can range from 25 MB and 100 MB.</param>
/// <param name="retentionDays">Maximum days of logs that will be available.</param>
/// <return>The next stage of the web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithContainerLoggingEnabled(int quotaInMB, int retentionDays);
/// <summary>
/// Specifies the configuration for container logging for Linux web apps.
/// Logs will be stored on the file system for up to 35 MB.
/// </summary>
/// <return>The next stage of the web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithContainerLoggingEnabled();
}
/// <summary>
/// The stage of the System Assigned (Local) Managed Service Identity enabled web app allowing to
/// set access role for the identity.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>
{
/// <summary>
/// Specifies that web app's system assigned (local) identity should have the given access
/// (described by the role) on an ARM resource identified by the resource ID. Applications running
/// on the web app will have the same permission (role) on the ARM resource.
/// </summary>
/// <param name="resourceId">The ARM identifier of the resource.</param>
/// <param name="role">Access role to assigned to the web app's local identity.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> WithSystemAssignedIdentityBasedAccessTo(string resourceId, BuiltInRole role);
/// <summary>
/// Specifies that web app's system assigned (local) identity should have the access
/// (described by the role definition) on an ARM resource identified by the resource ID.
/// Applications running on the web app will have the same permission (role) on the ARM resource.
/// </summary>
/// <param name="resourceId">Scope of the access represented in ARM resource ID format.</param>
/// <param name="roleDefinitionId">Access role definition to assigned to the web app's local identity.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> WithSystemAssignedIdentityBasedAccessTo(string resourceId, string roleDefinitionId);
/// <summary>
/// Specifies that web app's system assigned (local) identity should have the given access
/// (described by the role) on the resource group that web app resides. Applications running
/// on the web app will have the same permission (role) on the resource group.
/// </summary>
/// <param name="role">Access role to assigned to the web app's local identity.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role);
/// <summary>
/// Specifies that web app's system assigned (local) identity should have the access
/// (described by the role definition) on the resource group that web app resides.
/// Applications running on the web app will have the same permission (role) on the
/// resource group.
/// </summary>
/// <param name="roleDefinitionId">Access role definition to assigned to the web app's local identity.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(string roleDefinitionId);
}
/// <summary>
/// A web app definition stage allowing SSL binding to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithHostNameSslBinding<FluentT>
{
/// <summary>
/// Starts a definition of an SSL binding.
/// </summary>
/// <return>The first stage of an SSL binding definition.</return>
Microsoft.Azure.Management.AppService.Fluent.HostNameSslBinding.Definition.IBlank<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>> DefineSslBinding();
}
/// <summary>
/// A web app definition stage allowing app settings to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithAppSettings<FluentT>
{
/// <summary>
/// Adds an app setting to the web app.
/// </summary>
/// <param name="key">The key for the app setting.</param>
/// <param name="value">The value for the app setting.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithAppSetting(string key, string value);
/// <summary>
/// Specifies the app settings for the web app as a Map.
/// </summary>
/// <param name="settings">A Map of app settings.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithAppSettings(IDictionary<string,string> settings);
/// <summary>
/// Adds an app setting to the web app. This app setting will be swapped
/// as well after a deployment slot swap.
/// </summary>
/// <param name="key">The key for the app setting.</param>
/// <param name="value">The value for the app setting.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithStickyAppSetting(string key, string value);
/// <summary>
/// Specifies the app settings for the web app as a Map. These app settings will be swapped
/// as well after a deployment slot swap.
/// </summary>
/// <param name="settings">A Map of app settings.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithStickyAppSettings(IDictionary<string,string> settings);
}
/// <summary>
/// A web app definition stage allowing disabling the web app upon creation.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithSiteEnabled<FluentT>
{
/// <summary>
/// Disables the web app upon creation.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithAppDisabledOnCreation();
}
/// <summary>
/// A web app definition stage allowing setting if client cert is enabled.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithClientCertEnabled<FluentT>
{
/// <summary>
/// Specifies if client cert is enabled.
/// </summary>
/// <param name="enabled">True if client cert is enabled.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithClientCertEnabled(bool enabled);
}
/// <summary>
/// The entirety of the web app base definition.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IDefinition<FluentT> :
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithWebContainer<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT>
{
}
/// <summary>
/// A web app definition stage allowing connection strings to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithConnectionString<FluentT>
{
/// <summary>
/// Adds a connection string to the web app.
/// </summary>
/// <param name="name">The name of the connection string.</param>
/// <param name="value">The connection string value.</param>
/// <param name="type">The connection string type.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithConnectionString(string name, string value, ConnectionStringType type);
/// <summary>
/// Adds a connection string to the web app. This connection string will be swapped
/// as well after a deployment slot swap.
/// </summary>
/// <param name="name">The name of the connection string.</param>
/// <param name="value">The connection string value.</param>
/// <param name="type">The connection string type.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithStickyConnectionString(string name, string value, ConnectionStringType type);
}
/// <summary>
/// A web app definition stage allowing setting if client affinity is enabled.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithClientAffinityEnabled<FluentT>
{
/// <summary>
/// Specifies if client affinity is enabled.
/// </summary>
/// <param name="enabled">True if client affinity is enabled.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithClientAffinityEnabled(bool enabled);
}
/// <summary>
/// A web app definition stage allowing host name binding to be specified.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithHostNameBinding<FluentT>
{
/// <summary>
/// Starts the definition of a new host name binding.
/// </summary>
/// <return>The first stage of a hostname binding definition.</return>
Microsoft.Azure.Management.AppService.Fluent.HostNameBinding.Definition.IBlank<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>> DefineHostnameBinding();
/// <summary>
/// Defines a list of host names of an Azure managed domain. The DNS record type is
/// defaulted to be CNAME except for the root level domain (".
/// </summary>
/// <param name="domain">The Azure managed domain.</param>
/// <param name="hostnames">The list of sub-domains.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithManagedHostnameBindings(IAppServiceDomain domain, params string[] hostnames);
/// <summary>
/// Defines a list of host names of an externally purchased domain. The hostnames
/// must be configured before hand to point to the web app.
/// </summary>
/// <param name="domain">The external domain name.</param>
/// <param name="hostnames">The list of sub-domains.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithThirdPartyHostnameBinding(string domain, params string[] hostnames);
}
/// <summary>
/// A web app definition stage allowing authentication to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithAuthentication<FluentT>
{
/// <summary>
/// Specifies the definition of a new authentication configuration.
/// </summary>
/// <return>The first stage of an authentication definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppAuthentication.Definition.IBlank<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>> DefineAuthentication();
}
/// <summary>
/// A site definition with sufficient inputs to create a new web app /
/// deployments slot in the cloud, but exposing additional optional
/// inputs to specify.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithCreate<FluentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<FluentT>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithClientAffinityEnabled<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithClientCertEnabled<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithScmSiteAlsoStopped<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSiteConfigs<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithAppSettings<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithConnectionString<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSourceControl<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithHostNameBinding<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithHostNameSslBinding<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithAuthentication<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithDiagnosticLogging<FluentT>,
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithManagedServiceIdentity<FluentT>
{
}
/// <summary>
/// A web app definition stage allowing Java web container to be set. This is required
/// after specifying Java version.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithWebContainer<FluentT>
{
/// <summary>
/// Specifies the Java web container.
/// </summary>
/// <param name="webContainer">The Java web container.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithWebContainer(WebContainer webContainer);
}
/// <summary>
/// A web app definition stage allowing other configurations to be set. These configurations
/// can be cloned when creating or swapping with a deployment slot.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithSiteConfigs<FluentT>
{
/// <summary>
/// Specifies the slot name to auto-swap when a deployment is completed in this web app / deployment slot.
/// </summary>
/// <param name="slotName">The name of the slot, or 'production', to auto-swap.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithAutoSwapSlotName(string slotName);
/// <summary>
/// Adds a default document.
/// </summary>
/// <param name="document">Default document.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithDefaultDocument(string document);
/// <summary>
/// Adds a list of default documents.
/// </summary>
/// <param name="documents">List of default documents.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithDefaultDocuments(IList<string> documents);
/// <summary>
/// Sets whether the web app supports certain type of FTP(S).
/// </summary>
/// <param name="ftpsState">The FTP(S) configuration.</param>
/// <return>The next stage of web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithFtpsState(FtpsState ftpsState);
/// <summary>
/// Sets whether the web app accepts HTTP 2.0 traffic.
/// </summary>
/// <param name="http20Enabled">True if the web app accepts HTTP 2.0 traffic.</param>
/// <return>The next stage of web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithHttp20Enabled(bool http20Enabled);
/// <summary>
/// Sets whether the web app only accepts HTTPS traffic.
/// </summary>
/// <param name="httpsOnly">True if the web app only accepts HTTPS traffic.</param>
/// <return>The next stage of web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithHttpsOnly(bool httpsOnly);
/// <summary>
/// Specifies the Java version.
/// </summary>
/// <param name="version">The Java version.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithWebContainer<FluentT> WithJavaVersion(JavaVersion version);
/// <summary>
/// Specifies the managed pipeline mode.
/// </summary>
/// <param name="managedPipelineMode">Managed pipeline mode.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithManagedPipelineMode(ManagedPipelineMode managedPipelineMode);
/// <summary>
/// Specifies the .NET Framework version.
/// </summary>
/// <param name="version">The .NET Framework version.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithNetFrameworkVersion(NetFrameworkVersion version);
/// <summary>
/// Removes a default document.
/// </summary>
/// <param name="document">Default document to remove.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithoutDefaultDocument(string document);
/// <summary>
/// Turn off PHP support.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithoutPhp();
/// <summary>
/// Specifies the PHP version.
/// </summary>
/// <param name="version">The PHP version.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithPhpVersion(PhpVersion version);
/// <summary>
/// Specifies the platform architecture to use.
/// </summary>
/// <param name="platform">The platform architecture.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithPlatformArchitecture(PlatformArchitecture platform);
/// <summary>
/// Specifies the Python version.
/// </summary>
/// <param name="version">The Python version.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithPythonVersion(PythonVersion version);
/// <summary>
/// Disables remote debugging.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithRemoteDebuggingDisabled();
/// <summary>
/// Specifies the Visual Studio version for remote debugging.
/// </summary>
/// <param name="remoteVisualStudioVersion">The Visual Studio version for remote debugging.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion);
/// <summary>
/// Sets the virtual applications in the web app.
/// </summary>
/// <param name="virtualApplications">The list of virtual applications in the web app.</param>
/// <return>The next stage of web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithVirtualApplications(IList<Microsoft.Azure.Management.AppService.Fluent.Models.VirtualApplication> virtualApplications);
/// <summary>
/// Specifies if the VM powering the web app is always powered on.
/// </summary>
/// <param name="alwaysOn">True if the web app is always powered on.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithWebAppAlwaysOn(bool alwaysOn);
/// <summary>
/// Specifies if web sockets are enabled.
/// </summary>
/// <param name="enabled">True if web sockets are enabled.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithWebSocketsEnabled(bool enabled);
}
/// <summary>
/// A web app definition stage allowing System Assigned Managed Service Identity to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithManagedServiceIdentity<FluentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies that System Assigned Managed Service Identity needs to be enabled in the web app.
/// </summary>
/// <return>The next stage of the web app definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate<FluentT> WithSystemAssignedManagedServiceIdentity();
}
/// <summary>
/// A web app definition stage allowing source control to be set.
/// </summary>
/// <typeparam name="FluentT">The type of the resource.</typeparam>
public interface IWithSourceControl<FluentT>
{
/// <summary>
/// Starts the definition of a new source control.
/// </summary>
/// <return>The first stage of a source control definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppSourceControl.Definition.IBlank<Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT>> DefineSourceControl();
/// <summary>
/// Specifies the source control to be a local Git repository on the web app.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition.IWithCreate<FluentT> WithLocalGitSourceControl();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerTypeProxy(typeof(SpanDebugView<>))]
[DebuggerDisplay("Length = {Length}")]
public struct Span<T>
{
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
int arrayLength = array.Length;
if ((uint)start > (uint)arrayLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = arrayLength - start;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new Span<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return ref Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return ref Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
public unsafe void Clear()
{
int length = _length;
if (length == 0)
return;
var byteLength = (UIntPtr)((uint)length * Unsafe.SizeOf<T>());
if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
{
if (_pinnable == null)
{
var ptr = (byte*)_byteOffset.ToPointer();
SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
SpanHelpers.ClearLessThanPointerSized(ref b, byteLength);
}
}
else
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
{
UIntPtr pointerSizedLength = (UIntPtr)((length * Unsafe.SizeOf<T>()) / sizeof(IntPtr));
ref IntPtr ip = ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithReferences(ref ip, pointerSizedLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithoutReferences(ref b, byteLength);
}
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public unsafe void Fill(T value)
{
int length = _length;
if (length == 0)
return;
if (Unsafe.SizeOf<T>() == 1)
{
byte fill = Unsafe.As<T, byte>(ref value);
if (_pinnable == null)
{
Unsafe.InitBlockUnaligned(_byteOffset.ToPointer(), fill, (uint)length);
}
else
{
ref byte r = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
}
}
else
{
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
// Simple loop unrolling
int i = 0;
for (; i < (length & ~7); i += 8)
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
Unsafe.Add<T>(ref r, i + 4) = value;
Unsafe.Add<T>(ref r, i + 5) = value;
Unsafe.Add<T>(ref r, i + 6) = value;
Unsafe.Add<T>(ref r, i + 7) = value;
}
if (i < (length & ~3))
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.Add<T>(ref r, i) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
int length = _length;
int destLength = destination._length;
if ((uint)length == 0)
return true;
if ((uint)length > (uint)destLength)
return false;
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
SpanHelpers.CopyTo<T>(ref dst, destLength, ref src, length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => new Span<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length span whose base is the null pointer.
/// </summary>
public static Span<T> Empty => default(Span<T>);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
}
| |
// 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.DirectoryServices.DirectoryEntry.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.DirectoryServices
{
public partial class DirectoryEntry : System.ComponentModel.Component
{
#region Methods and constructors
public void Close()
{
}
public void CommitChanges()
{
}
public System.DirectoryServices.DirectoryEntry CopyTo(System.DirectoryServices.DirectoryEntry newParent)
{
Contract.Requires(newParent != null);
Contract.Ensures(Contract.Result<DirectoryEntry>() != null);
return default(System.DirectoryServices.DirectoryEntry);
}
// newname can be null
public System.DirectoryServices.DirectoryEntry CopyTo(System.DirectoryServices.DirectoryEntry newParent, string newName)
{
Contract.Requires(newParent != null);
Contract.Ensures(Contract.Result<DirectoryEntry>() != null);
return default(System.DirectoryServices.DirectoryEntry);
}
public void DeleteTree()
{
}
public DirectoryEntry(string path)
{
}
public DirectoryEntry()
{
}
public DirectoryEntry(string path, string username, string password)
{
}
public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType)
{
}
public DirectoryEntry(Object adsObject)
{
}
protected override void Dispose(bool disposing)
{
}
public static bool Exists(string path)
{
return default(bool);
}
public Object Invoke(string methodName, Object[] args)
{
Contract.Ensures(Contract.Result<object>() != null);
return default(Object);
}
public Object InvokeGet(string propertyName)
{
return default(Object);
}
public void InvokeSet(string propertyName, Object[] args)
{
}
public void MoveTo(System.DirectoryServices.DirectoryEntry newParent, string newName)
{
}
public void MoveTo(System.DirectoryServices.DirectoryEntry newParent)
{
}
public void RefreshCache()
{
}
public void RefreshCache(string[] propertyNames)
{
}
public void Rename(string newName)
{
}
#endregion
#region Properties and indexers
public AuthenticationTypes AuthenticationType
{
get
{
return default(AuthenticationTypes);
}
set
{
}
}
public DirectoryEntries Children
{
get
{
Contract.Ensures(Contract.Result<DirectoryEntries>() != null);
return default(DirectoryEntries);
}
}
public Guid Guid
{
get
{
return default(Guid);
}
}
public string Name
{
get
{
return default(string);
}
}
public string NativeGuid
{
get
{
return default(string);
}
}
public Object NativeObject
{
get
{
return default(Object);
}
}
public ActiveDirectorySecurity ObjectSecurity
{
get
{
return default(ActiveDirectorySecurity);
}
set
{
}
}
public DirectoryEntryConfiguration Options
{
get
{
return default(DirectoryEntryConfiguration);
}
}
public System.DirectoryServices.DirectoryEntry Parent
{
get
{
Contract.Ensures(Contract.Result<DirectoryEntry>() != null);
return default(System.DirectoryServices.DirectoryEntry);
}
}
public string Password
{
set
{
}
}
public string Path
{
get
{
return default(string);
}
set
{
}
}
public PropertyCollection Properties
{
get
{
return default(PropertyCollection);
}
}
public string SchemaClassName
{
get
{
return default(string);
}
}
public System.DirectoryServices.DirectoryEntry SchemaEntry
{
get
{
return default(System.DirectoryServices.DirectoryEntry);
}
}
public bool UsePropertyCache
{
get
{
return default(bool);
}
set
{
}
}
// may return nul
public string Username
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
/*
* CP1145.cs - IBM EBCDIC (Latin America/Spain with Euro) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-1145.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP1145 : ByteEncoding
{
public CP1145()
: base(1145, ToChars, "IBM EBCDIC (Latin America/Spain with Euro)",
"ibm1145", "ibm1145", "ibm1145",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5',
'\u00E7', '\u00A6', '\u005B', '\u002E', '\u003C', '\u0028',
'\u002B', '\u007C', '\u0026', '\u00E9', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u005D', '\u0024', '\u002A', '\u0029', '\u003B', '\u00AC',
'\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1',
'\u00C3', '\u00C5', '\u00C7', '\u0023', '\u00F1', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u0060', '\u003A', '\u00D1', '\u0040', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u20AC', '\u00B5', '\u00A8',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u005E', '\u0021', '\u00AF', '\u007E', '\u00B4', '\u00D7',
'\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9',
'\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0xBB; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x69; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0xBA; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0x4F; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xBD; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x49; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xA1; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0x5F; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x7B; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x6A; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0xBB; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x69; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0xBA; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0x4F; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xBD; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0xBB; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x69; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0xBA; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0x4F; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xBD; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x49; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xA1; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0x5F; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x7B; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x6A; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0xBB; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x69; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0xBA; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0x4F; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xBD; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1145
public class ENCibm1145 : CP1145
{
public ENCibm1145() : base() {}
}; // class ENCibm1145
}; // namespace I18N.Rare
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Plugins.Editor.JetBrains
{
[InitializeOnLoad]
public static class RiderPlugin
{
private static bool Initialized;
private static string SlnFile;
private static string DefaultApp
{
get { return EditorPrefs.GetString("kScriptsDefaultApp"); }
}
public static bool TargetFrameworkVersion45
{
get { return EditorPrefs.GetBool("Rider_TargetFrameworkVersion45", true); }
set { EditorPrefs.SetBool("Rider_TargetFrameworkVersion45", value); }
}
internal static bool Enabled
{
get
{
return !string.IsNullOrEmpty(DefaultApp) && DefaultApp.ToLower().Contains("rider");
}
}
static RiderPlugin()
{
if (Enabled)
{
InitRiderPlugin();
}
}
private static void InitRiderPlugin()
{
var riderFileInfo = new FileInfo(DefaultApp);
var newPath = riderFileInfo.FullName;
// try to search the new version
if (!riderFileInfo.Exists)
{
switch (riderFileInfo.Extension)
{
case ".exe":
{
var possibleNew =
riderFileInfo.Directory.Parent.Parent.GetDirectories("*ider*")
.SelectMany(a => a.GetDirectories("bin"))
.SelectMany(a => a.GetFiles(riderFileInfo.Name))
.ToArray();
if (possibleNew.Length > 0)
newPath = possibleNew.OrderBy(a => a.LastWriteTime).Last().FullName;
break;
}
}
if (newPath != riderFileInfo.FullName)
{
Log(string.Format("Update {0} to {1}", riderFileInfo.FullName, newPath));
EditorPrefs.SetString("kScriptsDefaultApp", newPath);
}
}
var projectDirectory = Directory.GetParent(Application.dataPath).FullName;
var projectName = Path.GetFileName(projectDirectory);
SlnFile = Path.Combine(projectDirectory, string.Format("{0}.sln", projectName));
UpdateUnitySettings(SlnFile);
Initialized = true;
}
/// <summary>
/// Helps to open xml and txt files at least on Windows
/// </summary>
/// <param name="slnFile"></param>
private static void UpdateUnitySettings(string slnFile)
{
try
{
EditorPrefs.SetString("kScriptEditorArgs", string.Format("{0}{1}{0} {0}$(File){0}", "\"", slnFile));
}
catch (Exception e)
{
Log("Exception on updating kScriptEditorArgs: " + e.Message);
}
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
if (Enabled)
{
if (!Initialized)
{
// make sure the plugin was initialized first.
// this can happen in case "Rider" was set as the default scripting app only after this plugin was imported.
InitRiderPlugin();
RiderAssetPostprocessor.OnGeneratedCSProjectFiles();
}
string appPath = Path.GetDirectoryName(Application.dataPath);
// determine asset that has been double clicked in the project view
var selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript" ||
selected.GetType().ToString() == "UnityEngine.Shader")
{
SyncSolution(); // added to handle opening file, which was just recently created.
var assetFilePath = Path.Combine(appPath, AssetDatabase.GetAssetPath(selected));
if (!CallUDPRider(line, SlnFile, assetFilePath))
{
var args = string.Format("{0}{1}{0} -l {2} {0}{3}{0}", "\"", SlnFile, line, assetFilePath);
CallRider(DefaultApp, args);
}
return true;
}
}
return false;
}
private static bool CallUDPRider(int line, string slnPath, string filePath)
{
Log(string.Format("CallUDPRider({0} {1} {2})", line, slnPath, filePath));
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
try
{
sock.ReceiveTimeout = 10000;
var serverAddr = IPAddress.Parse("127.0.0.1");
var endPoint = new IPEndPoint(serverAddr, 11234);
var text = line + "\r\n" + slnPath + "\r\n" + filePath + "\r\n";
var send_buffer = Encoding.ASCII.GetBytes(text);
sock.SendTo(send_buffer, endPoint);
var rcv_buffer = new byte[1024];
// Poll the socket for reception with a 10 ms timeout.
if (!sock.Poll(10000, SelectMode.SelectRead))
{
throw new TimeoutException();
}
int bytesRec = sock.Receive(rcv_buffer); // This call will not block
string status = Encoding.ASCII.GetString(rcv_buffer, 0, bytesRec);
if (status == "ok")
{
ActivateWindow(new FileInfo(DefaultApp).FullName);
return true;
}
}
catch (Exception)
{
//error Timed out
Log("Socket error or no response. Have you installed RiderUnity3DConnector in Rider?");
}
}
return false;
}
private static void CallRider(string riderPath, string args)
{
var riderFileInfo = new FileInfo(riderPath);
var macOSVersion = riderFileInfo.Extension == ".app";
var riderExists = macOSVersion ? new DirectoryInfo(riderPath).Exists : riderFileInfo.Exists;
if (!riderExists)
{
EditorUtility.DisplayDialog("Rider executable not found", "Please update 'External Script Editor' path to JetBrains Rider.", "OK");
}
var proc = new Process();
if (macOSVersion)
{
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = string.Format("-n {0}{1}{0} --args {2}", "\"", "/" + riderPath, args);
Log(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
}
else
{
proc.StartInfo.FileName = riderPath;
proc.StartInfo.Arguments = args;
Log("\"" + proc.StartInfo.FileName + "\"" + " " + proc.StartInfo.Arguments);
}
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
ActivateWindow(riderPath);
}
private static void ActivateWindow(string riderPath)
{
if (new FileInfo(riderPath).Extension == ".exe")
{
try
{
var process = Process.GetProcesses().FirstOrDefault(p =>
{
string processName;
try
{
processName = p.ProcessName; // some processes like kaspersky antivirus throw exception on attempt to get ProcessName
}
catch (Exception)
{
return false;
}
return !p.HasExited && processName.ToLower().Contains("rider");
});
if (process != null)
{
// Collect top level windows
var topLevelWindows = User32Dll.GetTopLevelWindowHandles();
// Get process main window title
var windowHandle = topLevelWindows.FirstOrDefault(hwnd => User32Dll.GetWindowProcessId(hwnd) == process.Id);
if (windowHandle != IntPtr.Zero)
User32Dll.SetForegroundWindow(windowHandle);
}
}
catch (Exception e)
{
Log("Exception on ActivateWindow: " + e);
}
}
}
[MenuItem("Assets/Open C# Project in Rider", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallRider(DefaultApp, string.Format("{0}{1}{0}", "\"", SlnFile));
}
[MenuItem("Assets/Open C# Project in Rider", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// Force Unity To Write Project File
/// </summary>
private static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
public static void Log(object message)
{
Debug.Log("[Rider] " + message);
}
/// <summary>
/// JetBrains Rider Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem("Rider")]
static void RiderPreferencesItem()
{
EditorGUILayout.BeginVertical();
var url = "https://github.com/JetBrains/Unity3dRider";
if (GUILayout.Button(url))
{
Application.OpenURL(url);
}
EditorGUI.BeginChangeCheck();
var help = @"For now target 4.5 is strongly recommended.
- Without 4.5:
- Rider will fail to resolve System.Linq on Mac/Linux
- Rider will fail to resolve Firebase Analytics.
- With 4.5 Rider will show ambiguos references in UniRx.
All thouse problems will go away after Unity upgrades to mono4.";
TargetFrameworkVersion45 =
EditorGUILayout.Toggle(
new GUIContent("TargetFrameworkVersion 4.5",
help), TargetFrameworkVersion45);
EditorGUILayout.HelpBox(help, MessageType.None);
EditorGUI.EndChangeCheck();
}
static class User32Dll
{
/// <summary>
/// Gets the ID of the process that owns the window.
/// Note that creating a <see cref="Process"/> wrapper for that is very expensive because it causes an enumeration of all the system processes to happen.
/// </summary>
public static int GetWindowProcessId(IntPtr hwnd)
{
uint dwProcessId;
GetWindowThreadProcessId(hwnd, out dwProcessId);
return unchecked((int) dwProcessId);
}
/// <summary>
/// Lists the handles of all the top-level windows currently available in the system.
/// </summary>
public static List<IntPtr> GetTopLevelWindowHandles()
{
var retval = new List<IntPtr>();
EnumWindowsProc callback = (hwnd, param) =>
{
retval.Add(hwnd);
return 1;
};
EnumWindows(Marshal.GetFunctionPointerForDelegate(callback), IntPtr.Zero);
GC.KeepAlive(callback);
return retval;
}
public delegate Int32 EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
public static extern Int32 EnumWindows(IntPtr lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
public static extern Int32 SetForegroundWindow(IntPtr hWnd);
}
}
}
// Developed using JetBrains Rider =)
| |
using Orleans.CodeGenerator.SyntaxGeneration;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using static Orleans.CodeGenerator.InvokableGenerator;
using static Orleans.CodeGenerator.SerializerGenerator;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator
{
internal static class CopierGenerator
{
private const string BaseTypeCopierFieldName = "_baseTypeCopier";
private const string ActivatorFieldName = "_activator";
private const string DeepCopyMethodName = "DeepCopy";
public static ClassDeclarationSyntax GenerateCopier(
LibraryTypes libraryTypes,
ISerializableTypeDescription type)
{
var simpleClassName = GetSimpleClassName(type);
var members = new List<ISerializableMember>();
foreach (var member in type.Members)
{
if (member is ISerializableMember serializable)
{
members.Add(serializable);
}
else if (member is IFieldDescription or IPropertyDescription)
{
members.Add(new SerializableMember(libraryTypes, type, member, members.Count));
}
else if (member is MethodParameterFieldDescription methodParameter)
{
members.Add(new SerializableMethodMember(methodParameter));
}
}
var accessibility = type.Accessibility switch
{
Accessibility.Public => SyntaxKind.PublicKeyword,
_ => SyntaxKind.InternalKeyword,
};
var classDeclaration = ClassDeclaration(simpleClassName)
.AddBaseListTypes(SimpleBaseType(libraryTypes.DeepCopier_1.ToTypeSyntax(type.TypeSyntax)))
.AddModifiers(Token(accessibility), Token(SyntaxKind.SealedKeyword))
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetGeneratedCodeAttributeSyntax())));
if (type.IsImmutable)
{
var copyMethod = GenerateImmutableTypeCopyMethod(type, libraryTypes);
classDeclaration = classDeclaration.AddMembers(copyMethod);
}
else
{
var fieldDescriptions = GetFieldDescriptions(type, members, libraryTypes);
var fieldDeclarations = GetFieldDeclarations(fieldDescriptions);
var ctor = GenerateConstructor(libraryTypes, simpleClassName, fieldDescriptions);
var copyMethod = GenerateMemberwiseDeepCopyMethod(type, fieldDescriptions, members, libraryTypes);
classDeclaration = classDeclaration
.AddMembers(copyMethod)
.AddMembers(fieldDeclarations)
.AddMembers(ctor);
if (!type.IsSealedType)
{
classDeclaration = classDeclaration
.AddMembers(GenerateBaseCopierDeepCopyMethod(type, fieldDescriptions, members, libraryTypes))
.AddBaseListTypes(SimpleBaseType(libraryTypes.BaseCopier_1.ToTypeSyntax(type.TypeSyntax)));
}
}
if (type.IsGenericType)
{
classDeclaration = SyntaxFactoryUtility.AddGenericTypeParameters(classDeclaration, type.TypeParameters);
}
return classDeclaration;
}
public static string GetSimpleClassName(ISerializableTypeDescription serializableType) => GetSimpleClassName(serializableType.Name);
public static string GetSimpleClassName(string name) => $"Copier_{name}";
public static string GetGeneratedNamespaceName(ITypeSymbol type) => type.GetNamespaceAndNesting() switch
{
{ Length: > 0 } ns => $"{CodeGenerator.CodeGeneratorName}.{ns}",
_ => CodeGenerator.CodeGeneratorName
};
private static MemberDeclarationSyntax[] GetFieldDeclarations(List<GeneratedFieldDescription> fieldDescriptions)
{
return fieldDescriptions.Select(GetFieldDeclaration).ToArray();
static MemberDeclarationSyntax GetFieldDeclaration(GeneratedFieldDescription description)
{
switch (description)
{
case SetterFieldDescription setter:
{
var fieldSetterVariable = VariableDeclarator(setter.FieldName);
return
FieldDeclaration(VariableDeclaration(setter.FieldType).AddVariables(fieldSetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword));
}
case GetterFieldDescription getter:
{
var fieldGetterVariable = VariableDeclarator(getter.FieldName);
return
FieldDeclaration(VariableDeclaration(getter.FieldType).AddVariables(fieldGetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword));
}
default:
return FieldDeclaration(VariableDeclaration(description.FieldType, SingletonSeparatedList(VariableDeclarator(description.FieldName))))
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword));
}
}
}
private static ConstructorDeclarationSyntax GenerateConstructor(LibraryTypes libraryTypes, string simpleClassName, List<GeneratedFieldDescription> fieldDescriptions)
{
var injected = fieldDescriptions.Where(f => f.IsInjected).ToList();
var parameters = new List<ParameterSyntax>(injected.Select(f => Parameter(f.FieldName.ToIdentifier()).WithType(f.FieldType)));
const string CodecProviderParameterName = "codecProvider";
parameters.Add(Parameter(Identifier(CodecProviderParameterName)).WithType(libraryTypes.ICodecProvider.ToTypeSyntax()));
IEnumerable<StatementSyntax> GetStatements()
{
foreach (var field in fieldDescriptions)
{
switch (field)
{
case GetterFieldDescription getter:
yield return getter.InitializationSyntax;
break;
case SetterFieldDescription setter:
yield return setter.InitializationSyntax;
break;
case GeneratedFieldDescription _ when field.IsInjected:
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ThisExpression().Member(field.FieldName.ToIdentifierName()),
Unwrapped(field.FieldName.ToIdentifierName())));
break;
case CopierFieldDescription codec when !field.IsInjected:
{
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ThisExpression().Member(field.FieldName.ToIdentifierName()),
GetService(field.FieldType)));
}
break;
}
}
}
return ConstructorDeclaration(simpleClassName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.ToArray())
.AddBodyStatements(GetStatements().ToArray());
static ExpressionSyntax Unwrapped(ExpressionSyntax expr)
{
return InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName("UnwrapService")),
ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(expr) })));
}
static ExpressionSyntax GetService(TypeSyntax type)
{
return InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), GenericName(Identifier("GetService"), TypeArgumentList(SingletonSeparatedList(type)))),
ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(IdentifierName(CodecProviderParameterName)) })));
}
}
private static List<GeneratedFieldDescription> GetFieldDescriptions(
ISerializableTypeDescription serializableTypeDescription,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var fields = new List<GeneratedFieldDescription>();
if (serializableTypeDescription.HasComplexBaseType)
{
fields.Add(new BaseCopierFieldDescription(libraryTypes.BaseCopier_1.ToTypeSyntax(serializableTypeDescription.BaseTypeSyntax), BaseTypeCopierFieldName));
}
if (serializableTypeDescription.UseActivator)
{
fields.Add(new ActivatorFieldDescription(libraryTypes.IActivator_1.ToTypeSyntax(serializableTypeDescription.TypeSyntax), ActivatorFieldName));
}
// Add a codec field for any field in the target which does not have a static codec.
fields.AddRange(serializableTypeDescription.Members
.Distinct(MemberDescriptionTypeComparer.Default)
.Where(t => !libraryTypes.StaticCopiers.Any(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, t.Type)))
.Select(member => GetCopierDescription(member)));
foreach (var member in members)
{
if (member.GetGetterFieldDescription() is { } getterFieldDescription)
{
fields.Add(getterFieldDescription);
}
if (member.GetSetterFieldDescription() is { } setterFieldDescription)
{
fields.Add(setterFieldDescription);
}
}
for (var hookIndex = 0; hookIndex < serializableTypeDescription.SerializationHooks.Count; ++hookIndex)
{
var hookType = serializableTypeDescription.SerializationHooks[hookIndex];
fields.Add(new SerializationHookFieldDescription(hookType.ToTypeSyntax(), $"_hook{hookIndex}"));
}
return fields;
CopierFieldDescription GetCopierDescription(IMemberDescription member)
{
TypeSyntax copierType = null;
var t = member.Type;
if (t.HasAttribute(libraryTypes.GenerateSerializerAttribute)
&& (!SymbolEqualityComparer.Default.Equals(t.ContainingAssembly, libraryTypes.Compilation.Assembly) || t.ContainingAssembly.HasAttribute(libraryTypes.TypeManifestProviderAttribute)))
{
// Use the concrete generated type and avoid expensive interface dispatch
if (t is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsGenericType)
{
// Construct the full generic type name
var ns = GetGeneratedNamespaceName(t);
var name = GenericName(Identifier(GetSimpleClassName(t.Name)), TypeArgumentList(SeparatedList(namedTypeSymbol.TypeArguments.Select(arg => arg.ToTypeSyntax()))));
copierType = QualifiedName(ParseName(ns), name);
}
else
{
var simpleName = $"{GetGeneratedNamespaceName(t)}.{GetSimpleClassName(t.Name)}";
copierType = ParseTypeName(simpleName);
}
}
else if (libraryTypes.WellKnownCopiers.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, t)) is WellKnownCopierDescription codec)
{
// The codec is not a static copier and is also not a generic copiers.
copierType = codec.CopierType.ToTypeSyntax();
}
else if (t is INamedTypeSymbol named && libraryTypes.WellKnownCopiers.Find(c => t is INamedTypeSymbol named && named.ConstructedFrom is ISymbol unboundFieldType && SymbolEqualityComparer.Default.Equals(c.UnderlyingType, unboundFieldType)) is WellKnownCopierDescription genericCopier)
{
// Construct the generic copier type using the field's type arguments.
copierType = genericCopier.CopierType.Construct(named.TypeArguments.ToArray()).ToTypeSyntax();
}
else
{
// Use the IDeepCopier<T> interface
copierType = libraryTypes.DeepCopier_1.ToTypeSyntax(member.TypeSyntax);
}
var fieldName = '_' + ToLowerCamelCase(member.TypeNameIdentifier) + "Copier";
return new CopierFieldDescription(copierType, fieldName, t);
}
static string ToLowerCamelCase(string input) => char.IsLower(input, 0) ? input : char.ToLowerInvariant(input[0]) + input.Substring(1);
}
private static MemberDeclarationSyntax GenerateMemberwiseDeepCopyMethod(
ISerializableTypeDescription type,
List<GeneratedFieldDescription> copierFields,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var returnType = type.TypeSyntax;
var originalParam = "original".ToIdentifierName();
var contextParam = "context".ToIdentifierName();
var resultVar = "result".ToIdentifierName();
var body = new List<StatementSyntax>();
ExpressionSyntax createValueExpression = type.UseActivator switch
{
true => InvocationExpression(copierFields.OfType<ActivatorFieldDescription>().Single().FieldName.ToIdentifierName().Member("Create")),
false => type.GetObjectCreationExpression(libraryTypes)
};
if (!type.IsValueType)
{
// C#: if (context.TryGetCopy(original, out T result)) { return result; }
var tryGetCopy = InvocationExpression(
contextParam.Member("TryGetCopy"),
ArgumentList(SeparatedList(new[]
{
Argument(originalParam),
Argument(DeclarationExpression(
type.TypeSyntax,
SingleVariableDesignation(Identifier("result"))))
.WithRefKindKeyword(Token(SyntaxKind.OutKeyword))
})));
body.Add(IfStatement(tryGetCopy, ReturnStatement(resultVar)));
if (!type.IsSealedType)
{
// C#: if (original.GetType() != typeof(<codec>)) { return context.Copy(original); }
var exactTypeMatch = BinaryExpression(
SyntaxKind.NotEqualsExpression,
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, originalParam, IdentifierName("GetType"))),
TypeOfExpression(type.TypeSyntax));
var contextCopy = InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, contextParam, IdentifierName("Copy")))
.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(originalParam))));
body.Add(IfStatement(exactTypeMatch, ReturnStatement(contextCopy)));
}
// C#: result = _activator.Create();
body.Add(ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, resultVar, createValueExpression)));
// C#: context.RecordCopy(original, result);
body.Add(ExpressionStatement(InvocationExpression(contextParam.Member("RecordCopy"), ArgumentList(SeparatedList(new[]
{
Argument(originalParam),
Argument(resultVar)
})))));
if (type.HasComplexBaseType)
{
// C#: _baseTypeCopier.DeepCopy(original, result, context);
body.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(BaseTypeCopierFieldName.ToIdentifierName()).Member(DeepCopyMethodName),
ArgumentList(SeparatedList(new[]
{
Argument(originalParam),
Argument(resultVar),
Argument(contextParam)
})))));
}
}
else
{
// C#: TField result = _activator.Create();
// or C#: TField result = new TField();
body.Add(LocalDeclarationStatement(
VariableDeclaration(
type.TypeSyntax,
SingletonSeparatedList(VariableDeclarator(resultVar.Identifier)
.WithInitializer(EqualsValueClause(createValueExpression))))));
}
body.AddRange(AddSerializationCallbacks(type, originalParam, resultVar, "OnCopying"));
body.AddRange(GenerateMemberwiseCopy(copierFields, members, libraryTypes, originalParam, contextParam, resultVar));
body.AddRange(AddSerializationCallbacks(type, originalParam, resultVar, "OnCopied"));
body.Add(ReturnStatement(resultVar));
var parameters = new[]
{
Parameter(originalParam.Identifier).WithType(type.TypeSyntax),
Parameter(contextParam.Identifier).WithType(libraryTypes.CopyContext.ToTypeSyntax())
};
return MethodDeclaration(returnType, DeepCopyMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static MemberDeclarationSyntax GenerateBaseCopierDeepCopyMethod(
ISerializableTypeDescription type,
List<GeneratedFieldDescription> copierFields,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var inputParam = "input".ToIdentifierName();
var resultParam = "output".ToIdentifierName();
var contextParam = "context".ToIdentifierName();
var body = new List<StatementSyntax>();
if (type.HasComplexBaseType)
{
// C#: _baseTypeCopier.DeepCopy(original, result, context);
body.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(BaseTypeCopierFieldName.ToIdentifierName()).Member(DeepCopyMethodName),
ArgumentList(SeparatedList(new[]
{
Argument(inputParam),
Argument(resultParam),
Argument(contextParam)
})))));
}
body.AddRange(AddSerializationCallbacks(type, inputParam, resultParam, "OnCopying"));
body.AddRange(GenerateMemberwiseCopy(copierFields, members, libraryTypes, inputParam, contextParam, resultParam));
body.AddRange(AddSerializationCallbacks(type, inputParam, resultParam, "OnCopied"));
var parameters = new[]
{
Parameter(inputParam.Identifier).WithType(type.TypeSyntax),
Parameter(resultParam.Identifier).WithType(type.TypeSyntax),
Parameter(contextParam.Identifier).WithType(libraryTypes.CopyContext.ToTypeSyntax())
};
return MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), DeepCopyMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static IEnumerable<StatementSyntax> GenerateMemberwiseCopy(
List<GeneratedFieldDescription> copierFields,
List<ISerializableMember> members,
LibraryTypes libraryTypes,
IdentifierNameSyntax sourceVar,
IdentifierNameSyntax contextVar,
IdentifierNameSyntax destinationVar)
{
var codecs = copierFields.OfType<ICopierDescription>()
.Concat(libraryTypes.StaticCopiers)
.ToList();
var orderedMembers = members.OrderBy(m => m.Member.FieldId).ToList();
foreach (var member in orderedMembers)
{
var description = member.Member;
// Copiers can either be static classes or injected into the constructor.
// Either way, the member signatures are the same.
var codec = codecs.First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, description.Type));
var memberType = description.Type;
var staticCopier = libraryTypes.StaticCopiers.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, memberType));
ExpressionSyntax codecExpression;
if (staticCopier != null)
{
codecExpression = staticCopier.CopierType.ToNameSyntax();
}
else
{
var instanceCopier = copierFields.OfType<CopierFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType));
codecExpression = ThisExpression().Member(instanceCopier.FieldName);
}
ExpressionSyntax getValueExpression;
if (member.IsShallowCopyable)
{
getValueExpression = member.GetGetter(sourceVar);
}
else
{
getValueExpression = InvocationExpression(
codecExpression.Member(DeepCopyMethodName),
ArgumentList(SeparatedList(new[] { Argument(member.GetGetter(sourceVar)), Argument(contextVar) })));
if (!SymbolEqualityComparer.Default.Equals(codec.UnderlyingType, member.Member.Type))
{
// If the member type type differs from the codec type (eg because the member is an array), cast the result.
getValueExpression = CastExpression(description.TypeSyntax, getValueExpression);
}
}
var memberAssignment = ExpressionStatement(member.GetSetter(destinationVar, getValueExpression));
yield return memberAssignment;
}
}
private static MemberDeclarationSyntax GenerateImmutableTypeCopyMethod(
ISerializableTypeDescription type,
LibraryTypes libraryTypes)
{
var returnType = type.TypeSyntax;
var inputParam = "input".ToIdentifierName();
var body = new StatementSyntax[]
{
ReturnStatement(inputParam)
};
var parameters = new[]
{
Parameter("input".ToIdentifier()).WithType(returnType),
Parameter("_".ToIdentifier()).WithType(libraryTypes.CopyContext.ToTypeSyntax()),
};
return MethodDeclaration(returnType, DeepCopyMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static IEnumerable<StatementSyntax> AddSerializationCallbacks(ISerializableTypeDescription type, IdentifierNameSyntax originalInstance, IdentifierNameSyntax resultInstance, string callbackMethodName)
{
for (var hookIndex = 0; hookIndex < type.SerializationHooks.Count; ++hookIndex)
{
var hookType = type.SerializationHooks[hookIndex];
var member = hookType.GetAllMembers<IMethodSymbol>(callbackMethodName, Accessibility.Public).FirstOrDefault();
if (member is null || member.Parameters.Length != 2)
{
continue;
}
var originalArgument = Argument(originalInstance);
if (member.Parameters[0].RefKind == RefKind.Ref)
{
originalArgument = originalArgument.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword));
}
var resultArgument = Argument(resultInstance);
if (member.Parameters[1].RefKind == RefKind.Ref)
{
resultArgument = resultArgument.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword));
}
yield return ExpressionStatement(InvocationExpression(
ThisExpression().Member($"_hook{hookIndex}").Member(callbackMethodName),
ArgumentList(SeparatedList(new[] { originalArgument, resultArgument }))));
}
}
internal class BaseCopierFieldDescription : GeneratedFieldDescription
{
public BaseCopierFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName)
{
}
public override bool IsInjected => true;
}
internal class CopierFieldDescription : GeneratedFieldDescription, ICopierDescription
{
public CopierFieldDescription(TypeSyntax fieldType, string fieldName, ITypeSymbol underlyingType) : base(fieldType, fieldName)
{
UnderlyingType = underlyingType;
}
public ITypeSymbol UnderlyingType { get; }
public override bool IsInjected => false;
}
}
}
| |
//
// BaseWidgetAccessible.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Atk;
namespace Hyena.Gui
{
#if ENABLE_ATK
public class BaseWidgetAccessible : Gtk.Accessible, Atk.ComponentImplementor
{
private Gtk.Widget widget;
private uint focus_id = 0;
private Dictionary<uint, Atk.FocusHandler> focus_handlers = new Dictionary<uint, Atk.FocusHandler> ();
public BaseWidgetAccessible (Gtk.Widget widget)
{
this.widget = widget;
widget.SizeAllocated += OnAllocated;
widget.Mapped += OnMap;
widget.Unmapped += OnMap;
widget.FocusInEvent += OnFocus;
widget.FocusOutEvent += OnFocus;
widget.AddNotification ("sensitive", (o, a) => NotifyStateChange (StateType.Sensitive, widget.Sensitive));
widget.AddNotification ("visible", (o, a) => NotifyStateChange (StateType.Visible, widget.Visible));
}
public virtual new Atk.Layer Layer {
get { return Layer.Widget; }
}
protected override Atk.StateSet OnRefStateSet ()
{
var s = base.OnRefStateSet ();
AddStateIf (s, widget.CanFocus, StateType.Focusable);
AddStateIf (s, widget.HasFocus, StateType.Focused);
AddStateIf (s, widget.Sensitive, StateType.Sensitive);
AddStateIf (s, widget.Sensitive, StateType.Enabled);
AddStateIf (s, widget.HasDefault, StateType.Default);
AddStateIf (s, widget.Visible, StateType.Visible);
AddStateIf (s, widget.Visible && widget.IsMapped, StateType.Showing);
return s;
}
private static void AddStateIf (StateSet s, bool condition, StateType t)
{
if (condition) {
s.AddState (t);
}
}
private void OnFocus (object o, EventArgs args)
{
NotifyStateChange (StateType.Focused, widget.HasFocus);
var handler = FocusChanged;
if (handler != null) {
handler (this, widget.HasFocus);
}
}
private void OnMap (object o, EventArgs args)
{
NotifyStateChange (StateType.Showing, widget.Visible && widget.IsMapped);
}
private void OnAllocated (object o, EventArgs args)
{
var a = widget.Allocation;
var bounds = new Atk.Rectangle () { X = a.X, Y = a.Y, Width = a.Width, Height = a.Height };
GLib.Signal.Emit (this, "bounds_changed", bounds);
/*var handler = BoundsChanged;
if (handler != null) {
handler (this, new BoundsChangedArgs () { Args = new object [] { bounds } });
}*/
}
private event FocusHandler FocusChanged;
#region Atk.Component
public uint AddFocusHandler (Atk.FocusHandler handler)
{
if (!focus_handlers.ContainsValue (handler)) {
FocusChanged += handler;
focus_handlers[++focus_id] = handler;
return focus_id;
}
return 0;
}
public bool Contains (int x, int y, Atk.CoordType coordType)
{
int x_extents, y_extents, w, h;
GetExtents (out x_extents, out y_extents, out w, out h, coordType);
Gdk.Rectangle extents = new Gdk.Rectangle (x_extents, y_extents, w, h);
return extents.Contains (x, y);
}
public virtual Atk.Object RefAccessibleAtPoint (int x, int y, Atk.CoordType coordType)
{
return new NoOpObject (widget);
}
public void GetExtents (out int x, out int y, out int w, out int h, Atk.CoordType coordType)
{
w = widget.Allocation.Width;
h = widget.Allocation.Height;
GetPosition (out x, out y, coordType);
}
public void GetPosition (out int x, out int y, Atk.CoordType coordType)
{
Gdk.Window window = null;
if (!widget.IsDrawable) {
x = y = Int32.MinValue;
return;
}
if (widget.Parent != null) {
x = widget.Allocation.X;
y = widget.Allocation.Y;
window = widget.ParentWindow;
} else {
x = 0;
y = 0;
window = widget.GdkWindow;
}
int x_window, y_window;
window.GetOrigin (out x_window, out y_window);
x += x_window;
y += y_window;
if (coordType == Atk.CoordType.Window) {
window = widget.GdkWindow.Toplevel;
int x_toplevel, y_toplevel;
window.GetOrigin (out x_toplevel, out y_toplevel);
x -= x_toplevel;
y -= y_toplevel;
}
}
public void GetSize (out int w, out int h)
{
w = widget.Allocation.Width;
h = widget.Allocation.Height;
}
public bool GrabFocus ()
{
if (!widget.CanFocus) {
return false;
}
widget.GrabFocus ();
var toplevel_window = widget.Toplevel as Gtk.Window;
if (toplevel_window != null) {
toplevel_window.Present ();
}
return true;
}
public void RemoveFocusHandler (uint handlerId)
{
if (focus_handlers.ContainsKey (handlerId)) {
FocusChanged -= focus_handlers[handlerId];
focus_handlers.Remove (handlerId);
}
}
public bool SetExtents (int x, int y, int w, int h, Atk.CoordType coordType)
{
return SetSizeAndPosition (x, y, w, h, coordType, true);
}
public bool SetPosition (int x, int y, Atk.CoordType coordType)
{
return SetSizeAndPosition (x, y, 0, 0, coordType, false);
}
private bool SetSizeAndPosition (int x, int y, int w, int h, Atk.CoordType coordType, bool setSize)
{
if (!widget.IsTopLevel) {
return false;
}
if (coordType == CoordType.Window) {
int x_off, y_off;
widget.GdkWindow.GetOrigin (out x_off, out y_off);
x += x_off;
y += y_off;
if (x < 0 || y < 0) {
return false;
}
}
#pragma warning disable 0612
widget.SetUposition (x, y);
#pragma warning restore 0612
if (setSize) {
widget.SetSizeRequest (w, h);
}
return true;
}
public bool SetSize (int w, int h)
{
if (widget.IsTopLevel) {
widget.SetSizeRequest (w, h);
return true;
} else {
return false;
}
}
public double Alpha {
get { return 1.0; }
}
#endregion Atk.Component
}
#endif
}
| |
/*
* C# port of Mozilla Character Set Detector
* https://code.google.com/p/chardetsharp/
*
* Original Mozilla License Block follows
*
*/
#region License Block
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// The Original Code is Mozilla Universal charset detector code.
//
// The Initial Developer of the Original Code is
// Netscape Communications Corporation.
// Portions created by the Initial Developer are Copyright (C) 2001
// the Initial Developer. All Rights Reserved.
//
// Contributor(s):
// Shy Shalom <shooshX@gmail.com>
//
// Alternatively, the contents of this file may be used under the terms of
// either the GNU General Public License Version 2 or later (the "GPL"), or
// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
// in which case the provisions of the GPL or the LGPL are applicable instead
// of those above. If you wish to allow use of your version of this file only
// under the terms of either the GPL or the LGPL, and not to allow others to
// use your version of this file under the terms of the MPL, indicate your
// decision by deleting the provisions above and replace them with the notice
// and other provisions required by the GPL or the LGPL. If you do not delete
// the provisions above, a recipient may use your version of this file under
// the terms of any one of the MPL, the GPL or the LGPL.
#endregion
namespace Cloney.Core.CharsetDetection
{
class Latin1Prober : AbstractCSProber
{
const int FREQ_CAT_NUM = 4;
public Latin1Prober() { Reset(); }
public override ProbingState HandleData(byte[] aBuf)
{
return HandleData(aBuf, aBuf.Length);
}
public override ProbingState HandleData(byte[] aBuf, int length)
{
byte[] newBuf1 = new byte[aBuf.Length];
int newLen1 = 0;
newLen1 = FilterWithEnglishLetters(aBuf, newBuf1);
byte charClass;
byte freq;
for (int i = 0; i < newLen1; i++)
{
charClass = Latin1_CharToClass[(byte)newBuf1[i]];
freq = Latin1ClassModel[mLastCharClass * CLASS_NUM + charClass];
if (freq == 0)
{
mState = ProbingState.NotMe;
break;
}
mFreqCounter[freq]++;
mLastCharClass = charClass;
}
if (newBuf1 != aBuf)
newBuf1 = null;
return mState;
}
public override void Reset()
{
mState = ProbingState.Detecting;
mLastCharClass = OTH;
for (int i = 0; i < FREQ_CAT_NUM; i++)
mFreqCounter[i] = 0;
active = true;
}
public override string CharSetName { get { return "windows-1252"; } }
public override ProbingState State { get { return mState; } }
public override float GetConfidence()
{
if (mState == ProbingState.NotMe)
return 0.01f;
float confidence;
int total = 0;
for (int i = 0; i < FREQ_CAT_NUM; i++)
total += mFreqCounter[i];
if (total == 0)
confidence = 0.0f;
else
{
confidence = mFreqCounter[3] * 1.0f / total;
confidence -= mFreqCounter[1] * 20.0f / total;
}
if (confidence < 0.0f)
confidence = 0.0f;
// lower the confidence of latin1 so that other more accurate detector
// can take priority.
confidence *= 0.50f;
return confidence;
}
public override void SetOpion() { }
public override bool IsActive
{
get { return active; }
set { active = value; }
}
protected ProbingState mState;
protected byte mLastCharClass;
protected int[] mFreqCounter = new int[FREQ_CAT_NUM];
protected bool active;
const byte UDF = 0; // undefined
const byte OTH = 1; // other
const byte ASC = 2; // ascii capital letter
const byte ASS = 3; // ascii small letter
const byte ACV = 4; // accent capital vowel
const byte ACO = 5; // accent capital other
const byte ASV = 6; // accent small vowel
const byte ASO = 7; // accent small other
const byte CLASS_NUM = 8; // total classes
static readonly byte[] Latin1_CharToClass = new byte[] {
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 00 - 07
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 08 - 0F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 10 - 17
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 18 - 1F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 20 - 27
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 28 - 2F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 30 - 37
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 38 - 3F
OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 40 - 47
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 48 - 4F
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 50 - 57
ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, // 58 - 5F
OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 60 - 67
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 68 - 6F
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 70 - 77
ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, // 78 - 7F
OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, // 80 - 87
OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, // 88 - 8F
UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 90 - 97
OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, // 98 - 9F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A0 - A7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A8 - AF
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B0 - B7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B8 - BF
ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, // C0 - C7
ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, // C8 - CF
ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, // D0 - D7
ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, // D8 - DF
ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, // E0 - E7
ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, // E8 - EF
ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, // F0 - F7
ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, // F8 - FF
};
/* 0 : illegal
1 : very unlikely
2 : normal
3 : very likely
*/
static readonly byte[] Latin1ClassModel = new byte[] {
/* UDF OTH ASC ASS ACV ACO ASV ASO */
/*UDF*/ 0, 0, 0, 0, 0, 0, 0, 0,
/*OTH*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASC*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASS*/ 0, 3, 3, 3, 1, 1, 3, 3,
/*ACV*/ 0, 3, 3, 3, 1, 2, 1, 2,
/*ACO*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASV*/ 0, 3, 1, 3, 1, 1, 1, 3,
/*ASO*/ 0, 3, 1, 3, 1, 1, 3, 3,
};
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.IO;
namespace m
{
/// <summary>
/// Summary description for LevelViewParent.
/// </summary>
public class LevelViewParent : System.Windows.Forms.UserControl, ICommandTarget
{
private m.LevelView view;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ComboBox comboDocs;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ToolBarButton toolBarButtonHideToolbar;
private System.Windows.Forms.Panel panelToolbar;
private System.Windows.Forms.Panel panelShowToolbar;
private System.Windows.Forms.ToolBar toolBarShowToolbar;
private System.Windows.Forms.ToolBarButton toolBarButtonShowToolbar;
private System.Windows.Forms.ToolBarButton toolBarButtonToggleTemplates;
private System.Windows.Forms.ToolBarButton toolBarButtonToggleGobs;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox comboZoom;
private System.Windows.Forms.ToolBarButton toolBarButtonToggleAreas;
TemplateDoc m_tmpdCurrent = null;
public LevelViewParent()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Default
panelShowToolbar.Hide();
panelToolbar.Show();
// Easier than creating a resource file?
System.Reflection.Assembly ass = typeof(LevelViewParent).Module.Assembly;
Stream stm = ass.GetManifestResourceStream("m.toolstrip.bmp");
imageList1.Images.AddStrip(new Bitmap(stm));
TemplateDocTemplate doct = (TemplateDocTemplate)DocManager.FindDocTemplate(typeof(TemplateDoc));
doct.DocAdded += new DocTemplate.DocAddedHandler(TemplateDocTemplate_DocAdded);
doct.DocRemoved += new DocTemplate.DocRemovedHandler(TemplateDocTemplate_DocRemoved);
// Combo index 0
FillCombo();
comboDocs.SelectedIndex = 0;
UpdateZoomSelection();
view.ScaleChanged += new EventHandler(View_ScaleChanged);
}
public void DispatchCommand(Command cmd) {
switch (cmd) {
case Command.Cut:
view.Cut();
break;
case Command.Copy:
view.Copy();
break;
case Command.Paste:
view.Paste();
break;
case Command.Delete:
view.Delete();
break;
}
}
void TemplateDocTemplate_DocAdded(Document doc) {
comboDocs.Items.Add(doc);
comboDocs.Invalidate();
}
void TemplateDocTemplate_DocRemoved(Document doc) {
// We'll get notified of this after the window has been destroyed. Only
// handle this event if this isn't the case
if (!Created)
return;
if (m_tmpdCurrent == (TemplateDoc)doc) {
m_tmpdCurrent = null;
comboDocs.SelectedIndex = 0;
}
comboDocs.Items.Remove(doc);
}
void FillCombo() {
comboDocs.Items.Clear();
TemplateDocTemplate doct = (TemplateDocTemplate)DocManager.FindDocTemplate(typeof(TemplateDoc));
Document[] adoc = doct.GetDocuments();
comboDocs.Items.Add("");
foreach (Document doc in adoc)
comboDocs.Items.Add(doc);
}
public void SetDocument(Document doc) {
view.SetDocument(doc);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.view = new m.LevelView();
this.panelToolbar = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.comboZoom = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.toolBarButtonToggleTemplates = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonToggleGobs = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonToggleAreas = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonHideToolbar = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.comboDocs = new System.Windows.Forms.ComboBox();
this.panelShowToolbar = new System.Windows.Forms.Panel();
this.toolBarShowToolbar = new System.Windows.Forms.ToolBar();
this.toolBarButtonShowToolbar = new System.Windows.Forms.ToolBarButton();
this.panelToolbar.SuspendLayout();
this.panelShowToolbar.SuspendLayout();
this.SuspendLayout();
//
// view
//
this.view.AllowDrop = true;
this.view.BackColor = System.Drawing.Color.Black;
this.view.Dock = System.Windows.Forms.DockStyle.Fill;
this.view.Name = "view";
this.view.Size = new System.Drawing.Size(720, 616);
this.view.TabIndex = 0;
//
// panelToolbar
//
this.panelToolbar.BackColor = System.Drawing.Color.White;
this.panelToolbar.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelToolbar.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label2,
this.comboZoom,
this.label1,
this.toolBar1,
this.comboDocs});
this.panelToolbar.Location = new System.Drawing.Point(-1, -1);
this.panelToolbar.Name = "panelToolbar";
this.panelToolbar.Size = new System.Drawing.Size(452, 25);
this.panelToolbar.TabIndex = 1;
this.panelToolbar.Visible = false;
//
// label2
//
this.label2.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label2.Location = new System.Drawing.Point(200, 4);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 23);
this.label2.TabIndex = 5;
this.label2.Text = "Zoom Percent:";
//
// comboZoom
//
this.comboZoom.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.comboZoom.Items.AddRange(new object[] {
"50",
"75",
"100",
"125",
"150",
"200",
"250",
"300"});
this.comboZoom.Location = new System.Drawing.Point(280, 1);
this.comboZoom.Name = "comboZoom";
this.comboZoom.Size = new System.Drawing.Size(72, 21);
this.comboZoom.TabIndex = 4;
this.comboZoom.TabStop = false;
this.comboZoom.KeyDown += new System.Windows.Forms.KeyEventHandler(this.comboZoom_KeyDown);
this.comboZoom.SelectedIndexChanged += new System.EventHandler(this.comboZoom_SelectedIndexChanged);
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label1.Location = new System.Drawing.Point(0, 4);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 23);
this.label1.TabIndex = 3;
this.label1.Text = "View with:";
//
// toolBar1
//
this.toolBar1.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButtonToggleTemplates,
this.toolBarButtonToggleGobs,
this.toolBarButtonToggleAreas,
this.toolBarButtonHideToolbar});
this.toolBar1.ButtonSize = new System.Drawing.Size(16, 15);
this.toolBar1.Divider = false;
this.toolBar1.Dock = System.Windows.Forms.DockStyle.None;
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(357, 1);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(99, 22);
this.toolBar1.TabIndex = 2;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// toolBarButtonToggleTemplates
//
this.toolBarButtonToggleTemplates.ImageIndex = 8;
this.toolBarButtonToggleTemplates.Pushed = true;
this.toolBarButtonToggleTemplates.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.toolBarButtonToggleTemplates.ToolTipText = "Toggle Templates";
//
// toolBarButtonToggleGobs
//
this.toolBarButtonToggleGobs.ImageIndex = 9;
this.toolBarButtonToggleGobs.Pushed = true;
this.toolBarButtonToggleGobs.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.toolBarButtonToggleGobs.ToolTipText = "Toggle Gobs";
//
// toolBarButtonToggleAreas
//
this.toolBarButtonToggleAreas.ImageIndex = 10;
this.toolBarButtonToggleAreas.Pushed = true;
this.toolBarButtonToggleAreas.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.toolBarButtonToggleAreas.ToolTipText = "Toggle Areas";
//
// toolBarButtonHideToolbar
//
this.toolBarButtonHideToolbar.ImageIndex = 6;
this.toolBarButtonHideToolbar.ToolTipText = "Hide Toolbar";
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 15);
this.imageList1.TransparentColor = System.Drawing.Color.Magenta;
//
// comboDocs
//
this.comboDocs.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.comboDocs.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.comboDocs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboDocs.Location = new System.Drawing.Point(56, 1);
this.comboDocs.Name = "comboDocs";
this.comboDocs.Size = new System.Drawing.Size(136, 21);
this.comboDocs.TabIndex = 1;
this.comboDocs.TabStop = false;
this.comboDocs.SelectedIndexChanged += new System.EventHandler(this.comboDocs_SelectedIndexChanged);
this.comboDocs.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboDocs_DrawItem);
//
// panelShowToolbar
//
this.panelShowToolbar.BackColor = System.Drawing.Color.White;
this.panelShowToolbar.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelShowToolbar.Controls.AddRange(new System.Windows.Forms.Control[] {
this.toolBarShowToolbar});
this.panelShowToolbar.Location = new System.Drawing.Point(-3, -5);
this.panelShowToolbar.Name = "panelShowToolbar";
this.panelShowToolbar.Size = new System.Drawing.Size(22, 23);
this.panelShowToolbar.TabIndex = 2;
//
// toolBarShowToolbar
//
this.toolBarShowToolbar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBarShowToolbar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButtonShowToolbar});
this.toolBarShowToolbar.ButtonSize = new System.Drawing.Size(16, 15);
this.toolBarShowToolbar.Dock = System.Windows.Forms.DockStyle.None;
this.toolBarShowToolbar.DropDownArrows = true;
this.toolBarShowToolbar.ImageList = this.imageList1;
this.toolBarShowToolbar.Name = "toolBarShowToolbar";
this.toolBarShowToolbar.ShowToolTips = true;
this.toolBarShowToolbar.Size = new System.Drawing.Size(25, 24);
this.toolBarShowToolbar.TabIndex = 0;
this.toolBarShowToolbar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBarShowToolbar_ButtonClick);
//
// toolBarButtonShowToolbar
//
this.toolBarButtonShowToolbar.ImageIndex = 7;
this.toolBarButtonShowToolbar.ToolTipText = "Show Toolbar";
//
// LevelViewParent
//
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panelShowToolbar,
this.panelToolbar,
this.view});
this.Name = "LevelViewParent";
this.Size = new System.Drawing.Size(720, 616);
this.panelToolbar.ResumeLayout(false);
this.panelShowToolbar.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) {
switch (toolBar1.Buttons.IndexOf(e.Button)) {
case 0:
view.SetLayerFlags(view.GetLayerFlags() ^ LayerFlags.Templates);
break;
case 1:
view.SetLayerFlags(view.GetLayerFlags() ^ LayerFlags.Gobs);
break;
case 2:
view.SetLayerFlags(view.GetLayerFlags() ^ LayerFlags.Areas);
break;
case 3:
panelToolbar.Hide();
panelShowToolbar.Show();
break;
}
}
private void toolBarShowToolbar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) {
switch (toolBarShowToolbar.Buttons.IndexOf(e.Button)) {
case 0:
panelShowToolbar.Hide();
panelToolbar.Show();
break;
}
}
private void comboDocs_SelectedIndexChanged(object sender, System.EventArgs e) {
int nIndex = comboDocs.SelectedIndex;
if (nIndex == 0) {
view.SetTemplateDoc(null);
return;
}
view.SetTemplateDoc((TemplateDoc)comboDocs.Items[nIndex]);
}
private void comboDocs_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) {
if (e.Index < 0 || e.Index >= comboDocs.Items.Count)
return;
string strName;
if (e.Index == 0) {
Document docActive = DocManager.GetActiveDocument(typeof(TemplateDoc));
if (docActive == null) {
strName = "None";
} else {
strName = "Active (" + docActive.GetName() + ")";
}
m_tmpdCurrent = null;
} else {
Document doc = (Document)comboDocs.Items[e.Index];
m_tmpdCurrent = (TemplateDoc)doc;
strName = doc.GetName();
}
e.DrawBackground();
e.Graphics.DrawString(strName, e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
private void comboZoom_SelectedIndexChanged(object sender, System.EventArgs e) {
SetScale();
}
private void comboZoom_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
SetScale();
}
}
void SetScale() {
bool fReset = false;
try {
view.SetScale(float.Parse(comboZoom.Text) / 100.0f);
} catch {
fReset = true;
}
if (fReset)
UpdateZoomSelection();
}
void UpdateZoomSelection() {
string strT = ((float)(view.GetScale() * 100.0f)).ToString();
for (int i = 0; i < comboZoom.Items.Count; i++) {
if (strT == float.Parse((string)comboZoom.Items[i]).ToString()) {
comboZoom.SelectedIndex = i;
break;
}
}
comboZoom.Text = strT;
}
void View_ScaleChanged(object sender, EventArgs e) {
UpdateZoomSelection();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Execution;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData;
namespace Microsoft.Build.UnitTests.QA
{
#region delegate
/// <summary>
/// Delegate the call to GetComponent if one is available
/// </summary>
internal delegate IBuildComponent GetComponentDelegate(BuildComponentType type);
#endregion
/// <summary>
/// The mock component host object.
/// </summary>
internal class QAMockHost : MockLoggingService, IBuildComponentHost, IBuildComponent
{
#region IBuildComponentHost Members
/// <summary>
/// The logging service
/// </summary>
private ILoggingService _loggingService = null;
/// <summary>
/// The request engine
/// </summary>
private IBuildRequestEngine _requestEngine = null;
/// <summary>
/// The test data provider
/// </summary>
private ITestDataProvider _testDataProvider = null;
/// <summary>
/// Number of miliseconds of engine idle time to cause a shutdown
/// </summary>
private int _engineShutdownTimeout = 30000;
/// <summary>
/// Number of initial node count
/// </summary>
private int _initialNodeCount = 1;
/// <summary>
/// Default node id
/// </summary>
private int _nodeId = 1;
/// <summary>
/// Only log critical events by default
/// </summary>
private bool _logOnlyCriticalEvents = true;
/// <summary>
/// The last status of the engine reported
/// </summary>
private BuildRequestEngineStatus _lastEngineStatus;
/// <summary>
/// Internal Event that is fired when the engine status changes
/// </summary>
private AutoResetEvent _engineStatusChangedEvent;
/// <summary>
/// Delegate which handles initilizing the components requested for
/// </summary>
private GetComponentDelegate _getComponentCallback;
/// <summary>
/// All the build components returned by the host
/// </summary>
private Queue<IBuildComponent> _buildComponents;
/// <summary>
/// The build parameters.
/// </summary>
private BuildParameters _buildParameters;
/// <summary>
/// Global timeout is 30 seconds
/// </summary>
public static int globalTimeOut = 30000;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
private LegacyThreadingData _legacyThreadingData;
/// <summary>
/// Constructor
/// </summary>
internal QAMockHost(GetComponentDelegate getComponentCallback)
{
_buildParameters = new BuildParameters();
_getComponentCallback = getComponentCallback;
_engineStatusChangedEvent = new AutoResetEvent(false);
_lastEngineStatus = BuildRequestEngineStatus.Shutdown;
_loggingService = this;
_requestEngine = null;
_testDataProvider = null;
_buildComponents = new Queue<IBuildComponent>();
_legacyThreadingData = new LegacyThreadingData();
}
/// <summary>
/// Returns the node logging service. We don't distinguish here.
/// </summary>
/// <param name="buildId">The build for which the service should be returned.</param>
/// <returns>The logging service.</returns>
public ILoggingService LoggingService
{
get
{
return _loggingService;
}
}
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData
{
get
{
return _legacyThreadingData;
}
}
/// <summary>
/// Retrieves the host name.
/// </summary>
public string Name
{
get
{
return "QAMockHost";
}
}
/// <summary>
/// Returns the build parameters.
/// </summary>
public BuildParameters BuildParameters
{
get
{
return _buildParameters;
}
}
/// <summary>
/// Constructs and returns a component of the specified type.
/// </summary>
public IBuildComponent GetComponent(BuildComponentType type)
{
IBuildComponent returnComponent = null;
switch (type)
{
case BuildComponentType.LoggingService: // Singleton
return (IBuildComponent)_loggingService;
case BuildComponentType.TestDataProvider: // Singleton
if (_testDataProvider != null)
{
return (IBuildComponent)_testDataProvider;
}
returnComponent = _getComponentCallback(type);
if (returnComponent != null)
{
returnComponent.InitializeComponent(this);
_testDataProvider = (ITestDataProvider)returnComponent;
}
break;
case BuildComponentType.RequestEngine: // Singleton
if (_requestEngine != null)
{
return (IBuildComponent)_requestEngine;
}
returnComponent = _getComponentCallback(type);
if (returnComponent != null)
{
returnComponent.InitializeComponent(this);
_requestEngine = (IBuildRequestEngine)returnComponent;
_requestEngine.OnEngineException += new EngineExceptionDelegate(RequestEngine_OnEngineException);
_requestEngine.OnNewConfigurationRequest += new NewConfigurationRequestDelegate(RequestEngine_OnNewConfigurationRequest);
_requestEngine.OnRequestBlocked += new RequestBlockedDelegate(RequestEngine_OnNewRequest);
_requestEngine.OnRequestComplete += new RequestCompleteDelegate(RequestEngine_OnRequestComplete);
_requestEngine.OnStatusChanged += new EngineStatusChangedDelegate(RequestEngine_OnStatusChanged);
}
break;
default:
returnComponent = _getComponentCallback(type);
if (returnComponent != null)
{
returnComponent.InitializeComponent(this);
}
break;
}
if (returnComponent != null)
{
lock (_buildComponents)
{
_buildComponents.Enqueue(returnComponent);
}
}
return returnComponent;
}
/// <summary>
/// Registers a component factory.
/// </summary>
public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory)
{
}
#endregion
#region Public properties
/// <summary>
/// Node ID
/// </summary>
internal int NodeId
{
get
{
return _nodeId;
}
set
{
_nodeId = value;
}
}
/// <summary>
/// True to log only critical events
/// </summary>
internal bool LogOnlyCriticalEvents
{
get
{
return _logOnlyCriticalEvents;
}
set
{
_logOnlyCriticalEvents = value;
}
}
/// <summary>
/// Number if idle mili seconds to wait before shutting down the build request engine
/// </summary>
internal int EngineShutdownTimeout
{
get
{
return _engineShutdownTimeout;
}
set
{
_engineShutdownTimeout = value;
}
}
/// <summary>
/// Number of initial nodes
/// </summary>
internal int InitialNodeCount
{
get
{
return _initialNodeCount;
}
set
{
_initialNodeCount = value;
}
}
#endregion
#region IBuildComponent Members
/// <summary>
/// Sets the component host. Since we are a host and we do not have a parent host we do not need to do anything here.
/// </summary>
/// <param name="host">The component host</param>
public void InitializeComponent(IBuildComponentHost host)
{
return;
}
/// <summary>
/// Shuts down the component. First shutdown the request engine. Then shutdown the remaining of the component.
/// Check if the test data provider exists before shutting it down as it may not have been registered yet because this is also
/// called in TearDown and teardown is called if an exception is received.
/// </summary>
public void ShutdownComponent()
{
ShutDownRequestEngine();
if (_testDataProvider != null)
{
((IBuildComponent)_testDataProvider).ShutdownComponent();
}
_buildComponents.Clear();
_loggingService = null;
_requestEngine = null;
}
/// <summary>
/// Cancels the current build
/// </summary>
public void AbortBuild()
{
_requestEngine.CleanupForBuild();
}
/// <summary>
/// Wait for the Build request engine to shutdown
/// </summary>
public void ShutDownRequestEngine()
{
if (this.LastEngineStatus != BuildRequestEngineStatus.Shutdown)
{
_requestEngine.CleanupForBuild();
((IBuildComponent)_requestEngine).ShutdownComponent();
WaitForEngineStatus(BuildRequestEngineStatus.Shutdown);
}
}
/// <summary>
/// Waits for the engine status requested. If a status is not changed within a certain amout of time then fail.
/// </summary>
public void WaitForEngineStatus(BuildRequestEngineStatus status)
{
while (this.LastEngineStatus != status)
{
if (_engineStatusChangedEvent.WaitOne(QAMockHost.globalTimeOut, false) == false)
{
Assert.Fail("Requested engine status was not received within - " + QAMockHost.globalTimeOut.ToString() + " seconds.");
}
}
}
#endregion
#region Event Methods
/// <summary>
/// Gets called by the build request engine when the build request engine state changes.
/// Special handeling when a shutdown has been sent so that only shutdown status set the event
/// </summary>
private void RequestEngine_OnStatusChanged(BuildRequestEngineStatus newStatus)
{
this.LastEngineStatus = newStatus;
_engineStatusChangedEvent.Set();
}
/// <summary>
/// Gets called by the build request engine when the build request has been completed
/// </summary>
private void RequestEngine_OnRequestComplete(BuildRequest request, BuildResult result)
{
if (_testDataProvider != null)
{
_testDataProvider.NewResult = new ResultFromEngine(request, result);
}
}
/// <summary>
/// Gets called by the build request engine when there is a new build request (engine callback)
/// </summary>
/// <param name="request"></param>
private void RequestEngine_OnNewRequest(BuildRequestBlocker blocker)
{
if (_testDataProvider != null)
{
foreach (BuildRequest request in blocker.BuildRequests)
{
_testDataProvider.NewRequest = request;
}
}
}
/// <summary>
/// Gets called by the build request engine when the a configuration for a new build request is not present
/// </summary>
/// <param name="config"></param>
private void RequestEngine_OnNewConfigurationRequest(BuildRequestConfiguration config)
{
if (_testDataProvider != null)
{
_testDataProvider.NewConfiguration = config;
}
}
/// <summary>
/// Gets called by the build request engine when the build request engine when there is an exception
/// </summary>
/// <param name="e"></param>
private void RequestEngine_OnEngineException(Exception e)
{
if (_testDataProvider != null)
{
_testDataProvider.EngineException = e;
}
}
private BuildRequestEngineStatus LastEngineStatus
{
get
{
return _lastEngineStatus;
}
set
{
_lastEngineStatus = value;
}
}
#endregion
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RedditSharp.Things;
using System;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using System.Threading.Tasks;
namespace RedditSharp
{
/// <summary>
/// Class to communicate with Reddit.com
/// </summary>
public class Reddit
{
#region Static Variables
static Reddit()
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = WebAgent.RateLimitMode.Pace;
WebAgent.Protocol = "http";
WebAgent.RootDomain = "www.reddit.com";
}
#endregion
internal readonly IWebAgent _webAgent;
/// <summary>
/// Captcha solver instance to use when solving captchas.
/// </summary>
public ICaptchaSolver CaptchaSolver;
/// <summary>
/// The authenticated user for this instance.
/// </summary>
public AuthenticatedUser User { get; set; }
/// <summary>
/// Sets the Rate Limiting Mode of the underlying WebAgent
/// </summary>
public WebAgent.RateLimitMode RateLimit
{
get { return WebAgent.RateLimit; }
set { WebAgent.RateLimit = value; }
}
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
/// Gets the FrontPage using the current Reddit instance.
/// </summary>
public Subreddit FrontPage
{
get { return Subreddit.GetFrontPage(this); }
}
/// <summary>
/// Gets /r/All using the current Reddit instance.
/// </summary>
public Subreddit RSlashAll
{
get { return Subreddit.GetRSlashAll(this); }
}
public Reddit()
: this(true) { }
public Reddit(bool useSsl)
{
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
WebAgent.Protocol = useSsl ? "https" : "http";
_webAgent = new WebAgent();
CaptchaSolver = new ConsoleCaptchaSolver();
}
public Reddit(WebAgent.RateLimitMode limitMode, bool useSsl = true)
: this(useSsl)
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = limitMode;
WebAgent.RootDomain = "www.reddit.com";
}
public Reddit(string username, string password, bool useSsl = true)
: this(useSsl)
{
LogIn(username, password, useSsl);
}
public Reddit(string accessToken)
: this(true)
{
WebAgent.RootDomain = RedditConstants.OAuthDomainUrl;
_webAgent.AccessToken = accessToken;
InitOrUpdateUser();
}
/// <summary>
/// Logs in the current Reddit instance.
/// </summary>
/// <param name="username">The username of the user to log on to.</param>
/// <param name="password">The password of the user to log on to.</param>
/// <param name="useSsl">Whether to use SSL or not. (default: true)</param>
/// <returns></returns>
public AuthenticatedUser LogIn(string username, string password, bool useSsl = true)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
_webAgent.Cookies = new CookieContainer();
HttpWebRequest request;
if (useSsl)
request = _webAgent.CreatePost(RedditConstants.SslLoginUrl);
else
request = _webAgent.CreatePost(RedditConstants.LoginUrl);
var stream = request.GetRequestStream();
if (useSsl)
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json"
});
}
else
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json",
op = "login"
});
}
stream.Close();
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result)["json"];
if (json["errors"].Count() != 0)
throw new AuthenticationException("Incorrect login.");
InitOrUpdateUser();
return User;
}
public RedditUser GetUser(string name)
{
var request = _webAgent.CreateGet(string.Format(RedditConstants.UserInfoUrl, name));
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new RedditUser().Init(this, json, _webAgent);
}
/// <summary>
/// Initializes the User property if it's null,
/// otherwise replaces the existing user object
/// with a new one fetched from reddit servers.
/// </summary>
public void InitOrUpdateUser()
{
var request = _webAgent.CreateGet(string.IsNullOrEmpty(_webAgent.AccessToken) ? RedditConstants.MeUrl : RedditConstants.OAuthMeUrl);
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
User = new AuthenticatedUser().Init(this, json, _webAgent);
}
#region Obsolete Getter Methods
[Obsolete("Use User property instead")]
public AuthenticatedUser GetMe()
{
return User;
}
#endregion Obsolete Getter Methods
public Subreddit GetSubreddit(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
return GetThing<Subreddit>(string.Format(RedditConstants.SubredditAboutUrl, name));
}
/// <summary>
/// Returns the subreddit.
/// </summary>
/// <param name="name">The name of the subreddit</param>
/// <returns>The Subreddit by given name</returns>
public async Task<Subreddit> GetSubredditAsync(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
return await GetThingAsync<Subreddit>(string.Format(RedditConstants.SubredditAboutUrl, name));
}
public Domain GetDomain(string domain)
{
if (!domain.StartsWith("http://") && !domain.StartsWith("https://"))
domain = "http://" + domain;
var uri = new Uri(domain);
return new Domain(this, uri, _webAgent);
}
public JToken GetToken(Uri uri)
{
var url = uri.AbsoluteUri;
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
var request = _webAgent.CreateGet(string.Format(RedditConstants.GetPostUrl, url));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return json[0]["data"]["children"].First;
}
public Post GetPost(Uri uri)
{
return new Post().Init(this, GetToken(uri), _webAgent);
}
public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "")
{
if (User == null)
throw new Exception("User can not be null.");
var request = _webAgent.CreatePost(RedditConstants.ComposeMessageUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
subject,
text = body,
to,
uh = User.Modhash,
iden = captchaId,
captcha = captchaAnswer
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
ICaptchaSolver solver = CaptchaSolver; // Prevent race condition
if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
{
captchaId = json["json"]["captcha"].ToString();
CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));
if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer);
}
}
/// <summary>
/// Registers a new Reddit user
/// </summary>
/// <param name="userName">The username for the new account.</param>
/// <param name="passwd">The password for the new account.</param>
/// <param name="email">The optional recovery email for the new account.</param>
/// <returns>The newly created user account</returns>
public AuthenticatedUser RegisterAccount(string userName, string passwd, string email = "")
{
var request = _webAgent.CreatePost(RedditConstants.RegisterAccountUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
email = email,
passwd = passwd,
passwd2 = passwd,
user = userName
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new AuthenticatedUser().Init(this, json, _webAgent);
// TODO: Error
}
public Thing GetThingByFullname(string fullname)
{
var request = _webAgent.CreateGet(string.Format(RedditConstants.GetThingUrl, fullname));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json["data"]["children"][0], _webAgent);
}
public Comment GetComment(string subreddit, string name, string linkName)
{
try
{
if (linkName.StartsWith("t3_"))
linkName = linkName.Substring(3);
if (name.StartsWith("t1_"))
name = name.Substring(3);
var url = string.Format(RedditConstants.GetCommentUrl, subreddit, linkName, name);
return GetComment(new Uri(url));
}
catch (WebException)
{
return null;
}
}
public Comment GetComment(Uri uri)
{
var url = string.Format(RedditConstants.GetPostUrl, uri.AbsoluteUri);
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var sender = new Post().Init(this, json[0]["data"]["children"][0], _webAgent);
return new Comment().Init(this, json[1]["data"]["children"][0], _webAgent, sender);
}
public Listing<T> SearchByUrl<T>(string url) where T : Thing
{
var urlSearchQuery = string.Format(RedditConstants.UrlSearchPattern, url);
return Search<T>(urlSearchQuery);
}
public Listing<T> Search<T>(string query, Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing
{
string sort = sortE.ToString().ToLower();
string time = timeE.ToString().ToLower();
return new Listing<T>(this, string.Format(RedditConstants.SearchUrl, query, sort, time), _webAgent);
}
#region Helpers
protected async internal Task<T> GetThingAsync<T>(string url) where T : Thing
{
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var ret = await Thing.ParseAsync(this, json, _webAgent);
return (T)ret;
}
protected internal T GetThing<T>(string url) where T : Thing
{
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return (T)Thing.Parse(this, json, _webAgent);
}
#endregion
}
}
| |
//
// how to capture still images, video and audio using iOS AVFoundation and the AVCAptureSession
//
// This sample handles all of the low-level AVFoundation and capture graph setup required to capture and save media. This code also exposes the
// capture, configuration and notification capabilities in a more '.Netish' way of programming. The client code will not need to deal with threads, delegate classes
// buffer management, or objective-C data types but instead will create .NET objects and handle standard .NET events. The underlying iOS concepts and classes are detailed in
// the iOS developer online help (TP40010188-CH5-SW2).
//
// https://developer.apple.com/library/mac/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW2
//
// Enhancements, suggestions and bug reports can be sent to steve.millar@infinitekdev.com
//
using System;
using System.Collections.Concurrent;
using System.Drawing;
using System.IO;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AVFoundation;
using MonoTouch.CoreVideo;
using MonoTouch.CoreMedia;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreFoundation;
using System.Runtime.InteropServices;
namespace MediaCapture
{
public class CaptureManager
{
// capture session
private AVCaptureSession session = null;
private bool isCapturing = false;
private bool captureImages = false;
private bool captureAudio = false;
private bool captureVideo = false;
private string movieRecordingDirectory;
private CameraType cameraType = CameraType.RearFacing;
private Resolution resolution = Resolution.Medium;
// camera input objects
private AVCaptureDevice videoCaptureDevice = null;
private AVCaptureDeviceInput videoInput = null;
// microphone input objects
private AVCaptureDevice audioCaptureDevice = null;
private AVCaptureDeviceInput audioInput = null;
// frame grabber objects
private AVCaptureVideoDataOutput frameGrabberOutput = null;
private VideoFrameSamplerDelegate videoFrameSampler = null;
private DispatchQueue queue = null;
// movie recorder objects
private AVCaptureMovieFileOutput movieFileOutput = null;
private MovieSegmentWriterDelegate movieSegmentWriter = null;
private string currentSegmentFile = null;
private DateTime currentSegmentStartedAt;
private uint nextMovieIndex = 1;
private int movieSegmentDurationInMilliSeconds = 20000;
private bool breakMovieIntoSegments = true;
private CaptureManager(){}
public CaptureManager(
Resolution resolution,
bool captureImages,
bool captureAudio,
bool captureVideo,
CameraType cameraType,
string movieRecordingDirectory,
int movieSegmentDurationInMilliSeconds,
bool breakMovieIntoSegments )
{
this.resolution = resolution;
this.captureImages = captureImages;
this.captureAudio = captureAudio;
this.captureVideo = captureVideo;
this.cameraType = cameraType;
this.movieSegmentDurationInMilliSeconds = movieSegmentDurationInMilliSeconds;
this.breakMovieIntoSegments = breakMovieIntoSegments;
if ( captureAudio || captureVideo )
{
this.movieRecordingDirectory = Path.Combine( movieRecordingDirectory, getDateTimeDirectoryName( DateTime.Now ) );
if ( Directory.Exists( this.movieRecordingDirectory ) == false )
{
Directory.CreateDirectory( this.movieRecordingDirectory );
}
}
}
#region events
public EventHandler<MovieSegmentCapturedEventArgs> MovieSegmentCaptured;
private void onMovieSegmentCaptured( MovieSegmentCapturedEventArgs args )
{
if ( MovieSegmentCaptured != null )
{
MovieSegmentCaptured( this, args );
}
}
public EventHandler<CaptureErrorEventArgs> CaptureError;
private void onCaptureError( CaptureErrorEventArgs args )
{
if ( CaptureError != null )
{
CaptureError( this, args );
}
}
public EventHandler<ImageCaptureEventArgs> ImageCaptured;
private void onImageCaptured( ImageCaptureEventArgs args )
{
if ( ImageCaptured != null )
{
ImageCaptured( this, args );
}
}
#endregion
public int MovieSegmentDurationInMilliSeconds
{
get
{
return movieSegmentDurationInMilliSeconds;
}
}
public bool IsCapturing
{
get
{
return this.isCapturing;
}
set
{
isCapturing = value;
}
}
private bool shouldRecord
{
get
{
return ( ( this.captureAudio || this.captureVideo ) && ( string.IsNullOrEmpty(this.movieRecordingDirectory) == false ) );
}
}
public bool StartCapture( out string message )
{
message = "";
if ( isCapturing == true )
{
message = "already capturing";
return true;
}
isCapturing = true;
if ( setupCaptureSessionInternal( out message ) == false )
{
return false;
}
// start the capture
session.StartRunning();
// start recording (if configured)
if ( shouldRecord )
{
startMovieWriter();
}
return true;
}
public void StopCapture()
{
if ( isCapturing == false )
{
return;
}
isCapturing = false;
// stop recording
if ( shouldRecord )
{
stopMovieWriter();
}
// stop the capture session
session.StopRunning();
unsubscribeDelegateEvents();
}
private void startMovieWriter()
{
if ( movieFileOutput == null )
{
return;
}
startRecordingNextMovieFilename();
}
private void startRecordingNextMovieFilename()
{
// generate file name
currentSegmentFile = System.IO.Path.Combine( this.movieRecordingDirectory, string.Format("video_{0}.mov", nextMovieIndex++) );
NSUrl segmentUrl = NSUrl.FromFilename( currentSegmentFile );
// start recording
movieFileOutput.StartRecordingToOutputFile( segmentUrl, movieSegmentWriter);
}
private void stopMovieWriter()
{
if ( movieFileOutput == null )
{
return;
}
movieFileOutput.StopRecording();
}
private bool setupCaptureSessionInternal( out string errorMessage )
{
errorMessage = "";
// create the capture session
session = new AVCaptureSession();
switch ( resolution )
{
case Resolution.Low:
session.SessionPreset = AVCaptureSession.PresetLow;
break;
case Resolution.High:
session.SessionPreset = AVCaptureSession.PresetHigh;
break;
case Resolution.Medium:
default:
session.SessionPreset = AVCaptureSession.PresetMedium;
break;
}
// conditionally configure the camera input
if ( captureVideo || captureImages)
{
if ( addCameraInput( out errorMessage ) == false )
{
return false;
}
}
// conditionally configure the microphone input
if ( captureAudio )
{
if ( addAudioInput( out errorMessage ) == false )
{
return false;
}
}
// conditionally configure the sample buffer output
if ( captureImages )
{
int minimumSampleIntervalInMilliSeconds = captureVideo ? 1000 : 100;
if ( addImageSamplerOutput( out errorMessage, minimumSampleIntervalInMilliSeconds ) == false )
{
return false;
}
}
// conditionally configure the movie file output
if ( shouldRecord )
{
if ( addMovieFileOutput( out errorMessage ) == false )
{
return false;
}
}
return true;
}
private bool addCameraInput( out string errorMessage )
{
errorMessage = "";
videoCaptureDevice = this.cameraType == CameraType.FrontFacing ? MediaDevices.FrontCamera : MediaDevices.BackCamera;
videoInput = AVCaptureDeviceInput.FromDevice(videoCaptureDevice);
if (videoInput == null)
{
errorMessage = "No video capture device";
return false;
}
session.AddInput (videoInput);
return true;
}
private bool addAudioInput( out string errorMessage )
{
errorMessage = "";
audioCaptureDevice = MediaDevices.Microphone;
audioInput = AVCaptureDeviceInput.FromDevice(audioCaptureDevice);
if (audioInput == null)
{
errorMessage = "No audio capture device";
return false;
}
session.AddInput (audioInput);
return true;
}
private bool addMovieFileOutput( out string errorMessage )
{
errorMessage = "";
// create a movie file output and add it to the capture session
movieFileOutput = new AVCaptureMovieFileOutput();
if ( movieSegmentDurationInMilliSeconds > 0 )
{
movieFileOutput.MaxRecordedDuration = new CMTime( movieSegmentDurationInMilliSeconds, 1000 );
}
// setup the delegate that handles the writing
movieSegmentWriter = new MovieSegmentWriterDelegate();
// subscribe to the delegate events
movieSegmentWriter.MovieSegmentRecordingStarted += new EventHandler<MovieSegmentRecordingStartedEventArgs>( handleMovieSegmentRecordingStarted );
movieSegmentWriter.MovieSegmentRecordingComplete += new EventHandler<MovieSegmentRecordingCompleteEventArgs>( handleMovieSegmentRecordingComplete );
movieSegmentWriter.CaptureError += new EventHandler<CaptureErrorEventArgs>( handleMovieCaptureError );
session.AddOutput (movieFileOutput);
return true;
}
private bool addImageSamplerOutput( out string errorMessage, int minimumSampleIntervalInMilliSeconds )
{
errorMessage = "";
// create a VideoDataOutput and add it to the capture session
frameGrabberOutput = new AVCaptureVideoDataOutput();
frameGrabberOutput.VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA);
// set up the output queue and delegate
queue = new MonoTouch.CoreFoundation.DispatchQueue ("captureQueue");
videoFrameSampler = new VideoFrameSamplerDelegate();
frameGrabberOutput.SetSampleBufferDelegateAndQueue (videoFrameSampler, queue);
// subscribe to from capture events
videoFrameSampler.CaptureError += new EventHandler<CaptureErrorEventArgs>( handleImageCaptureError );
videoFrameSampler.ImageCaptured += new EventHandler<ImageCaptureEventArgs>( handleImageCaptured );
// add the output to the session
session.AddOutput (frameGrabberOutput);
// set minimum time interval between image samples (if possible).
try
{
AVCaptureConnection connection = (AVCaptureConnection)frameGrabberOutput.Connections[0];
connection.VideoMinFrameDuration = new CMTime(minimumSampleIntervalInMilliSeconds, 1000);
}
catch
{
}
return true;
}
private void handleMovieSegmentRecordingStarted( object sender, MovieSegmentRecordingStartedEventArgs args )
{
currentSegmentStartedAt = DateTime.Now;
}
#region event handlers
private void handleMovieSegmentRecordingComplete(object sender, MovieSegmentRecordingCompleteEventArgs args )
{
try
{
// grab the pertinent event data
MovieSegmentCapturedEventArgs captureInfo = new MovieSegmentCapturedEventArgs();
captureInfo.StartedAt = currentSegmentStartedAt;
captureInfo.DurationMilliSeconds = movieSegmentDurationInMilliSeconds;
captureInfo.File = args.Path;
// conditionally start recording the next segment
if ( args.ErrorOccured == false && breakMovieIntoSegments && isCapturing)
{
startRecordingNextMovieFilename();
}
// raise the capture event to external listeners
onMovieSegmentCaptured( captureInfo );
}
catch
{
}
}
private void handleMovieCaptureError(object sender, CaptureErrorEventArgs args )
{
// bubble up
onCaptureError( args );
}
private void handleImageCaptured( object sender, ImageCaptureEventArgs args)
{
// bubble up
onImageCaptured( args);
}
private void handleImageCaptureError( object sender, CaptureErrorEventArgs args )
{
// bubble up
onCaptureError( args );
}
#endregion
private void unsubscribeDelegateEvents()
{
try
{
if ( videoFrameSampler != null )
{
videoFrameSampler.CaptureError -= new EventHandler<CaptureErrorEventArgs>( handleImageCaptureError );
videoFrameSampler.ImageCaptured -= new EventHandler<ImageCaptureEventArgs>( handleImageCaptured );
}
if ( movieSegmentWriter != null )
{
movieSegmentWriter.MovieSegmentRecordingStarted -= new EventHandler<MovieSegmentRecordingStartedEventArgs>( handleMovieSegmentRecordingStarted );
movieSegmentWriter.MovieSegmentRecordingComplete -= new EventHandler<MovieSegmentRecordingCompleteEventArgs>( handleMovieSegmentRecordingComplete );
movieSegmentWriter.CaptureError -= new EventHandler<CaptureErrorEventArgs>( handleMovieCaptureError );
}
}
catch
{
}
}
private string getDateTimeDirectoryName( DateTime dateTime )
{
return dateTime.ToString().Replace(":","-").Replace ("/","-").Replace (" ","-").Replace ("\\","-");
}
}
public enum Resolution
{
Low,
Medium,
High
}
public enum CameraType
{
FrontFacing,
RearFacing
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using Lighthouse.Common.Interoperability;
using Lighthouse.Common.Ioc;
using Lighthouse.Common.Services;
using Lighthouse.Common.SilverlightUnitTestingAbstractions;
using Lighthouse.Silverlight.Core.Controls;
using Lighthouse.Silverlight.Core.SilverlightUnitTestingCustomizations;
using Microsoft.Silverlight.Testing;
using Microsoft.Silverlight.Testing.Harness;
using System.Linq;
namespace Lighthouse.Silverlight.Core.Services
{
[ScriptableType]
public class RemoteUnitTestingApplicationService : IApplicationService, IApplicationLifetimeAware
{
private LighthouseUnitTestRunnerPage _testPage;
private static RemoteUnitTestingApplicationService _current;
public static RemoteUnitTestingApplicationService Current
{
get { return _current; }
}
private ISerializationService _serializationService;
private ISilverlightUnitTestAbstractionsFactory _silverlightUnitTestAbstractionsFactory;
public RemoteUnitTestingApplicationService()
{
_silverlightUnitTestAbstractionsFactory =
SimpleServiceLocator.Instance.Get<ISilverlightUnitTestAbstractionsFactory>();
_serializationService = SimpleServiceLocator.Instance.Get<ISerializationService>();
}
public RemoteUnitTestingApplicationService(ISerializationService serializationService, ISilverlightUnitTestAbstractionsFactory silverlightUnitTestAbstractionsFactory)
{
_serializationService = serializationService;
_silverlightUnitTestAbstractionsFactory = silverlightUnitTestAbstractionsFactory;
}
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; }
}
public void StartService(ApplicationServiceContext context)
{
_serializationService = new SerializationService();
_silverlightUnitTestAbstractionsFactory = new SilverlightUnitTestAbstractionsFactory();
_current = this;
if (IsEnabled)
{
HtmlPage.RegisterScriptableObject("TestFrontend", this);
var waitingPage = new WaitingPage();
waitingPage.Loaded += (s, e) => InvokeExternalMethod("ReadyToStart");
Application.Current.RootVisual = waitingPage;
}
}
public void Run(SilverlightUnitTestRunSettings settings)
{
UnitTestSettings unitTestSettings = MyUnitTestSystem.CreateDefaultSettings(settings);
_testPage = MyUnitTestSystem.CreateTestPage(unitTestSettings) as LighthouseUnitTestRunnerPage;
if (_testPage != null)
{
var userControl = Application.Current.RootVisual as UserControl;
if (userControl != null)
{
userControl.Content = _testPage;
userControl.Focus();
try
{
_testPage.StartTesting();
}
catch (Exception e)
{
ReportError(e);
PublishResultsWithError(e);
}
}
else
{
ReportError(new Exception("Could not assign new RootVisual"));
}
}
}
public void Run()
{
Run(new SilverlightUnitTestRunSettings()
{
AssembliesThatContainTests = new List<string>() { "Lighthouse.Silverlight4.SampleXapWithTests.dll" }
});
}
[ScriptableMember]
public void RemoteRun(string settings)
{
var materializedSettings = new SilverlightUnitTestRunSettings();
try
{
materializedSettings = _serializationService.Deserialize<SilverlightUnitTestRunSettings>(settings);
}
catch (Exception)
{
}
Run(materializedSettings);
}
private bool InvokeExternalMethod(string name)
{
return InvokeExternalMethod(name, new object[] {});
}
private bool InvokeExternalMethod(string name, object[] parameters)
{
var testResultsInformer = HtmlPage.Window.Eval("window.external") as ScriptObject;
if (testResultsInformer != null)
{
try
{
testResultsInformer.Invoke(name, parameters);
return true;
}
catch (Exception)
{
return false;
}
}
return false;
}
private bool InvokeExternalMethod(string name, string parameters)
{
return InvokeExternalMethod(name, new object[] {parameters});
}
public void OnTestRunStarting(object sender, TestRunStartingEventArgs testRunStartingEventArgs)
{
var args = new LighthouseUnitTestRunStartInformation()
{
TotalNumberOfAssemblies = testRunStartingEventArgs.EnqueuedAssemblies,
TotalNumberOfMethods = testRunStartingEventArgs.Settings.TestHarness.TestMethodCount
};
var serializedResult = _serializationService.Serialize(args);
InvokeExternalMethod("TestsStarted", serializedResult);
}
public void ReportThatWeStartedExecutingTests(string count)
{
InvokeExternalMethod("TestsStarted", count);
}
public void OnTestClassStarting(object sender, TestClassStartingEventArgs e)
{
}
public void OnTestClassCompleted(object sender, TestClassCompletedEventArgs e)
{
}
public void OnTestMethodStarting(object sender, TestMethodStartingEventArgs e)
{
var result = new TestMethodDetailedInformation()
{
Class = _silverlightUnitTestAbstractionsFactory.Convert(e.TestClass),
Method = _silverlightUnitTestAbstractionsFactory.Convert(e.TestMethod)
};
var serializedResult = _serializationService.Serialize(result);
InvokeExternalMethod("TestMethodStarting", serializedResult);
}
public void OnTestMethodCompleted(object sender, TestMethodCompletedEventArgs e)
{
var convertedResult = _silverlightUnitTestAbstractionsFactory.Convert(e.Result);
var serializedResult = _serializationService.Serialize(convertedResult);
InvokeExternalMethod("TestMethodCompleted", serializedResult);
}
public void PublishResults(List<ScenarioResult> results)
{
var convertedResult = _silverlightUnitTestAbstractionsFactory.Convert(results);
var serializedResult = _serializationService.Serialize(convertedResult);
InvokeExternalMethod("TestsFinished", serializedResult);
}
public void PublishResultsWithError(Exception error)
{
var errorInfo = _silverlightUnitTestAbstractionsFactory.Convert(error);
var results = new ComposedUnitTestOutcome() {Errors = new List<IUnitTestException>() {errorInfo}};
var serializedResult = _serializationService.Serialize(results);
InvokeExternalMethod("TestsFinished", serializedResult);
}
public void StopService()
{
}
public void Starting()
{
}
public void Started()
{
}
public void Exiting()
{
}
public void Exited()
{
}
public void SendLogMessageToRemoteTestExecutor(string message)
{
InvokeExternalMethod("LogMessageSent", message);
}
public void ReportError(Exception exception)
{
var convertedException = _silverlightUnitTestAbstractionsFactory.Convert(exception);
var serializedException = _serializationService.Serialize(convertedException);
InvokeExternalMethod("ErrorOccured", serializedException);
}
public void TestAssemblyStarting(object sender, TestAssemblyStartingEventArgs e)
{
var convertedData = _silverlightUnitTestAbstractionsFactory.Convert(e.Assembly);
var serializedData = _serializationService.Serialize(convertedData);
InvokeExternalMethod("TestsAssemblyStarting", serializedData);
}
public void TestAssemblyCompleted(object sender, TestAssemblyCompletedEventArgs e)
{
var convertedData = _silverlightUnitTestAbstractionsFactory.Convert(e.Assembly);
var serializedData = _serializationService.Serialize(convertedData);
InvokeExternalMethod("TestsAssemblyCompleted", serializedData);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Framework.Threading;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Gameplay.Components;
using osu.Game.Tournament.Screens.MapPool;
using osu.Game.Tournament.Screens.TeamWin;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Gameplay
{
public class GameplayScreen : BeatmapInfoScreen, IProvideVideo
{
private readonly BindableBool warmup = new BindableBool();
private readonly Bindable<TournamentMatch> currentMatch = new Bindable<TournamentMatch>();
public readonly Bindable<TourneyState> State = new Bindable<TourneyState>();
private OsuButton warmupButton;
private MatchIPCInfo ipc;
[Resolved(canBeNull: true)]
private TournamentSceneManager sceneManager { get; set; }
[Resolved]
private TournamentMatchChatDisplay chat { get; set; }
private Box chroma;
[BackgroundDependencyLoader]
private void load(LadderInfo ladder, MatchIPCInfo ipc, Storage storage)
{
this.ipc = ipc;
AddRangeInternal(new Drawable[]
{
new TourneyVideo("gameplay")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
header = new MatchHeader
{
ShowLogo = false
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Y = 110,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Children = new Drawable[]
{
chroma = new Box
{
// chroma key area for stable gameplay
Name = "chroma",
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Height = 512,
Colour = new Color4(0, 255, 0, 255),
},
}
},
scoreDisplay = new MatchScoreDisplay
{
Y = -147,
Anchor = Anchor.BottomCentre,
Origin = Anchor.TopCentre,
},
new ControlPanel
{
Children = new Drawable[]
{
warmupButton = new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle warmup",
Action = () => warmup.Toggle()
},
new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle chat",
Action = () => { State.Value = State.Value == TourneyState.Idle ? TourneyState.Playing : TourneyState.Idle; }
},
new SettingsSlider<int>
{
LabelText = "Chroma Width",
Bindable = LadderInfo.ChromaKeyWidth,
KeyboardStep = 1,
}
}
}
});
State.BindTo(ipc.State);
State.BindValueChanged(stateChanged, true);
ladder.ChromaKeyWidth.BindValueChanged(width => chroma.Width = width.NewValue, true);
currentMatch.BindValueChanged(m =>
{
warmup.Value = m.NewValue.Team1Score.Value + m.NewValue.Team2Score.Value == 0;
scheduledOperation?.Cancel();
});
currentMatch.BindTo(ladder.CurrentMatch);
warmup.BindValueChanged(w =>
{
warmupButton.Alpha = !w.NewValue ? 0.5f : 1;
header.ShowScores = !w.NewValue;
}, true);
}
private ScheduledDelegate scheduledOperation;
private MatchScoreDisplay scoreDisplay;
private TourneyState lastState;
private MatchHeader header;
private void stateChanged(ValueChangedEvent<TourneyState> state)
{
try
{
if (state.NewValue == TourneyState.Ranking)
{
if (warmup.Value) return;
if (ipc.Score1.Value > ipc.Score2.Value)
currentMatch.Value.Team1Score.Value++;
else
currentMatch.Value.Team2Score.Value++;
}
scheduledOperation?.Cancel();
void expand()
{
chat?.Contract();
using (BeginDelayedSequence(300, true))
{
scoreDisplay.FadeIn(100);
SongBar.Expanded = true;
}
}
void contract()
{
SongBar.Expanded = false;
scoreDisplay.FadeOut(100);
using (chat?.BeginDelayedSequence(500))
chat?.Expand();
}
switch (state.NewValue)
{
case TourneyState.Idle:
contract();
const float delay_before_progression = 4000;
// if we've returned to idle and the last screen was ranking
// we should automatically proceed after a short delay
if (lastState == TourneyState.Ranking && !warmup.Value)
{
if (currentMatch.Value?.Completed.Value == true)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(TeamWinScreen)); }, delay_before_progression);
else if (currentMatch.Value?.Completed.Value == false)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(MapPoolScreen)); }, delay_before_progression);
}
break;
case TourneyState.Ranking:
scheduledOperation = Scheduler.AddDelayed(contract, 10000);
break;
default:
chat.Contract();
expand();
break;
}
}
finally
{
lastState = state.NewValue;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
public class TextureEditor
{
public enum Mode
{
None,
Texture,
Anchor,
Collider
}
int textureBorderPixels = 16;
Mode mode = Mode.Texture;
Vector2 textureScrollPos = new Vector2(0.0f, 0.0f);
bool drawColliderNormals = false;
float editorDisplayScale
{
get { return SpriteCollection.editorDisplayScale; }
set { SpriteCollection.editorDisplayScale = value; }
}
Color[] _handleInactiveColors = new Color[] {
new Color32(127, 201, 122, 255), // default
new Color32(180, 0, 0, 255), // red
new Color32(255, 255, 255, 255), // white
new Color32(32, 32, 32, 255), // black
};
Color[] _handleActiveColors = new Color[] {
new Color32(228, 226, 60, 255),
new Color32(255, 0, 0, 255),
new Color32(255, 0, 0, 255),
new Color32(96, 0, 0, 255),
};
tk2dSpriteCollectionDefinition.ColliderColor currentColliderColor = tk2dSpriteCollectionDefinition.ColliderColor.Default;
Color handleInactiveColor { get { return _handleInactiveColors[(int)currentColliderColor]; } }
Color handleActiveColor { get { return _handleActiveColors[(int)currentColliderColor]; } }
IEditorHost host;
public TextureEditor(IEditorHost host)
{
this.host = host;
}
SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } }
public void SetMode(Mode mode)
{
if (this.mode != mode)
{
this.mode = mode;
HandleUtility.Repaint();
}
}
Vector2 ClosestPointOnLine(Vector2 p, Vector2 p1, Vector2 p2)
{
float magSq = (p2 - p1).sqrMagnitude;
if (magSq < float.Epsilon)
return p1;
float u = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / magSq;
if (u < 0.0f || u > 1.0f)
return p1;
return p1 + (p2 - p1) * u;
}
void DrawPolygonColliderEditor(Rect r, ref tk2dSpriteColliderIsland[] islands, Texture2D tex, bool forceClosed)
{
Vector2 origin = new Vector2(r.x, r.y);
Vector3 origin3 = new Vector3(r.x, r.y, 0);
// Sanitize
if (islands == null || islands.Length == 0 ||
!islands[0].IsValid())
{
islands = new tk2dSpriteColliderIsland[1];
islands[0] = new tk2dSpriteColliderIsland();
islands[0].connected = true;
int w = tex.width;
int h = tex.height;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(0, 0);
p[1] = new Vector2(0, h);
p[2] = new Vector2(w, h);
p[3] = new Vector2(w, 0);
islands[0].points = p;
}
Color previousHandleColor = Handles.color;
bool insertPoint = false;
if (Event.current.clickCount == 2 && Event.current.type == EventType.MouseDown)
{
insertPoint = true;
Event.current.Use();
}
if (r.Contains(Event.current.mousePosition) && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.C)
{
Vector2 min = Event.current.mousePosition / editorDisplayScale - new Vector2(16.0f, 16.0f);
Vector3 max = Event.current.mousePosition / editorDisplayScale + new Vector2(16.0f, 16.0f);
min.x = Mathf.Clamp(min.x, 0, tex.width * editorDisplayScale);
min.y = Mathf.Clamp(min.y, 0, tex.height * editorDisplayScale);
max.x = Mathf.Clamp(max.x, 0, tex.width * editorDisplayScale);
max.y = Mathf.Clamp(max.y, 0, tex.height * editorDisplayScale);
tk2dSpriteColliderIsland island = new tk2dSpriteColliderIsland();
island.connected = true;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(min.x, min.y);
p[1] = new Vector2(min.x, max.y);
p[2] = new Vector2(max.x, max.y);
p[3] = new Vector2(max.x, min.y);
island.points = p;
System.Array.Resize(ref islands, islands.Length + 1);
islands[islands.Length - 1] = island;
Event.current.Use();
}
// Draw outline lines
int deletedIsland = -1;
for (int islandId = 0; islandId < islands.Length; ++islandId)
{
float closestDistanceSq = 1.0e32f;
Vector2 closestPoint = Vector2.zero;
int closestPreviousPoint = 0;
var island = islands[islandId];
Handles.color = handleInactiveColor;
Vector2 ov = (island.points.Length>0)?island.points[island.points.Length-1]:Vector2.zero;
for (int i = 0; i < island.points.Length; ++i)
{
Vector2 v = island.points[i];
// Don't draw last connection if its not connected
if (!island.connected && i == 0)
{
ov = v;
continue;
}
if (insertPoint)
{
Vector2 localMousePosition = (Event.current.mousePosition - origin) / editorDisplayScale;
Vector2 closestPointToCursor = ClosestPointOnLine(localMousePosition, ov, v);
float lengthSq = (closestPointToCursor - localMousePosition).sqrMagnitude;
if (lengthSq < closestDistanceSq)
{
closestDistanceSq = lengthSq;
closestPoint = closestPointToCursor;
closestPreviousPoint = i;
}
}
if (drawColliderNormals)
{
Vector2 l = (ov - v).normalized;
Vector2 n = new Vector2(l.y, -l.x);
Vector2 c = (v + ov) * 0.5f * editorDisplayScale + origin;
Handles.DrawLine(c, c + n * 16.0f);
}
Handles.DrawLine(v * editorDisplayScale + origin, ov * editorDisplayScale + origin);
ov = v;
}
Handles.color = previousHandleColor;
if (insertPoint && closestDistanceSq < 16.0f)
{
var tmpList = new List<Vector2>(island.points);
tmpList.Insert(closestPreviousPoint, closestPoint);
island.points = tmpList.ToArray();
HandleUtility.Repaint();
}
int deletedIndex = -1;
bool flipIsland = false;
bool disconnectIsland = false;
for (int i = 0; i < island.points.Length; ++i)
{
Vector3 cp = island.points[i];
KeyCode keyCode = KeyCode.None;
int id = 16433 + i;
cp = (tk2dGuiUtility.PositionHandle(id, cp * editorDisplayScale + origin3, 4.0f, handleInactiveColor, handleActiveColor, out keyCode) - origin) / editorDisplayScale;
if (keyCode == KeyCode.Backspace || keyCode == KeyCode.Delete)
{
deletedIndex = i;
}
if (keyCode == KeyCode.X)
{
deletedIsland = islandId;
}
if (keyCode == KeyCode.T && !forceClosed)
{
disconnectIsland = true;
}
if (keyCode == KeyCode.F)
{
flipIsland = true;
}
cp.x = Mathf.Round(cp.x);
cp.y = Mathf.Round(cp.y);
// constrain
cp.x = Mathf.Clamp(cp.x, 0.0f, tex.width);
cp.y = Mathf.Clamp(cp.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(cp.x, cp.y));
island.points[i] = cp;
}
if (flipIsland)
{
System.Array.Reverse(island.points);
}
if (disconnectIsland)
{
island.connected = !island.connected;
if (island.connected && island.points.Length < 3)
{
Vector2 pp = (island.points[1] - island.points[0]);
float l = pp.magnitude;
pp.Normalize();
Vector2 nn = new Vector2(pp.y, -pp.x);
nn.y = Mathf.Clamp(nn.y, 0, tex.height);
nn.x = Mathf.Clamp(nn.x, 0, tex.width);
System.Array.Resize(ref island.points, island.points.Length + 1);
island.points[island.points.Length - 1] = (island.points[0] + island.points[1]) * 0.5f + nn * l * 0.5f;
}
}
if (deletedIndex != -1 &&
((island.connected && island.points.Length > 3) ||
(!island.connected && island.points.Length > 2)) )
{
var tmpList = new List<Vector2>(island.points);
tmpList.RemoveAt(deletedIndex);
island.points = tmpList.ToArray();
}
}
// Can't delete the last island
if (deletedIsland != -1 && islands.Length > 1)
{
var tmpIslands = new List<tk2dSpriteColliderIsland>(islands);
tmpIslands.RemoveAt(deletedIsland);
islands = tmpIslands.ToArray();
}
}
void DrawCustomBoxColliderEditor(Rect r, tk2dSpriteCollectionDefinition param, Texture2D tex)
{
Vector2 origin = new Vector2(r.x, r.y);
// sanitize
if (param.boxColliderMin == Vector2.zero && param.boxColliderMax == Vector2.zero)
{
param.boxColliderMax = new Vector2(tex.width, tex.height);
}
Vector3[] pt = new Vector3[] {
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
};
Color32 transparentColor = handleInactiveColor;
transparentColor.a = 10;
Handles.DrawSolidRectangleWithOutline(pt, transparentColor, handleInactiveColor);
// Draw grab handles
Vector3 handlePos;
int id = 16433;
// Draw top handle
handlePos = (pt[0] + pt[1]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 0, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMin.y = handlePos.y;
if (param.boxColliderMin.y > param.boxColliderMax.y) param.boxColliderMin.y = param.boxColliderMax.y;
// Draw bottom handle
handlePos = (pt[2] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 1, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMax.y = handlePos.y;
if (param.boxColliderMax.y < param.boxColliderMin.y) param.boxColliderMax.y = param.boxColliderMin.y;
// Draw left handle
handlePos = (pt[0] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 2, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMin.x = handlePos.x;
if (param.boxColliderMin.x > param.boxColliderMax.x) param.boxColliderMin.x = param.boxColliderMax.x;
// Draw right handle
handlePos = (pt[1] + pt[2]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 3, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMax.x = handlePos.x;
if (param.boxColliderMax.x < param.boxColliderMin.x) param.boxColliderMax.x = param.boxColliderMin.x;
param.boxColliderMax.x = Mathf.Round(param.boxColliderMax.x);
param.boxColliderMax.y = Mathf.Round(param.boxColliderMax.y);
param.boxColliderMin.x = Mathf.Round(param.boxColliderMin.x);
param.boxColliderMin.y = Mathf.Round(param.boxColliderMin.y);
// constrain
param.boxColliderMax.x = Mathf.Clamp(param.boxColliderMax.x, 0.0f, tex.width);
param.boxColliderMax.y = Mathf.Clamp(param.boxColliderMax.y, 0.0f, tex.height);
param.boxColliderMin.x = Mathf.Clamp(param.boxColliderMin.x, 0.0f, tex.width);
param.boxColliderMin.y = Mathf.Clamp(param.boxColliderMin.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id + 0, new Vector2(0, param.boxColliderMin.y));
tk2dGuiUtility.SetPositionHandleValue(id + 1, new Vector2(0, param.boxColliderMax.y));
tk2dGuiUtility.SetPositionHandleValue(id + 2, new Vector2(param.boxColliderMin.x, 0));
tk2dGuiUtility.SetPositionHandleValue(id + 3, new Vector2(param.boxColliderMax.x, 0));
}
void HandleKeys()
{
Event evt = Event.current;
if (evt.type == EventType.KeyUp && evt.shift)
{
Mode newMode = Mode.None;
switch (evt.keyCode)
{
case KeyCode.Q: newMode = Mode.Texture; break;
case KeyCode.W: newMode = Mode.Anchor; break;
case KeyCode.E: newMode = Mode.Collider; break;
case KeyCode.N: drawColliderNormals = !drawColliderNormals; HandleUtility.Repaint(); break;
}
if (newMode != Mode.None)
{
mode = newMode;
evt.Use();
}
}
}
public void DrawTextureView(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
HandleKeys();
if (mode == Mode.None)
mode = Mode.Texture;
// sanity check
if (editorDisplayScale <= 1.0f) editorDisplayScale = 1.0f;
// mirror data
currentColliderColor = param.colliderColor;
GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
if (texture == null)
{
// Get somewhere to put the texture...
GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
}
else
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom);
if (mode == Mode.Anchor && !allowAnchor) mode = Mode.Texture;
if (mode == Mode.Collider && !allowCollider) mode = Mode.Texture;
Rect rect = GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
tk2dGrid.Draw(rect);
// middle mouse drag and scroll zoom
if (rect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseDrag && Event.current.button == 2)
{
textureScrollPos -= Event.current.delta * editorDisplayScale;
Event.current.Use();
HandleUtility.Repaint();
}
if (Event.current.type == EventType.ScrollWheel)
{
editorDisplayScale -= Event.current.delta.y * 0.03f;
Event.current.Use();
HandleUtility.Repaint();
}
}
bool alphaBlend = true;
textureScrollPos = GUI.BeginScrollView(rect, textureScrollPos,
new Rect(0, 0, textureBorderPixels * 2 + (texture.width) * editorDisplayScale, textureBorderPixels * 2 + (texture.height) * editorDisplayScale));
Rect textureRect = new Rect(textureBorderPixels, textureBorderPixels, texture.width * editorDisplayScale, texture.height * editorDisplayScale);
texture.filterMode = FilterMode.Point;
GUI.DrawTexture(textureRect, texture, ScaleMode.ScaleAndCrop, alphaBlend);
if (mode == Mode.Collider)
{
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom)
DrawCustomBoxColliderEditor(textureRect, param, texture);
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
DrawPolygonColliderEditor(textureRect, ref param.polyColliderIslands, texture, false);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
DrawPolygonColliderEditor(textureRect, ref param.geometryIslands, texture, true);
}
// Anchor
if (mode == Mode.Anchor)
{
Color handleColor = new Color(0,0,0,0.2f);
Color lineColor = Color.white;
Vector2 anchor = new Vector2(param.anchorX, param.anchorY);
Vector2 origin = new Vector2(textureRect.x, textureRect.y);
int id = 99999;
anchor = (tk2dGuiUtility.PositionHandle(id, anchor * editorDisplayScale + origin, 12.0f, handleColor, handleColor ) - origin) / editorDisplayScale;
Color oldColor = Handles.color;
Handles.color = lineColor;
float w = Mathf.Max(rect.width, texture.width * editorDisplayScale);
float h = Mathf.Max(rect.height, texture.height * editorDisplayScale);
Handles.DrawLine(new Vector3(textureRect.x, textureRect.y + anchor.y * editorDisplayScale, 0), new Vector3(textureRect.x + w, textureRect.y + anchor.y * editorDisplayScale, 0));
Handles.DrawLine(new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + 0, 0), new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + h, 0));
Handles.color = oldColor;
// constrain
param.anchorX = Mathf.Clamp(Mathf.Round(anchor.x), 0.0f, texture.width);
param.anchorY = Mathf.Clamp(Mathf.Round(anchor.y), 0.0f, texture.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(param.anchorX, param.anchorY));
HandleUtility.Repaint();
}
GUI.EndScrollView();
}
// Draw toolbar
DrawToolbar(param, texture);
GUILayout.EndVertical();
}
public void DrawToolbar(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom);
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
mode = GUILayout.Toggle((mode == Mode.Texture), new GUIContent("Sprite", "Shift+Q"), EditorStyles.toolbarButton)?Mode.Texture:mode;
if (allowAnchor)
mode = GUILayout.Toggle((mode == Mode.Anchor), new GUIContent("Anchor", "Shift+W"), EditorStyles.toolbarButton)?Mode.Anchor:mode;
if (allowCollider)
mode = GUILayout.Toggle((mode == Mode.Collider), new GUIContent("Collider", "Shift+E"), EditorStyles.toolbarButton)?Mode.Collider:mode;
GUILayout.FlexibleSpace();
if (tk2dGuiUtility.HasActivePositionHandle)
{
string str = "X: " + tk2dGuiUtility.ActiveHandlePosition.x + " Y: " + tk2dGuiUtility.ActiveHandlePosition.y;
GUILayout.Label(str, EditorStyles.toolbarTextField);
}
if ((mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) ||
(mode == Mode.Texture && param.customSpriteGeometry))
{
drawColliderNormals = GUILayout.Toggle(drawColliderNormals, new GUIContent("Show Normals", "Shift+N"), EditorStyles.toolbarButton);
}
if (mode == Mode.Texture && texture != null) {
GUILayout.Label(string.Format("W: {0} H: {1}", texture.width, texture.height));
}
GUILayout.EndHorizontal();
}
public void DrawEmptyTextureView()
{
mode = Mode.None;
GUILayout.FlexibleSpace();
}
public void DrawTextureInspector(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
if (mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + T - toggle connected" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
using OmniSharp.Roslyn.CSharp.Services.Diagnostics;
using OmniSharp.Services;
using TestUtility.Fake;
namespace OmniSharp.Tests
{
public static class TestHelpers
{
public class LineColumn
{
public int Line { get; private set; }
public int Column { get; private set; }
public LineColumn(int line, int column)
{
Line = line;
Column = column;
}
public bool Equals(LineColumn other)
{
return this.Line.Equals(other.Line) &&
this.Column.Equals(other.Column);
}
}
public class Range
{
public LineColumn Start { get; private set; }
public LineColumn End { get; private set; }
public Range(LineColumn start, LineColumn end)
{
Start = start;
End = end;
}
public bool IsEmpty { get { return Start.Equals(End); } }
}
public static LineColumn GetLineAndColumnFromDollar(string text)
{
return GetLineAndColumnFromFirstOccurence(text, "$");
}
public static Range GetRangeFromDollars(string text)
{
var start = GetLineAndColumnFromFirstOccurence(text, "$");
var end = GetLineAndColumnFromLastOccurence(text, "$");
return new Range(start, end);
}
public static LineColumn GetLineAndColumnFromPercent(string text)
{
return GetLineAndColumnFromFirstOccurence(text, "%");
}
private static LineColumn GetLineAndColumnFromFirstOccurence(string text, string marker)
{
var indexOfChar = text.IndexOf(marker);
CheckIndex(indexOfChar, marker);
return GetLineAndColumnFromIndex(text, indexOfChar);
}
private static LineColumn GetLineAndColumnFromLastOccurence(string text, string marker)
{
var indexOfChar = text.LastIndexOf(marker);
CheckIndex(indexOfChar, marker);
return GetLineAndColumnFromIndex(text, indexOfChar);
}
private static void CheckIndex(int index, string marker)
{
if (index == -1)
throw new ArgumentException(string.Format("Expected a {0} in test input", marker));
}
public static LineColumn GetLineAndColumnFromIndex(string text, int index)
{
int lineCount = 0, lastLineEnd = -1;
for (int i = 0; i < index; i++)
if (text[i] == '\n')
{
lineCount++;
lastLineEnd = i;
}
return new LineColumn(lineCount, index - 1 - lastLineEnd);
}
public static string RemovePercentMarker(string fileContent)
{
return fileContent.Replace("%", "");
}
public static string RemoveDollarMarker(string fileContent)
{
return fileContent.Replace("$", "");
}
public static OmnisharpWorkspace CreateCsxWorkspace(string source, string fileName = "dummy.csx")
{
var versionStamp = VersionStamp.Create();
var mscorlib = MetadataReference.CreateFromFile(AssemblyFromType(typeof(object)).Location);
var systemCore = MetadataReference.CreateFromFile(AssemblyFromType(typeof(Enumerable)).Location);
var references = new[] { mscorlib, systemCore };
var workspace = new OmnisharpWorkspace(new HostServicesBuilder(Enumerable.Empty<ICodeActionProvider>()));
var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);
var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
var project = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, fileName,
compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), metadataReferences: references, parseOptions: parseOptions,
isSubmission: true);
workspace.AddProject(project);
var document = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), fileName, null, SourceCodeKind.Script, null, fileName)
.WithSourceCodeKind(SourceCodeKind.Script)
.WithTextLoader(TextLoader.From(TextAndVersion.Create(SourceText.From(source), VersionStamp.Create())));
workspace.AddDocument(document);
return workspace;
}
public static Task<OmnisharpWorkspace> CreateSimpleWorkspace(string source, string fileName = "dummy.cs")
{
return CreateSimpleWorkspace(CreatePluginHost(Enumerable.Empty<Assembly>()), new Dictionary<string, string> { { fileName, source } });
}
public static Task<OmnisharpWorkspace> CreateSimpleWorkspace(CompositionHost host, string source, string fileName = "dummy.cs")
{
return CreateSimpleWorkspace(host, new Dictionary<string, string> { { fileName, source } });
}
public static Task<OmnisharpWorkspace> CreateSimpleWorkspace(Dictionary<string, string> sourceFiles)
{
return CreateSimpleWorkspace(CreatePluginHost(Enumerable.Empty<Assembly>()), sourceFiles);
}
public async static Task<OmnisharpWorkspace> CreateSimpleWorkspace(CompositionHost _host, Dictionary<string, string> sourceFiles)
{
var host = _host ?? CreatePluginHost(new[] { typeof(CodeCheckService).GetTypeInfo().Assembly });
var workspace = host.GetExport<OmnisharpWorkspace>();
await AddProjectToWorkspace(workspace, "project.json", new[] { "dnx451", "dnxcore50" }, sourceFiles);
await Task.Delay(50);
return workspace;
}
public static CompositionHost CreatePluginHost(
IEnumerable<Assembly> assemblies,
Func<ContainerConfiguration, ContainerConfiguration> configure = null)
{
return Startup.ConfigureMef(
new TestServiceProvider(new FakeLoggerFactory()),
new FakeOmniSharpOptions().Value,
assemblies,
configure);
}
public static CompositionHost CreatePluginHost(IEnumerable<Assembly> assemblies)
{
return CreatePluginHost(assemblies, configure: null);
}
public static Task<OmnisharpWorkspace> AddProjectToWorkspace(OmnisharpWorkspace workspace, string filePath, string[] frameworks, Dictionary<string, string> sourceFiles)
{
var versionStamp = VersionStamp.Create();
var mscorlib = MetadataReference.CreateFromFile(AssemblyFromType(typeof(object)).Location);
var systemCore = MetadataReference.CreateFromFile(AssemblyFromType(typeof(Enumerable)).Location);
var references = new[] { mscorlib, systemCore };
foreach (var framework in frameworks)
{
var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), versionStamp,
"OmniSharp+" + framework, "AssemblyName",
LanguageNames.CSharp, filePath, metadataReferences: references);
workspace.AddProject(projectInfo);
foreach (var file in sourceFiles)
{
var document = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), file.Key,
null, SourceCodeKind.Regular,
TextLoader.From(TextAndVersion.Create(SourceText.From(file.Value), versionStamp)), file.Key);
workspace.AddDocument(document);
}
}
return Task.FromResult(workspace);
}
private static Assembly AssemblyFromType(Type type)
{
return type.GetTypeInfo().Assembly;
}
public static async Task<ISymbol> SymbolFromQuickFix(OmnisharpWorkspace workspace, QuickFix result)
{
var document = workspace.GetDocument(result.FileName);
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(result.Line, result.Column));
var semanticModel = await document.GetSemanticModelAsync();
return await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace);
}
public static async Task<IEnumerable<ISymbol>> SymbolsFromQuickFixes(OmnisharpWorkspace workspace, IEnumerable<QuickFix> quickFixes)
{
var symbols = new List<ISymbol>();
foreach (var quickfix in quickFixes)
{
symbols.Add(await TestHelpers.SymbolFromQuickFix(workspace, quickfix));
}
return symbols;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Diagnostics.Application;
using System.Threading;
/// <summary>
///
/// BufferedOutputAsyncStream is used for writing streamed response.
/// For performance reasons, the behavior we want is chunk, chunk, chunk,.. terminating chunk without a delay.
/// We call BeginWrite,BeginWrite,BeginWrite and Close()(close sends the terminating chunk) without
/// waiting for all outstanding BeginWrites to complete.
///
/// BufferedOutputAsyncStream is not a general-purpose stream wrapper, it requires that the base stream
/// 1. allow concurrent IO (for multiple BeginWrite calls)
/// 2. support the BeginWrite,BeginWrite,BeginWrite,.. Close() calling pattern.
///
/// Currently BufferedOutputAsyncStream only used to wrap the System.Net.HttpResponseStream, which satisfy both requirements.
///
/// BufferedOutputAsyncStream can also be used when doing asynchronous operations. [....] operations are not allowed when an async
/// operation is in-flight. If a [....] operation is in progress (i.e., data exists in our CurrentBuffer) and we issue an async operation,
/// we flush everything in the buffers (and block while doing so) before the async operation is allowed to proceed.
///
/// </summary>
class BufferedOutputAsyncStream : Stream
{
readonly Stream stream;
readonly int bufferSize;
readonly int bufferLimit;
readonly BufferQueue buffers;
ByteBuffer currentByteBuffer;
int availableBufferCount;
static AsyncEventArgsCallback onFlushComplete = new AsyncEventArgsCallback(OnFlushComplete);
int asyncWriteCount;
WriteAsyncState writeState;
WriteAsyncArgs writeArgs;
static AsyncEventArgsCallback onAsyncFlushComplete;
static AsyncEventArgsCallback onWriteCallback;
EventTraceActivity activity;
bool closed;
internal BufferedOutputAsyncStream(Stream stream, int bufferSize, int bufferLimit)
{
this.stream = stream;
this.bufferSize = bufferSize;
this.bufferLimit = bufferLimit;
this.buffers = new BufferQueue(this.bufferLimit);
this.buffers.Add(new ByteBuffer(this, this.bufferSize, stream));
this.availableBufferCount = 1;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return stream.CanWrite && (!this.closed); }
}
public override long Length
{
get
{
#pragma warning suppress 56503 // [....], required by the Stream.Length contract
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
}
}
public override long Position
{
get
{
#pragma warning suppress 56503 // [....], required by the Stream.Position contract
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
set
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
}
internal EventTraceActivity EventTraceActivity
{
get
{
if (TD.BufferedAsyncWriteStartIsEnabled())
{
if (this.activity == null)
{
this.activity = EventTraceActivity.GetFromThreadOrCreate();
}
}
return this.activity;
}
}
ByteBuffer GetCurrentBuffer()
{
// Dequeue will null out the buffer
this.ThrowOnException();
if (this.currentByteBuffer == null)
{
this.currentByteBuffer = this.buffers.CurrentBuffer();
}
return this.currentByteBuffer;
}
public override void Close()
{
try
{
if (!this.closed)
{
this.FlushPendingBuffer();
stream.Close();
this.WaitForAllWritesToComplete();
}
}
finally
{
this.closed = true;
}
}
public override void Flush()
{
FlushPendingBuffer();
stream.Flush();
}
void FlushPendingBuffer()
{
ByteBuffer asyncBuffer = this.buffers.CurrentBuffer();
if (asyncBuffer != null)
{
this.DequeueAndFlush(asyncBuffer, onFlushComplete);
}
}
void IncrementAsyncWriteCount()
{
if (Interlocked.Increment(ref this.asyncWriteCount) > 1)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WriterAsyncWritePending)));
}
}
void DecrementAsyncWriteCount()
{
if (Interlocked.Decrement(ref this.asyncWriteCount) != 0)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.NoAsyncWritePending)));
}
}
void EnsureNoAsyncWritePending()
{
if (this.asyncWriteCount != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.WriterAsyncWritePending)));
}
}
void EnsureOpened()
{
if (this.closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StreamClosed)));
}
}
ByteBuffer NextBuffer()
{
if (!this.AdjustBufferSize())
{
this.buffers.WaitForAny();
}
return this.GetCurrentBuffer();
}
bool AdjustBufferSize()
{
if (this.availableBufferCount < this.bufferLimit)
{
buffers.Add(new ByteBuffer(this, bufferSize, stream));
this.availableBufferCount++;
return true;
}
return false;
}
public override int Read(byte[] buffer, int offset, int count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
}
public override int ReadByte()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
}
public override long Seek(long offset, SeekOrigin origin)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
public override void SetLength(long value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
void WaitForAllWritesToComplete()
{
// Complete all outstanding writes
this.buffers.WaitForAllWritesToComplete();
}
public override void Write(byte[] buffer, int offset, int count)
{
this.EnsureOpened();
this.EnsureNoAsyncWritePending();
while (count > 0)
{
ByteBuffer currentBuffer = this.GetCurrentBuffer();
if (currentBuffer == null)
{
currentBuffer = this.NextBuffer();
}
int freeBytes = currentBuffer.FreeBytes; // space left in the CurrentBuffer
if (freeBytes > 0)
{
if (freeBytes > count)
freeBytes = count;
currentBuffer.CopyData(buffer, offset, freeBytes);
offset += freeBytes;
count -= freeBytes;
}
if (currentBuffer.FreeBytes == 0)
{
this.DequeueAndFlush(currentBuffer, onFlushComplete);
}
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
this.EnsureOpened();
this.IncrementAsyncWriteCount();
Fx.Assert(this.writeState == null ||
this.writeState.Arguments == null ||
this.writeState.Arguments.Count <= 0,
"All data has not been written yet.");
if (onWriteCallback == null)
{
onWriteCallback = new AsyncEventArgsCallback(OnWriteCallback);
onAsyncFlushComplete = new AsyncEventArgsCallback(OnAsyncFlushComplete);
}
if (this.writeState == null)
{
this.writeState = new WriteAsyncState();
this.writeArgs = new WriteAsyncArgs();
}
else
{
// Since writeState!= null, check if the stream has an
// exception as the async path has already been invoked.
this.ThrowOnException();
}
this.writeArgs.Set(buffer, offset, count, callback, state);
this.writeState.Set(onWriteCallback, this.writeArgs, this);
if (this.WriteAsync(this.writeState) == AsyncCompletionResult.Completed)
{
this.writeState.Complete(true);
if (callback != null)
{
callback(this.writeState.CompletedSynchronouslyAsyncResult);
}
return this.writeState.CompletedSynchronouslyAsyncResult;
}
return this.writeState.PendingAsyncResult;
}
public override void EndWrite(IAsyncResult asyncResult)
{
this.DecrementAsyncWriteCount();
this.ThrowOnException();
}
public override void WriteByte(byte value)
{
this.EnsureNoAsyncWritePending();
ByteBuffer currentBuffer = this.GetCurrentBuffer();
if (currentBuffer == null)
{
currentBuffer = NextBuffer();
}
currentBuffer.CopyData(value);
if (currentBuffer.FreeBytes == 0)
{
this.DequeueAndFlush(currentBuffer, onFlushComplete);
}
}
void DequeueAndFlush(ByteBuffer currentBuffer, AsyncEventArgsCallback callback)
{
// Dequeue does a checkout of the buffer from its slot.
// the callback for the [....] path only enqueues the buffer.
// The WriteAsync callback needs to enqueue and also complete.
this.currentByteBuffer = null;
ByteBuffer dequeued = this.buffers.Dequeue();
Fx.Assert(dequeued == currentBuffer, "Buffer queue in an inconsistent state.");
WriteFlushAsyncEventArgs writeflushState = (WriteFlushAsyncEventArgs)currentBuffer.FlushAsyncArgs;
if (writeflushState == null)
{
writeflushState = new WriteFlushAsyncEventArgs();
currentBuffer.FlushAsyncArgs = writeflushState;
}
writeflushState.Set(callback, null, this);
if (currentBuffer.FlushAsync() == AsyncCompletionResult.Completed)
{
this.buffers.Enqueue(currentBuffer);
writeflushState.Complete(true);
}
}
static void OnFlushComplete(IAsyncEventArgs state)
{
BufferedOutputAsyncStream thisPtr = (BufferedOutputAsyncStream)state.AsyncState;
WriteFlushAsyncEventArgs flushState = (WriteFlushAsyncEventArgs)state;
ByteBuffer byteBuffer = flushState.Result;
thisPtr.buffers.Enqueue(byteBuffer);
}
AsyncCompletionResult WriteAsync(WriteAsyncState state)
{
Fx.Assert(state != null && state.Arguments != null, "Invalid WriteAsyncState parameter.");
if (state.Arguments.Count == 0)
{
return AsyncCompletionResult.Completed;
}
byte[] buffer = state.Arguments.Buffer;
int offset = state.Arguments.Offset;
int count = state.Arguments.Count;
ByteBuffer currentBuffer = this.GetCurrentBuffer();
while (count > 0)
{
if (currentBuffer == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WriteAsyncWithoutFreeBuffer)));
}
int freeBytes = currentBuffer.FreeBytes; // space left in the CurrentBuffer
if (freeBytes > 0)
{
if (freeBytes > count)
freeBytes = count;
currentBuffer.CopyData(buffer, offset, freeBytes);
offset += freeBytes;
count -= freeBytes;
}
if (currentBuffer.FreeBytes == 0)
{
this.DequeueAndFlush(currentBuffer, onAsyncFlushComplete);
// We might need to increase the number of buffers available
// if there is more data to be written or no buffer is available.
if (count > 0 || this.buffers.Count == 0)
{
this.AdjustBufferSize();
}
}
//Update state for any pending writes.
state.Arguments.Offset = offset;
state.Arguments.Count = count;
// We can complete synchronously only
// if there a buffer available for writes.
currentBuffer = this.GetCurrentBuffer();
if (currentBuffer == null)
{
if (this.buffers.TryUnlock())
{
return AsyncCompletionResult.Queued;
}
currentBuffer = this.GetCurrentBuffer();
}
}
return AsyncCompletionResult.Completed;
}
static void OnAsyncFlushComplete(IAsyncEventArgs state)
{
BufferedOutputAsyncStream thisPtr = (BufferedOutputAsyncStream)state.AsyncState;
Exception completionException = null;
bool completeSelf = false;
try
{
OnFlushComplete(state);
if (thisPtr.buffers.TryAcquireLock())
{
WriteFlushAsyncEventArgs flushState = (WriteFlushAsyncEventArgs)state;
if (flushState.Exception != null)
{
completeSelf = true;
completionException = flushState.Exception;
}
else
{
if (thisPtr.WriteAsync(thisPtr.writeState) == AsyncCompletionResult.Completed)
{
completeSelf = true;
}
}
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
if (completionException == null)
{
completionException = exception;
}
completeSelf = true;
}
if (completeSelf)
{
thisPtr.writeState.Complete(false, completionException);
}
}
static void OnWriteCallback(IAsyncEventArgs state)
{
BufferedOutputAsyncStream thisPtr = (BufferedOutputAsyncStream)state.AsyncState;
IAsyncResult returnResult = thisPtr.writeState.PendingAsyncResult;
AsyncCallback callback = thisPtr.writeState.Arguments.Callback;
thisPtr.writeState.Arguments.Callback = null;
if (callback != null)
{
callback(returnResult);
}
}
void ThrowOnException()
{
// if any of the buffers or the write state has an
// exception the stream is not usable anymore.
this.buffers.ThrowOnException();
if (this.writeState != null)
{
this.writeState.ThrowOnException();
}
}
class BufferQueue
{
readonly List<ByteBuffer> refBufferList;
readonly int size;
readonly Slot[] buffers;
Exception completionException;
int head;
int count;
bool waiting;
bool pendingCompletion;
internal BufferQueue(int queueSize)
{
this.head = 0;
this.count = 0;
this.size = queueSize;
this.buffers = new Slot[size];
this.refBufferList = new List<ByteBuffer>();
for (int i = 0; i < queueSize; i++)
{
Slot s = new Slot();
s.checkedOut = true; //Start with all buffers checkedout.
this.buffers[i] = s;
}
}
object ThisLock
{
get
{
return this.buffers;
}
}
internal int Count
{
get
{
lock (ThisLock)
{
return count;
}
}
}
internal ByteBuffer Dequeue()
{
Fx.Assert(!this.pendingCompletion, "Dequeue cannot be invoked when there is a pending completion");
lock (ThisLock)
{
if (count == 0)
{
return null;
}
Slot s = buffers[head];
Fx.Assert(!s.checkedOut, "This buffer is already in use.");
this.head = (this.head + 1) % size;
this.count--;
ByteBuffer buffer = s.buffer;
s.buffer = null;
s.checkedOut = true;
return buffer;
}
}
internal void Add(ByteBuffer buffer)
{
lock (ThisLock)
{
Fx.Assert(this.refBufferList.Count < size, "Bufferlist is already full.");
if (this.refBufferList.Count < this.size)
{
this.refBufferList.Add(buffer);
this.Enqueue(buffer);
}
}
}
internal void Enqueue(ByteBuffer buffer)
{
lock (ThisLock)
{
this.completionException = this.completionException ?? buffer.CompletionException;
Fx.Assert(count < size, "The queue is already full.");
int tail = (this.head + this.count) % size;
Slot s = this.buffers[tail];
this.count++;
Fx.Assert(s.checkedOut, "Current buffer is still free.");
s.checkedOut = false;
s.buffer = buffer;
if (this.waiting)
{
Monitor.Pulse(this.ThisLock);
}
}
}
internal ByteBuffer CurrentBuffer()
{
lock (ThisLock)
{
ThrowOnException();
Slot s = this.buffers[head];
return s.buffer;
}
}
internal void WaitForAllWritesToComplete()
{
for (int i = 0; i < this.refBufferList.Count; i++)
{
this.refBufferList[i].WaitForWriteComplete();
}
}
internal void WaitForAny()
{
lock (ThisLock)
{
if (this.count == 0)
{
this.waiting = true;
Monitor.Wait(ThisLock);
this.waiting = false;
}
}
this.ThrowOnException();
}
internal void ThrowOnException()
{
if (this.completionException != null)
{
throw FxTrace.Exception.AsError(this.completionException);
}
}
internal bool TryUnlock()
{
// The main thread tries to indicate a pending completion
// if there aren't any free buffers for the next write.
// The callback should try to complete() through TryAcquireLock.
lock (ThisLock)
{
Fx.Assert(!this.pendingCompletion, "There is already a completion pending.");
if (this.count == 0)
{
this.pendingCompletion = true;
return true;
}
}
return false;
}
internal bool TryAcquireLock()
{
// The callback tries to acquire the lock if there is a pending completion and a free buffer.
// Buffers might get dequeued by the main writing thread as soon as they are enqueued.
lock (ThisLock)
{
if (this.pendingCompletion && this.count > 0)
{
this.pendingCompletion = false;
return true;
}
}
return false;
}
class Slot
{
internal bool checkedOut;
internal ByteBuffer buffer;
}
}
/// <summary>
/// AsyncEventArgs used to invoke the FlushAsync() on the ByteBuffer.
/// </summary>
class WriteFlushAsyncEventArgs : AsyncEventArgs<object, ByteBuffer>
{
}
class ByteBuffer
{
byte[] bytes;
int position;
Stream stream;
bool writePending;
bool waiting;
Exception completionException;
BufferedOutputAsyncStream parent;
static AsyncCallback writeCallback = Fx.ThunkCallback(new AsyncCallback(WriteCallback));
static AsyncCallback flushCallback;
internal ByteBuffer(BufferedOutputAsyncStream parent, int bufferSize, Stream stream)
{
this.waiting = false;
this.writePending = false;
this.position = 0;
this.bytes = DiagnosticUtility.Utility.AllocateByteArray(bufferSize);
this.stream = stream;
this.parent = parent;
}
object ThisLock
{
get { return this; }
}
internal Exception CompletionException
{
get { return this.completionException; }
}
internal int FreeBytes
{
get
{
return this.bytes.Length - this.position;
}
}
internal AsyncEventArgs<object, ByteBuffer> FlushAsyncArgs
{
get;
set;
}
static void WriteCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
// Fetch our state information: ByteBuffer
ByteBuffer buffer = (ByteBuffer)result.AsyncState;
try
{
if (TD.BufferedAsyncWriteStopIsEnabled())
{
TD.BufferedAsyncWriteStop(buffer.parent.EventTraceActivity);
}
buffer.stream.EndWrite(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
buffer.completionException = e;
}
// Tell the main thread we've finished.
lock (buffer.ThisLock)
{
buffer.writePending = false;
// Do not Pulse if no one is waiting, to avoid the overhead of Pulse
if (!buffer.waiting)
return;
Monitor.Pulse(buffer.ThisLock);
}
}
internal void WaitForWriteComplete()
{
lock (ThisLock)
{
if (this.writePending)
{
// Wait until the async write of this buffer is finished.
this.waiting = true;
Monitor.Wait(ThisLock);
this.waiting = false;
}
}
// Raise exception if necessary
if (this.completionException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(completionException);
}
}
internal void CopyData(byte[] buffer, int offset, int count)
{
Fx.Assert(this.position + count <= this.bytes.Length, string.Format(CultureInfo.InvariantCulture, "Chunk is too big to fit in this buffer. Chunk size={0}, free space={1}", count, this.bytes.Length - this.position));
Fx.Assert(!this.writePending, string.Format(CultureInfo.InvariantCulture, "The buffer is in use, position={0}", this.position));
Buffer.BlockCopy(buffer, offset, this.bytes, this.position, count);
this.position += count;
}
internal void CopyData(byte value)
{
Fx.Assert(this.position < this.bytes.Length, "Buffer is full");
Fx.Assert(!this.writePending, string.Format(CultureInfo.InvariantCulture, "The buffer is in use, position={0}", this.position));
this.bytes[this.position++] = value;
}
/// <summary>
/// Set the ByteBuffer's FlushAsyncArgs to invoke FlushAsync()
/// </summary>
/// <returns></returns>
internal AsyncCompletionResult FlushAsync()
{
if (this.position <= 0)
return AsyncCompletionResult.Completed;
Fx.Assert(this.FlushAsyncArgs != null, "FlushAsyncArgs not set.");
if (flushCallback == null)
{
flushCallback = new AsyncCallback(OnAsyncFlush);
}
int bytesToWrite = this.position;
this.SetWritePending();
this.position = 0;
if (TD.BufferedAsyncWriteStartIsEnabled())
{
TD.BufferedAsyncWriteStart(this.parent.EventTraceActivity, this.GetHashCode(), bytesToWrite);
}
IAsyncResult asyncResult = this.stream.BeginWrite(this.bytes, 0, bytesToWrite, flushCallback, this);
if (asyncResult.CompletedSynchronously)
{
if (TD.BufferedAsyncWriteStopIsEnabled())
{
TD.BufferedAsyncWriteStop(this.parent.EventTraceActivity);
}
this.stream.EndWrite(asyncResult);
this.ResetWritePending();
return AsyncCompletionResult.Completed;
}
return AsyncCompletionResult.Queued;
}
static void OnAsyncFlush(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
ByteBuffer thisPtr = (ByteBuffer)result.AsyncState;
AsyncEventArgs<object, ByteBuffer> asyncEventArgs = thisPtr.FlushAsyncArgs;
try
{
ByteBuffer.WriteCallback(result);
asyncEventArgs.Result = thisPtr;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
if (thisPtr.completionException == null)
{
thisPtr.completionException = exception;
}
}
asyncEventArgs.Complete(false, thisPtr.completionException);
}
void ResetWritePending()
{
lock (ThisLock)
{
this.writePending = false;
}
}
void SetWritePending()
{
lock (ThisLock)
{
if (this.writePending)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.FlushBufferAlreadyInUse)));
}
this.writePending = true;
}
}
}
/// <summary>
/// Used to hold the users callback and state and arguments when BeginWrite is invoked.
/// </summary>
class WriteAsyncArgs
{
internal byte[] Buffer { get; set; }
internal int Offset { get; set; }
internal int Count { get; set; }
internal AsyncCallback Callback { get; set; }
internal object AsyncState { get; set; }
internal void Set(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
this.Buffer = buffer;
this.Offset = offset;
this.Count = count;
this.Callback = callback;
this.AsyncState = state;
}
}
class WriteAsyncState : AsyncEventArgs<WriteAsyncArgs, BufferedOutputAsyncStream>
{
PooledAsyncResult pooledAsyncResult;
PooledAsyncResult completedSynchronouslyResult;
internal IAsyncResult PendingAsyncResult
{
get
{
if (this.pooledAsyncResult == null)
{
this.pooledAsyncResult = new PooledAsyncResult(this, false);
}
return this.pooledAsyncResult;
}
}
internal IAsyncResult CompletedSynchronouslyAsyncResult
{
get
{
if (this.completedSynchronouslyResult == null)
{
this.completedSynchronouslyResult = new PooledAsyncResult(this, true);
}
return completedSynchronouslyResult;
}
}
internal void ThrowOnException()
{
if (this.Exception != null)
{
throw FxTrace.Exception.AsError(this.Exception);
}
}
class PooledAsyncResult : IAsyncResult
{
readonly WriteAsyncState writeState;
readonly bool completedSynchronously;
internal PooledAsyncResult(WriteAsyncState parentState, bool completedSynchronously)
{
this.writeState = parentState;
this.completedSynchronously = completedSynchronously;
}
public object AsyncState
{
get
{
return this.writeState.Arguments != null ? this.writeState.Arguments.AsyncState : null;
}
}
public WaitHandle AsyncWaitHandle
{
get { throw FxTrace.Exception.AsError(new NotImplementedException()); }
}
public bool CompletedSynchronously
{
get { return this.completedSynchronously; }
}
public bool IsCompleted
{
get { throw FxTrace.Exception.AsError(new NotImplementedException()); }
}
}
}
}
}
| |
// <copyright file="EditableItemBase.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Threading;
using IX.StandardExtensions.ComponentModel;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
namespace IX.Undoable
{
/// <summary>
/// A base class for editable items that can be edited in a transactional-style pattern.
/// </summary>
/// <seealso cref="IX.Undoable.ITransactionEditableItem" />
/// <seealso cref="IX.Undoable.IUndoableItem" />
[PublicAPI]
public abstract class EditableItemBase : ViewModelBase, ITransactionEditableItem, IUndoableItem
{
private readonly List<StateChange> stateChanges;
private int historyLevels;
private Lazy<UndoableInnerContext> undoContext;
/// <summary>
/// Initializes a new instance of the <see cref="EditableItemBase" /> class.
/// </summary>
protected EditableItemBase()
: this(0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EditableItemBase" /> class.
/// </summary>
/// <param name="limit">The limit.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="limit" /> is a negative number.</exception>
protected EditableItemBase(int limit)
{
Requires.NonNegative(
out this.historyLevels,
in limit,
nameof(limit));
this.undoContext = new Lazy<UndoableInnerContext>(this.InnerContextFactory);
this.stateChanges = new List<StateChange>();
}
/// <summary>
/// Occurs when an edit on this item is committed.
/// </summary>
public event EventHandler<EditCommittedEventArgs> EditCommitted;
/// <summary>
/// Gets a value indicating whether this instance is in edit mode.
/// </summary>
/// <value><see langword="true" /> if this instance is in edit mode; otherwise, <see langword="false" />.</value>
public bool IsInEditMode { get; private set; }
/// <summary>
/// Gets or sets the number of levels to keep undo or redo information.
/// </summary>
/// <value>The history levels.</value>
/// <remarks>
/// <para>
/// If this value is set, for example, to 7, then the implementing object should allow the <see cref="Undo" />
/// method
/// to be called 7 times to change the state of the object. Upon calling it an 8th time, there should be no change
/// in the
/// state of the object.
/// </para>
/// <para>
/// Any call beyond the limit imposed here should not fail, but it should also not change the state of the
/// object.
/// </para>
/// </remarks>
public int HistoryLevels
{
get => this.historyLevels;
set
{
if (value == this.historyLevels)
{
return;
}
this.undoContext.Value.HistoryLevels = value;
// We'll let the internal undo context to curate our history levels
this.historyLevels = this.undoContext.Value.HistoryLevels;
}
}
/// <summary>
/// Gets a value indicating whether this instance is captured in undo context.
/// </summary>
/// <value><see langword="true" /> if this instance is captured in undo context; otherwise, <see langword="false" />.</value>
public bool IsCapturedIntoUndoContext => this.ParentUndoContext != null;
/// <summary>
/// Gets a value indicating whether or not an undo can be performed on this item.
/// </summary>
/// <value>
/// <see langword="true" /> if the call to the <see cref="Undo" /> method would result in a state change,
/// <see langword="false" /> otherwise.
/// </value>
public bool CanUndo => this.IsCapturedIntoUndoContext ||
(this.undoContext.IsValueCreated && this.undoContext.Value.UndoStack.Count > 0);
/// <summary>
/// Gets a value indicating whether or not a redo can be performed on this item.
/// </summary>
/// <value>
/// <see langword="true" /> if the call to the <see cref="Redo" /> method would result in a state change,
/// <see langword="false" /> otherwise.
/// </value>
public bool CanRedo => this.IsCapturedIntoUndoContext ||
(this.undoContext.IsValueCreated && this.undoContext.Value.RedoStack.Count > 0);
/// <summary>
/// Gets the parent undo context.
/// </summary>
/// <value>The parent undo context.</value>
public IUndoableItem ParentUndoContext { get; private set; }
/// <summary>
/// Begins the editing of an item.
/// </summary>
public void BeginEdit()
{
if (this.IsInEditMode)
{
return;
}
this.IsInEditMode = true;
this.RaisePropertyChanged(nameof(this.IsInEditMode));
}
/// <summary>
/// Discards all changes to the item, reloading the state at the last commit or at the beginning of the edit
/// transaction, whichever occurred last.
/// </summary>
/// <exception cref="IX.Undoable.ItemNotInEditModeException">The item is not in edit mode.</exception>
public void CancelEdit()
{
if (!this.IsInEditMode)
{
throw new ItemNotInEditModeException();
}
if (this.stateChanges.Count <= 0)
{
return;
}
this.RevertChanges(this.stateChanges.ToArray());
this.stateChanges.Clear();
}
/// <summary>
/// Commits the changes to the item as they are, without ending the editing.
/// </summary>
/// <exception cref="IX.Undoable.ItemNotInEditModeException">The item is not in edit mode.</exception>
public void CommitEdit()
{
if (!this.IsInEditMode)
{
throw new ItemNotInEditModeException();
}
if (this.stateChanges.Count <= 0)
{
return;
}
this.CommitEditInternal(this.stateChanges.ToArray());
this.stateChanges.Clear();
}
/// <summary>
/// Ends the editing of an item.
/// </summary>
/// <exception cref="IX.Undoable.ItemNotInEditModeException">The item is not in edit mode.</exception>
public void EndEdit()
{
if (!this.IsInEditMode)
{
throw new ItemNotInEditModeException();
}
if (this.stateChanges.Count > 0)
{
this.CommitEditInternal(this.stateChanges.ToArray());
this.stateChanges.Clear();
}
this.IsInEditMode = false;
this.RaisePropertyChanged(nameof(this.IsInEditMode));
}
/// <summary>
/// Allows the item to be captured by a containing undo-/redo-capable object so that undo and redo operations
/// can be coordinated across a larger scope.
/// </summary>
/// <param name="parent">The parent undo and redo context.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="parent" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <exception cref="IX.Undoable.ItemIsInEditModeException">
/// The item is in edit mode, and this operation cannot be
/// performed at this time.
/// </exception>
/// <remarks>This method is meant to be used by containers, and should not be called directly.</remarks>
public void CaptureIntoUndoContext(IUndoableItem parent)
{
Requires.NotNull(
parent,
nameof(parent));
if (parent == this.ParentUndoContext)
{
return;
}
if (this.IsInEditMode)
{
throw new ItemIsInEditModeException();
}
// Set the parent undo context
this.ParentUndoContext = parent;
if (this.undoContext.IsValueCreated)
{
// We already have an undo inner context, let's clear it out.
// If we don't have an undo inner context, no sense in clearing it out just yet.
this.undoContext.Value.HistoryLevels = 0;
}
this.RaisePropertyChanged(nameof(this.IsCapturedIntoUndoContext));
}
/// <summary>
/// Releases the item from being captured into an undo and redo context.
/// </summary>
/// <remarks>This method is meant to be used by containers, and should not be called directly.</remarks>
public void ReleaseFromUndoContext()
{
if (this.ParentUndoContext == null)
{
return;
}
// Set parent undo context as null
this.ParentUndoContext = null;
if (this.undoContext.IsValueCreated)
{
// We already have an undo inner context, let's set it back.
// If we don't have an undo inner context, no sense in setting anything.
this.undoContext.Value.HistoryLevels = this.historyLevels;
}
this.RaisePropertyChanged(nameof(this.IsCapturedIntoUndoContext));
}
/// <summary>
/// Has the last operation performed on the item undone.
/// </summary>
/// <remarks>
/// <para>
/// If the object is captured, the method will call the capturing parent's Undo method, which can bubble down to
/// the last instance of an undo-/redo-capable object.
/// </para>
/// <para>
/// If that is the case, the capturing object is solely responsible for ensuring that the inner state of the whole
/// system is correct. Implementing classes should not expect this method to also handle state.
/// </para>
/// <para>If the object is released, it is expected that this method once again starts ensuring state when called.</para>
/// </remarks>
public void Undo()
{
if (this.ParentUndoContext != null)
{
// We are captured by a parent context, let's invoke that context's Undo.
this.ParentUndoContext.Undo();
return;
}
// We are not captured, let's proceed with Undo.
// Let's check whether or not we have an undo inner context first
if (!this.undoContext.IsValueCreated)
{
// Undo inner context not created, there's nothing to undo
return;
}
// Undo context created, let's try to undo
UndoableInnerContext uc = this.undoContext.Value;
if (uc.UndoStack.Count == 0)
{
// We don't have anything to Undo.
return;
}
StateChange[] undoData = uc.UndoStack.Pop();
uc.RedoStack.Push(undoData);
this.RevertChanges(undoData);
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
/// <summary>
/// Has the last undone operation performed on this item, presuming that it has not changed since then, redone.
/// </summary>
/// <remarks>
/// <para>
/// If the object is captured, the method will call the capturing parent's Redo method, which can bubble down to
/// the last instance of an undo-/redo-capable object.
/// </para>
/// <para>
/// If that is the case, the capturing object is solely responsible for ensuring that the inner state of the whole
/// system is correct. Implementing classes should not expect this method to also handle state.
/// </para>
/// <para>If the object is released, it is expected that this method once again starts ensuring state when called.</para>
/// </remarks>
public void Redo()
{
if (this.ParentUndoContext != null)
{
// We are captured by a parent context, let's invoke that context's Redo.
this.ParentUndoContext.Redo();
return;
}
// We are not captured, let's proceed with Undo.
// Let's check whether or not we have an undo inner context first
if (!this.undoContext.IsValueCreated)
{
// Undo inner context not created, there's nothing to undo
return;
}
// Undo context created, let's try to undo
UndoableInnerContext uc = this.undoContext.Value;
if (uc.RedoStack.Count == 0)
{
// We don't have anything to Redo.
return;
}
StateChange[] redoData = uc.RedoStack.Pop();
uc.UndoStack.Push(redoData);
this.DoChanges(redoData);
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
/// <summary>
/// Has the state changes received undone from the object.
/// </summary>
/// <param name="changesToUndo">The state changes to undo.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="changesToUndo" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <exception cref="ItemNotCapturedIntoUndoContextException">
/// The item is not captured into an undo/redo context, and this
/// operation is illegal.
/// </exception>
public void UndoStateChanges(StateChange[] changesToUndo)
{
Requires.NotNull(
changesToUndo,
nameof(changesToUndo));
if (!this.IsCapturedIntoUndoContext)
{
throw new ItemNotCapturedIntoUndoContextException();
}
if (changesToUndo.Length > 0)
{
this.RevertChanges(changesToUndo);
}
}
/// <summary>
/// Has the state changes received redone into the object.
/// </summary>
/// <param name="changesToRedo">The state changes to redo.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="changesToRedo" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <exception cref="ItemNotCapturedIntoUndoContextException">
/// The item is not captured into an undo/redo context, and this
/// operation is illegal.
/// </exception>
public void RedoStateChanges(StateChange[] changesToRedo)
{
Requires.NotNull(
changesToRedo,
nameof(changesToRedo));
if (!this.IsCapturedIntoUndoContext)
{
throw new ItemNotCapturedIntoUndoContextException();
}
if (changesToRedo.Length > 0)
{
this.DoChanges(changesToRedo);
}
}
/// <summary>
/// Captures a sub item into the present context.
/// </summary>
/// <typeparam name="TSubItem">The type of the sub item.</typeparam>
/// <param name="item">The item.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="item" />
/// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This method is intended to capture only objects that are directly sub-objects that can have their own internal
/// state and undo/redo
/// capabilities and are also transactional in nature when being edited. Using this method on any other object may
/// yield unwanted
/// commits.
/// </remarks>
protected void CaptureSubItemIntoPresentContext<TSubItem>(TSubItem item)
where TSubItem : IUndoableItem, IEditCommittableItem
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.CaptureIntoUndoContext(this);
item.EditCommitted += this.Item_EditCommitted;
}
/// <summary>
/// Releases the sub item from present context.
/// </summary>
/// <typeparam name="TSubItem">The type of the sub item.</typeparam>
/// <param name="item">The item.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="item" />
/// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
protected void ReleaseSubItemFromPresentContext<TSubItem>(TSubItem item)
where TSubItem : IUndoableItem, IEditCommittableItem
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.EditCommitted -= this.Item_EditCommitted;
item.ReleaseFromUndoContext();
}
/// <summary>
/// Can be called to advertise a change of state in an implementing class.
/// </summary>
/// <param name="stateChange">The state change to advertise.</param>
protected void AdvertiseStateChange(StateChange stateChange)
{
if (this.IsInEditMode)
{
this.stateChanges.Add(stateChange);
}
else
{
this.CommitEditInternal(new[] { stateChange });
}
}
/// <summary>
/// Advertises a property change.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="propertyName">Name of the property.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
protected void AdvertisePropertyChange<T>(
string propertyName,
T oldValue,
T newValue) => this.AdvertiseStateChange(
new PropertyStateChange<T>
{
PropertyName = propertyName,
OldValue = oldValue,
NewValue = newValue
});
/// <summary>
/// Disposes in the managed context.
/// </summary>
protected override void DisposeManagedContext()
{
base.DisposeManagedContext();
var uc = Interlocked.Exchange(
ref this.undoContext,
null);
if (uc?.IsValueCreated ?? false)
{
uc.Value.Dispose();
}
}
/// <summary>
/// Called when a list of state changes are canceled and must be reverted.
/// </summary>
/// <param name="stateChanges">The state changes to revert.</param>
protected abstract void RevertChanges(StateChange[] stateChanges);
/// <summary>
/// Called when a list of state changes must be executed.
/// </summary>
/// <param name="stateChanges">The state changes to execute.</param>
protected abstract void DoChanges(StateChange[] stateChanges);
/// <summary>
/// Handles the EditCommitted event of the sub-item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EditCommittedEventArgs" /> instance containing the event data.</param>
private void Item_EditCommitted(
object sender,
EditCommittedEventArgs e)
{
this.stateChanges.Add(
new SubItemStateChange { StateChanges = e.StateChanges, SubObject = (IUndoableItem)sender });
this.CommitEditInternal(this.stateChanges.ToArray());
}
/// <summary>
/// Commits the edit internally.
/// </summary>
/// <param name="changesToCommit">The state changes.</param>
private void CommitEditInternal(StateChange[] changesToCommit)
{
if ((changesToCommit?.Length ?? 0) == 0)
{
return;
}
if (this.ParentUndoContext == null && this.historyLevels > 0)
{
this.undoContext.Value.UndoStack.Push(changesToCommit);
this.undoContext.Value.RedoStack.Clear();
}
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
this.EditCommitted?.Invoke(
this,
new EditCommittedEventArgs(changesToCommit));
}
private UndoableInnerContext InnerContextFactory() => new UndoableInnerContext
{
HistoryLevels = this.historyLevels
};
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
namespace dnlib.DotNet.MD {
/// <summary>
/// Initializes .NET table row sizes
/// </summary>
public sealed class DotNetTableSizes {
bool bigStrings;
bool bigGuid;
bool bigBlob;
bool forceAllBig;
TableInfo[] tableInfos;
internal static bool IsSystemTable(Table table) => table < Table.Document;
/// <summary>
/// Initializes the table sizes
/// </summary>
/// <param name="bigStrings"><c>true</c> if #Strings size >= 0x10000</param>
/// <param name="bigGuid"><c>true</c> if #GUID size >= 0x10000</param>
/// <param name="bigBlob"><c>true</c> if #Blob size >= 0x10000</param>
/// <param name="systemRowCounts">Count of rows in each table</param>
/// <param name="debugRowCounts">Count of rows in each table (debug tables)</param>
public void InitializeSizes(bool bigStrings, bool bigGuid, bool bigBlob, IList<uint> systemRowCounts, IList<uint> debugRowCounts) =>
InitializeSizes(bigStrings, bigGuid, bigBlob, systemRowCounts, debugRowCounts, false);
/// <summary>
/// Initializes the table sizes
/// </summary>
/// <param name="bigStrings"><c>true</c> if #Strings size >= 0x10000</param>
/// <param name="bigGuid"><c>true</c> if #GUID size >= 0x10000</param>
/// <param name="bigBlob"><c>true</c> if #Blob size >= 0x10000</param>
/// <param name="systemRowCounts">Count of rows in each table</param>
/// <param name="debugRowCounts">Count of rows in each table (debug tables)</param>
/// <param name="forceAllBig">Force all columns to 4 bytes instead of 2 or 4 bytes</param>
internal void InitializeSizes(bool bigStrings, bool bigGuid, bool bigBlob, IList<uint> systemRowCounts, IList<uint> debugRowCounts, bool forceAllBig) {
this.bigStrings = bigStrings || forceAllBig;
this.bigGuid = bigGuid || forceAllBig;
this.bigBlob = bigBlob || forceAllBig;
this.forceAllBig = forceAllBig;
foreach (var tableInfo in tableInfos) {
var rowCounts = IsSystemTable(tableInfo.Table) ? systemRowCounts : debugRowCounts;
int colOffset = 0;
foreach (var colInfo in tableInfo.Columns) {
colInfo.Offset = colOffset;
var colSize = GetSize(colInfo.ColumnSize, rowCounts);
colInfo.Size = colSize;
colOffset += colSize;
}
tableInfo.RowSize = colOffset;
}
}
int GetSize(ColumnSize columnSize, IList<uint> rowCounts) {
if (ColumnSize.Module <= columnSize && columnSize <= ColumnSize.CustomDebugInformation) {
int table = (int)(columnSize - ColumnSize.Module);
uint count = table >= rowCounts.Count ? 0 : rowCounts[table];
return forceAllBig || count > 0xFFFF ? 4 : 2;
}
else if (ColumnSize.TypeDefOrRef <= columnSize && columnSize <= ColumnSize.HasCustomDebugInformation) {
var info = columnSize switch {
ColumnSize.TypeDefOrRef => CodedToken.TypeDefOrRef,
ColumnSize.HasConstant => CodedToken.HasConstant,
ColumnSize.HasCustomAttribute => CodedToken.HasCustomAttribute,
ColumnSize.HasFieldMarshal => CodedToken.HasFieldMarshal,
ColumnSize.HasDeclSecurity => CodedToken.HasDeclSecurity,
ColumnSize.MemberRefParent => CodedToken.MemberRefParent,
ColumnSize.HasSemantic => CodedToken.HasSemantic,
ColumnSize.MethodDefOrRef => CodedToken.MethodDefOrRef,
ColumnSize.MemberForwarded => CodedToken.MemberForwarded,
ColumnSize.Implementation => CodedToken.Implementation,
ColumnSize.CustomAttributeType => CodedToken.CustomAttributeType,
ColumnSize.ResolutionScope => CodedToken.ResolutionScope,
ColumnSize.TypeOrMethodDef => CodedToken.TypeOrMethodDef,
ColumnSize.HasCustomDebugInformation => CodedToken.HasCustomDebugInformation,
_ => throw new InvalidOperationException($"Invalid ColumnSize: {columnSize}"),
};
uint maxRows = 0;
foreach (var tableType in info.TableTypes) {
int index = (int)tableType;
var tableRows = index >= rowCounts.Count ? 0 : rowCounts[index];
if (tableRows > maxRows)
maxRows = tableRows;
}
// Can't overflow since maxRows <= 0x00FFFFFF and info.Bits < 8
uint finalRows = maxRows << info.Bits;
return forceAllBig || finalRows > 0xFFFF ? 4 : 2;
}
else {
switch (columnSize) {
case ColumnSize.Byte: return 1;
case ColumnSize.Int16: return 2;
case ColumnSize.UInt16: return 2;
case ColumnSize.Int32: return 4;
case ColumnSize.UInt32: return 4;
case ColumnSize.Strings:return forceAllBig || bigStrings ? 4 : 2;
case ColumnSize.GUID: return forceAllBig || bigGuid ? 4 : 2;
case ColumnSize.Blob: return forceAllBig || bigBlob ? 4 : 2;
}
}
throw new InvalidOperationException($"Invalid ColumnSize: {columnSize}");
}
/// <summary>
/// Creates the table infos
/// </summary>
/// <param name="majorVersion">Major table version</param>
/// <param name="minorVersion">Minor table version</param>
/// <returns>All table infos (not completely initialized)</returns>
public TableInfo[] CreateTables(byte majorVersion, byte minorVersion) =>
CreateTables(majorVersion, minorVersion, out int maxPresentTables);
internal const int normalMaxTables = (int)Table.CustomDebugInformation + 1;
/// <summary>
/// Creates the table infos
/// </summary>
/// <param name="majorVersion">Major table version</param>
/// <param name="minorVersion">Minor table version</param>
/// <param name="maxPresentTables">Initialized to max present tables (eg. 42 or 45)</param>
/// <returns>All table infos (not completely initialized)</returns>
public TableInfo[] CreateTables(byte majorVersion, byte minorVersion, out int maxPresentTables) {
maxPresentTables = (majorVersion == 1 && minorVersion == 0) ? (int)Table.NestedClass + 1 : normalMaxTables;
var tableInfos = new TableInfo[normalMaxTables];
tableInfos[(int)Table.Module] = new TableInfo(Table.Module, "Module", new ColumnInfo[] {
new ColumnInfo(0, "Generation", ColumnSize.UInt16),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Mvid", ColumnSize.GUID),
new ColumnInfo(3, "EncId", ColumnSize.GUID),
new ColumnInfo(4, "EncBaseId", ColumnSize.GUID),
});
tableInfos[(int)Table.TypeRef] = new TableInfo(Table.TypeRef, "TypeRef", new ColumnInfo[] {
new ColumnInfo(0, "ResolutionScope", ColumnSize.ResolutionScope),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Namespace", ColumnSize.Strings),
});
tableInfos[(int)Table.TypeDef] = new TableInfo(Table.TypeDef, "TypeDef", new ColumnInfo[] {
new ColumnInfo(0, "Flags", ColumnSize.UInt32),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Namespace", ColumnSize.Strings),
new ColumnInfo(3, "Extends", ColumnSize.TypeDefOrRef),
new ColumnInfo(4, "FieldList", ColumnSize.Field),
new ColumnInfo(5, "MethodList", ColumnSize.Method),
});
tableInfos[(int)Table.FieldPtr] = new TableInfo(Table.FieldPtr, "FieldPtr", new ColumnInfo[] {
new ColumnInfo(0, "Field", ColumnSize.Field),
});
tableInfos[(int)Table.Field] = new TableInfo(Table.Field, "Field", new ColumnInfo[] {
new ColumnInfo(0, "Flags", ColumnSize.UInt16),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Signature", ColumnSize.Blob),
});
tableInfos[(int)Table.MethodPtr] = new TableInfo(Table.MethodPtr, "MethodPtr", new ColumnInfo[] {
new ColumnInfo(0, "Method", ColumnSize.Method),
});
tableInfos[(int)Table.Method] = new TableInfo(Table.Method, "Method", new ColumnInfo[] {
new ColumnInfo(0, "RVA", ColumnSize.UInt32),
new ColumnInfo(1, "ImplFlags", ColumnSize.UInt16),
new ColumnInfo(2, "Flags", ColumnSize.UInt16),
new ColumnInfo(3, "Name", ColumnSize.Strings),
new ColumnInfo(4, "Signature", ColumnSize.Blob),
new ColumnInfo(5, "ParamList", ColumnSize.Param),
});
tableInfos[(int)Table.ParamPtr] = new TableInfo(Table.ParamPtr, "ParamPtr", new ColumnInfo[] {
new ColumnInfo(0, "Param", ColumnSize.Param),
});
tableInfos[(int)Table.Param] = new TableInfo(Table.Param, "Param", new ColumnInfo[] {
new ColumnInfo(0, "Flags", ColumnSize.UInt16),
new ColumnInfo(1, "Sequence", ColumnSize.UInt16),
new ColumnInfo(2, "Name", ColumnSize.Strings),
});
tableInfos[(int)Table.InterfaceImpl] = new TableInfo(Table.InterfaceImpl, "InterfaceImpl", new ColumnInfo[] {
new ColumnInfo(0, "Class", ColumnSize.TypeDef),
new ColumnInfo(1, "Interface", ColumnSize.TypeDefOrRef),
});
tableInfos[(int)Table.MemberRef] = new TableInfo(Table.MemberRef, "MemberRef", new ColumnInfo[] {
new ColumnInfo(0, "Class", ColumnSize.MemberRefParent),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Signature", ColumnSize.Blob),
});
tableInfos[(int)Table.Constant] = new TableInfo(Table.Constant, "Constant", new ColumnInfo[] {
new ColumnInfo(0, "Type", ColumnSize.Byte),
new ColumnInfo(1, "Padding", ColumnSize.Byte),
new ColumnInfo(2, "Parent", ColumnSize.HasConstant),
new ColumnInfo(3, "Value", ColumnSize.Blob),
});
tableInfos[(int)Table.CustomAttribute] = new TableInfo(Table.CustomAttribute, "CustomAttribute", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.HasCustomAttribute),
new ColumnInfo(1, "Type", ColumnSize.CustomAttributeType),
new ColumnInfo(2, "Value", ColumnSize.Blob),
});
tableInfos[(int)Table.FieldMarshal] = new TableInfo(Table.FieldMarshal, "FieldMarshal", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.HasFieldMarshal),
new ColumnInfo(1, "NativeType", ColumnSize.Blob),
});
tableInfos[(int)Table.DeclSecurity] = new TableInfo(Table.DeclSecurity, "DeclSecurity", new ColumnInfo[] {
new ColumnInfo(0, "Action", ColumnSize.Int16),
new ColumnInfo(1, "Parent", ColumnSize.HasDeclSecurity),
new ColumnInfo(2, "PermissionSet", ColumnSize.Blob),
});
tableInfos[(int)Table.ClassLayout] = new TableInfo(Table.ClassLayout, "ClassLayout", new ColumnInfo[] {
new ColumnInfo(0, "PackingSize", ColumnSize.UInt16),
new ColumnInfo(1, "ClassSize", ColumnSize.UInt32),
new ColumnInfo(2, "Parent", ColumnSize.TypeDef),
});
tableInfos[(int)Table.FieldLayout] = new TableInfo(Table.FieldLayout, "FieldLayout", new ColumnInfo[] {
new ColumnInfo(0, "OffSet", ColumnSize.UInt32),
new ColumnInfo(1, "Field", ColumnSize.Field),
});
tableInfos[(int)Table.StandAloneSig] = new TableInfo(Table.StandAloneSig, "StandAloneSig", new ColumnInfo[] {
new ColumnInfo(0, "Signature", ColumnSize.Blob),
});
tableInfos[(int)Table.EventMap] = new TableInfo(Table.EventMap, "EventMap", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.TypeDef),
new ColumnInfo(1, "EventList", ColumnSize.Event),
});
tableInfos[(int)Table.EventPtr] = new TableInfo(Table.EventPtr, "EventPtr", new ColumnInfo[] {
new ColumnInfo(0, "Event", ColumnSize.Event),
});
tableInfos[(int)Table.Event] = new TableInfo(Table.Event, "Event", new ColumnInfo[] {
new ColumnInfo(0, "EventFlags", ColumnSize.UInt16),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "EventType", ColumnSize.TypeDefOrRef),
});
tableInfos[(int)Table.PropertyMap] = new TableInfo(Table.PropertyMap, "PropertyMap", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.TypeDef),
new ColumnInfo(1, "PropertyList", ColumnSize.Property),
});
tableInfos[(int)Table.PropertyPtr] = new TableInfo(Table.PropertyPtr, "PropertyPtr", new ColumnInfo[] {
new ColumnInfo(0, "Property", ColumnSize.Property),
});
tableInfos[(int)Table.Property] = new TableInfo(Table.Property, "Property", new ColumnInfo[] {
new ColumnInfo(0, "PropFlags", ColumnSize.UInt16),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "Type", ColumnSize.Blob),
});
tableInfos[(int)Table.MethodSemantics] = new TableInfo(Table.MethodSemantics, "MethodSemantics", new ColumnInfo[] {
new ColumnInfo(0, "Semantic", ColumnSize.UInt16),
new ColumnInfo(1, "Method", ColumnSize.Method),
new ColumnInfo(2, "Association", ColumnSize.HasSemantic),
});
tableInfos[(int)Table.MethodImpl] = new TableInfo(Table.MethodImpl, "MethodImpl", new ColumnInfo[] {
new ColumnInfo(0, "Class", ColumnSize.TypeDef),
new ColumnInfo(1, "MethodBody", ColumnSize.MethodDefOrRef),
new ColumnInfo(2, "MethodDeclaration", ColumnSize.MethodDefOrRef),
});
tableInfos[(int)Table.ModuleRef] = new TableInfo(Table.ModuleRef, "ModuleRef", new ColumnInfo[] {
new ColumnInfo(0, "Name", ColumnSize.Strings),
});
tableInfos[(int)Table.TypeSpec] = new TableInfo(Table.TypeSpec, "TypeSpec", new ColumnInfo[] {
new ColumnInfo(0, "Signature", ColumnSize.Blob),
});
tableInfos[(int)Table.ImplMap] = new TableInfo(Table.ImplMap, "ImplMap", new ColumnInfo[] {
new ColumnInfo(0, "MappingFlags", ColumnSize.UInt16),
new ColumnInfo(1, "MemberForwarded", ColumnSize.MemberForwarded),
new ColumnInfo(2, "ImportName", ColumnSize.Strings),
new ColumnInfo(3, "ImportScope", ColumnSize.ModuleRef),
});
tableInfos[(int)Table.FieldRVA] = new TableInfo(Table.FieldRVA, "FieldRVA", new ColumnInfo[] {
new ColumnInfo(0, "RVA", ColumnSize.UInt32),
new ColumnInfo(1, "Field", ColumnSize.Field),
});
tableInfos[(int)Table.ENCLog] = new TableInfo(Table.ENCLog, "ENCLog", new ColumnInfo[] {
new ColumnInfo(0, "Token", ColumnSize.UInt32),
new ColumnInfo(1, "FuncCode", ColumnSize.UInt32),
});
tableInfos[(int)Table.ENCMap] = new TableInfo(Table.ENCMap, "ENCMap", new ColumnInfo[] {
new ColumnInfo(0, "Token", ColumnSize.UInt32),
});
tableInfos[(int)Table.Assembly] = new TableInfo(Table.Assembly, "Assembly", new ColumnInfo[] {
new ColumnInfo(0, "HashAlgId", ColumnSize.UInt32),
new ColumnInfo(1, "MajorVersion", ColumnSize.UInt16),
new ColumnInfo(2, "MinorVersion", ColumnSize.UInt16),
new ColumnInfo(3, "BuildNumber", ColumnSize.UInt16),
new ColumnInfo(4, "RevisionNumber", ColumnSize.UInt16),
new ColumnInfo(5, "Flags", ColumnSize.UInt32),
new ColumnInfo(6, "PublicKey", ColumnSize.Blob),
new ColumnInfo(7, "Name", ColumnSize.Strings),
new ColumnInfo(8, "Locale", ColumnSize.Strings),
});
tableInfos[(int)Table.AssemblyProcessor] = new TableInfo(Table.AssemblyProcessor, "AssemblyProcessor", new ColumnInfo[] {
new ColumnInfo(0, "Processor", ColumnSize.UInt32),
});
tableInfos[(int)Table.AssemblyOS] = new TableInfo(Table.AssemblyOS, "AssemblyOS", new ColumnInfo[] {
new ColumnInfo(0, "OSPlatformId", ColumnSize.UInt32),
new ColumnInfo(1, "OSMajorVersion", ColumnSize.UInt32),
new ColumnInfo(2, "OSMinorVersion", ColumnSize.UInt32),
});
tableInfos[(int)Table.AssemblyRef] = new TableInfo(Table.AssemblyRef, "AssemblyRef", new ColumnInfo[] {
new ColumnInfo(0, "MajorVersion", ColumnSize.UInt16),
new ColumnInfo(1, "MinorVersion", ColumnSize.UInt16),
new ColumnInfo(2, "BuildNumber", ColumnSize.UInt16),
new ColumnInfo(3, "RevisionNumber", ColumnSize.UInt16),
new ColumnInfo(4, "Flags", ColumnSize.UInt32),
new ColumnInfo(5, "PublicKeyOrToken", ColumnSize.Blob),
new ColumnInfo(6, "Name", ColumnSize.Strings),
new ColumnInfo(7, "Locale", ColumnSize.Strings),
new ColumnInfo(8, "HashValue", ColumnSize.Blob),
});
tableInfos[(int)Table.AssemblyRefProcessor] = new TableInfo(Table.AssemblyRefProcessor, "AssemblyRefProcessor", new ColumnInfo[] {
new ColumnInfo(0, "Processor", ColumnSize.UInt32),
new ColumnInfo(1, "AssemblyRef", ColumnSize.AssemblyRef),
});
tableInfos[(int)Table.AssemblyRefOS] = new TableInfo(Table.AssemblyRefOS, "AssemblyRefOS", new ColumnInfo[] {
new ColumnInfo(0, "OSPlatformId", ColumnSize.UInt32),
new ColumnInfo(1, "OSMajorVersion", ColumnSize.UInt32),
new ColumnInfo(2, "OSMinorVersion", ColumnSize.UInt32),
new ColumnInfo(3, "AssemblyRef", ColumnSize.AssemblyRef),
});
tableInfos[(int)Table.File] = new TableInfo(Table.File, "File", new ColumnInfo[] {
new ColumnInfo(0, "Flags", ColumnSize.UInt32),
new ColumnInfo(1, "Name", ColumnSize.Strings),
new ColumnInfo(2, "HashValue", ColumnSize.Blob),
});
tableInfos[(int)Table.ExportedType] = new TableInfo(Table.ExportedType, "ExportedType", new ColumnInfo[] {
new ColumnInfo(0, "Flags", ColumnSize.UInt32),
new ColumnInfo(1, "TypeDefId", ColumnSize.UInt32),
new ColumnInfo(2, "TypeName", ColumnSize.Strings),
new ColumnInfo(3, "TypeNamespace", ColumnSize.Strings),
new ColumnInfo(4, "Implementation", ColumnSize.Implementation),
});
tableInfos[(int)Table.ManifestResource] = new TableInfo(Table.ManifestResource, "ManifestResource", new ColumnInfo[] {
new ColumnInfo(0, "Offset", ColumnSize.UInt32),
new ColumnInfo(1, "Flags", ColumnSize.UInt32),
new ColumnInfo(2, "Name", ColumnSize.Strings),
new ColumnInfo(3, "Implementation", ColumnSize.Implementation),
});
tableInfos[(int)Table.NestedClass] = new TableInfo(Table.NestedClass, "NestedClass", new ColumnInfo[] {
new ColumnInfo(0, "NestedClass", ColumnSize.TypeDef),
new ColumnInfo(1, "EnclosingClass", ColumnSize.TypeDef),
});
if (majorVersion == 1 && minorVersion == 1) {
tableInfos[(int)Table.GenericParam] = new TableInfo(Table.GenericParam, "GenericParam", new ColumnInfo[] {
new ColumnInfo(0, "Number", ColumnSize.UInt16),
new ColumnInfo(1, "Flags", ColumnSize.UInt16),
new ColumnInfo(2, "Owner", ColumnSize.TypeOrMethodDef),
new ColumnInfo(3, "Name", ColumnSize.Strings),
new ColumnInfo(4, "Kind", ColumnSize.TypeDefOrRef),
});
}
else {
tableInfos[(int)Table.GenericParam] = new TableInfo(Table.GenericParam, "GenericParam", new ColumnInfo[] {
new ColumnInfo(0, "Number", ColumnSize.UInt16),
new ColumnInfo(1, "Flags", ColumnSize.UInt16),
new ColumnInfo(2, "Owner", ColumnSize.TypeOrMethodDef),
new ColumnInfo(3, "Name", ColumnSize.Strings),
});
}
tableInfos[(int)Table.MethodSpec] = new TableInfo(Table.MethodSpec, "MethodSpec", new ColumnInfo[] {
new ColumnInfo(0, "Method", ColumnSize.MethodDefOrRef),
new ColumnInfo(1, "Instantiation", ColumnSize.Blob),
});
tableInfos[(int)Table.GenericParamConstraint] = new TableInfo(Table.GenericParamConstraint, "GenericParamConstraint", new ColumnInfo[] {
new ColumnInfo(0, "Owner", ColumnSize.GenericParam),
new ColumnInfo(1, "Constraint", ColumnSize.TypeDefOrRef),
});
tableInfos[0x2D] = new TableInfo((Table)0x2D, string.Empty, new ColumnInfo[] { });
tableInfos[0x2E] = new TableInfo((Table)0x2E, string.Empty, new ColumnInfo[] { });
tableInfos[0x2F] = new TableInfo((Table)0x2F, string.Empty, new ColumnInfo[] { });
tableInfos[(int)Table.Document] = new TableInfo(Table.Document, "Document", new ColumnInfo[] {
new ColumnInfo(0, "Name", ColumnSize.Blob),
new ColumnInfo(1, "HashAlgorithm", ColumnSize.GUID),
new ColumnInfo(2, "Hash", ColumnSize.Blob),
new ColumnInfo(3, "Language", ColumnSize.GUID),
});
tableInfos[(int)Table.MethodDebugInformation] = new TableInfo(Table.MethodDebugInformation, "MethodDebugInformation", new ColumnInfo[] {
new ColumnInfo(0, "Document", ColumnSize.Document),
new ColumnInfo(1, "SequencePoints", ColumnSize.Blob),
});
tableInfos[(int)Table.LocalScope] = new TableInfo(Table.LocalScope, "LocalScope", new ColumnInfo[] {
new ColumnInfo(0, "Method", ColumnSize.Method),
new ColumnInfo(1, "ImportScope", ColumnSize.ImportScope),
new ColumnInfo(2, "VariableList", ColumnSize.LocalVariable),
new ColumnInfo(3, "ConstantList", ColumnSize.LocalConstant),
new ColumnInfo(4, "StartOffset", ColumnSize.UInt32),
new ColumnInfo(5, "Length", ColumnSize.UInt32),
});
tableInfos[(int)Table.LocalVariable] = new TableInfo(Table.LocalVariable, "LocalVariable", new ColumnInfo[] {
new ColumnInfo(0, "Attributes", ColumnSize.UInt16),
new ColumnInfo(1, "Index", ColumnSize.UInt16),
new ColumnInfo(2, "Name", ColumnSize.Strings),
});
tableInfos[(int)Table.LocalConstant] = new TableInfo(Table.LocalConstant, "LocalConstant", new ColumnInfo[] {
new ColumnInfo(0, "Name", ColumnSize.Strings),
new ColumnInfo(1, "Signature", ColumnSize.Blob),
});
tableInfos[(int)Table.ImportScope] = new TableInfo(Table.ImportScope, "ImportScope", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.ImportScope),
new ColumnInfo(1, "Imports", ColumnSize.Blob),
});
tableInfos[(int)Table.StateMachineMethod] = new TableInfo(Table.StateMachineMethod, "StateMachineMethod", new ColumnInfo[] {
new ColumnInfo(0, "MoveNextMethod", ColumnSize.Method),
new ColumnInfo(1, "KickoffMethod", ColumnSize.Method),
});
tableInfos[(int)Table.CustomDebugInformation] = new TableInfo(Table.CustomDebugInformation, "CustomDebugInformation", new ColumnInfo[] {
new ColumnInfo(0, "Parent", ColumnSize.HasCustomDebugInformation),
new ColumnInfo(1, "Kind", ColumnSize.GUID),
new ColumnInfo(2, "Value", ColumnSize.Blob),
});
return this.tableInfos = tableInfos;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
namespace System.Xml
{
internal partial class XsdCachingReader : XmlReader, IXmlLineInfo
{
private enum CachingReaderState
{
None = 0,
Init = 1,
Record = 2,
Replay = 3,
ReaderClosed = 4,
Error = 5,
}
private XmlReader _coreReader;
private XmlNameTable _coreReaderNameTable;
private ValidatingReaderNodeData[] _contentEvents;
private ValidatingReaderNodeData[] _attributeEvents;
private ValidatingReaderNodeData _cachedNode;
private CachingReaderState _cacheState;
private int _contentIndex;
private int _attributeCount;
private bool _returnOriginalStringValues;
private CachingEventHandler _cacheHandler;
//current state
private int _currentAttrIndex;
private int _currentContentIndex;
private bool _readAhead;
//Lineinfo
private IXmlLineInfo _lineInfo;
//ReadAttributeValue TextNode
private ValidatingReaderNodeData _textNode;
//Constants
private const int InitialAttributeCount = 8;
private const int InitialContentCount = 4;
//Constructor
internal XsdCachingReader(XmlReader reader, IXmlLineInfo lineInfo, CachingEventHandler handlerMethod)
{
_coreReader = reader;
_lineInfo = lineInfo;
_cacheHandler = handlerMethod;
_attributeEvents = new ValidatingReaderNodeData[InitialAttributeCount];
_contentEvents = new ValidatingReaderNodeData[InitialContentCount];
Init();
}
private void Init()
{
_coreReaderNameTable = _coreReader.NameTable;
_cacheState = CachingReaderState.Init;
_contentIndex = 0;
_currentAttrIndex = -1;
_currentContentIndex = -1;
_attributeCount = 0;
_cachedNode = null;
_readAhead = false;
//Initialize the cachingReader with start state
if (_coreReader.NodeType == XmlNodeType.Element)
{
ValidatingReaderNodeData element = AddContent(_coreReader.NodeType);
element.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth); //Only created for element node type
element.SetLineInfo(_lineInfo);
RecordAttributes();
}
}
internal void Reset(XmlReader reader)
{
_coreReader = reader;
Init();
}
// Settings
public override XmlReaderSettings Settings
{
get
{
return _coreReader.Settings;
}
}
// Node Properties
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get
{
return _cachedNode.NodeType;
}
}
// Gets the name of the current node, including the namespace prefix.
public override string Name
{
get
{
return _cachedNode.GetAtomizedNameWPrefix(_coreReaderNameTable);
}
}
// Gets the name of the current node without the namespace prefix.
public override string LocalName
{
get
{
return _cachedNode.LocalName;
}
}
// Gets the namespace URN (as defined in the W3C Namespace Specification) of the current namespace scope.
public override string NamespaceURI
{
get
{
return _cachedNode.Namespace;
}
}
// Gets the namespace prefix associated with the current node.
public override string Prefix
{
get
{
return _cachedNode.Prefix;
}
}
// Gets a value indicating whether the current node can have a non-empty Value.
public override bool HasValue
{
get
{
return XmlReader.HasValueInternal(_cachedNode.NodeType);
}
}
// Gets the text value of the current node.
public override string Value
{
get
{
return _returnOriginalStringValues ? _cachedNode.OriginalStringValue : _cachedNode.RawValue;
}
}
// Gets the depth of the current node in the XML element stack.
public override int Depth
{
get
{
return _cachedNode.Depth;
}
}
// Gets the base URI of the current node.
public override string BaseURI
{
get
{
return _coreReader.BaseURI;
}
}
// Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
public override bool IsEmptyElement
{
get
{
return false;
}
}
// Gets a value indicating whether the current node is an attribute that was generated from the default value defined
// in the DTD or schema.
public override bool IsDefault
{
get
{
return false;
}
}
// Gets the quotation mark character used to enclose the value of an attribute node.
public override char QuoteChar
{
get
{
return _coreReader.QuoteChar;
}
}
// Gets the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
return _coreReader.XmlSpace;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
get
{
return _coreReader.XmlLang;
}
}
// Attribute Accessors
// The number of attributes on the current node.
public override int AttributeCount
{
get
{
return _attributeCount;
}
}
// Gets the value of the attribute with the specified Name.
public override string GetAttribute(string name)
{
int i;
if (!name.Contains(':'))
{
i = GetAttributeIndexWithoutPrefix(name);
}
else
{
i = GetAttributeIndexWithPrefix(name);
}
return (i >= 0) ? _attributeEvents[i].RawValue : null;
}
// Gets the value of the attribute with the specified LocalName and NamespaceURI.
public override string GetAttribute(string name, string namespaceURI)
{
namespaceURI = (namespaceURI == null) ? string.Empty : _coreReaderNameTable.Get(namespaceURI);
name = _coreReaderNameTable.Get(name);
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) && Ref.Equal(attribute.Namespace, namespaceURI))
{
return attribute.RawValue;
}
}
return null;
}
// Gets the value of the attribute with the specified index.
public override string GetAttribute(int i)
{
if (i < 0 || i >= _attributeCount)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
return _attributeEvents[i].RawValue;
}
// Gets the value of the attribute with the specified index.
public override string this[int i]
{
get
{
return GetAttribute(i);
}
}
// Gets the value of the attribute with the specified LocalName and NamespaceURI.
public override string this[string name, string namespaceURI]
{
get
{
return GetAttribute(name, namespaceURI);
}
}
// Moves to the attribute with the specified Name.
public override bool MoveToAttribute(string name)
{
int i;
if (!name.Contains(':'))
{
i = GetAttributeIndexWithoutPrefix(name);
}
else
{
i = GetAttributeIndexWithPrefix(name);
}
if (i >= 0)
{
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
return true;
}
else
{
return false;
}
}
// Moves to the attribute with the specified LocalName and NamespaceURI
public override bool MoveToAttribute(string name, string ns)
{
ns = (ns == null) ? string.Empty : _coreReaderNameTable.Get(ns);
name = _coreReaderNameTable.Get(name);
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) &&
Ref.Equal(attribute.Namespace, ns))
{
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
return true;
}
}
return false;
}
// Moves to the attribute with the specified index.
public override void MoveToAttribute(int i)
{
if (i < 0 || i >= _attributeCount)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
}
// Moves to the first attribute.
public override bool MoveToFirstAttribute()
{
if (_attributeCount == 0)
{
return false;
}
_currentAttrIndex = 0;
_cachedNode = _attributeEvents[0];
return true;
}
// Moves to the next attribute.
public override bool MoveToNextAttribute()
{
if (_currentAttrIndex + 1 < _attributeCount)
{
_cachedNode = _attributeEvents[++_currentAttrIndex];
return true;
}
return false;
}
// Moves to the element that contains the current attribute node.
public override bool MoveToElement()
{
if (_cacheState != CachingReaderState.Replay || _cachedNode.NodeType != XmlNodeType.Attribute)
{
return false;
}
_currentContentIndex = 0;
_currentAttrIndex = -1;
Read();
return true;
}
// Reads the next node from the stream/TextReader.
public override bool Read()
{
switch (_cacheState)
{
case CachingReaderState.Init:
_cacheState = CachingReaderState.Record;
goto case CachingReaderState.Record;
case CachingReaderState.Record:
ValidatingReaderNodeData recordedNode = null;
if (_coreReader.Read())
{
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
//Dont record element within the content of a union type since the main reader will break on this and the underlying coreReader will be positioned on this node
_cacheState = CachingReaderState.ReaderClosed;
return false;
case XmlNodeType.EndElement:
recordedNode = AddContent(_coreReader.NodeType);
recordedNode.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth); //Only created for element node type
recordedNode.SetLineInfo(_lineInfo);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
recordedNode = AddContent(_coreReader.NodeType);
recordedNode.SetItemData(_coreReader.Value);
recordedNode.SetLineInfo(_lineInfo);
recordedNode.Depth = _coreReader.Depth;
break;
default:
break;
}
_cachedNode = recordedNode;
return true;
}
else
{
_cacheState = CachingReaderState.ReaderClosed;
return false;
}
case CachingReaderState.Replay:
if (_currentContentIndex >= _contentIndex)
{ //When positioned on the last cached node, switch back as the underlying coreReader is still positioned on this node
_cacheState = CachingReaderState.ReaderClosed;
_cacheHandler(this);
if (_coreReader.NodeType != XmlNodeType.Element || _readAhead)
{ //Only when coreReader not positioned on Element node, read ahead, otherwise it is on the next element node already, since this was not cached
return _coreReader.Read();
}
return true;
}
_cachedNode = _contentEvents[_currentContentIndex];
if (_currentContentIndex > 0)
{
ClearAttributesInfo();
}
_currentContentIndex++;
return true;
default:
return false;
}
}
internal ValidatingReaderNodeData RecordTextNode(string textValue, string originalStringValue, int depth, int lineNo, int linePos)
{
ValidatingReaderNodeData textNode = AddContent(XmlNodeType.Text);
textNode.SetItemData(textValue, originalStringValue);
textNode.SetLineInfo(lineNo, linePos);
textNode.Depth = depth;
return textNode;
}
internal void SwitchTextNodeAndEndElement(string textValue, string originalStringValue)
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement || (_coreReader.NodeType == XmlNodeType.Element && _coreReader.IsEmptyElement));
ValidatingReaderNodeData textNode = RecordTextNode(textValue, originalStringValue, _coreReader.Depth + 1, 0, 0);
int endElementIndex = _contentIndex - 2;
ValidatingReaderNodeData endElementNode = _contentEvents[endElementIndex];
Debug.Assert(endElementNode.NodeType == XmlNodeType.EndElement);
_contentEvents[endElementIndex] = textNode;
_contentEvents[_contentIndex - 1] = endElementNode;
}
internal void RecordEndElementNode()
{
ValidatingReaderNodeData recordedNode = AddContent(XmlNodeType.EndElement);
Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement || (_coreReader.NodeType == XmlNodeType.Element && _coreReader.IsEmptyElement));
recordedNode.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth);
recordedNode.SetLineInfo(_coreReader as IXmlLineInfo);
if (_coreReader.IsEmptyElement)
{ //Simulated endElement node for <e/>, the coreReader is on cached Element node itself.
_readAhead = true;
}
}
internal string ReadOriginalContentAsString()
{
_returnOriginalStringValues = true;
string strValue = InternalReadContentAsString();
_returnOriginalStringValues = false;
return strValue;
}
// Gets a value indicating whether XmlReader is positioned at the end of the stream.
public override bool EOF
{
get
{
return _cacheState == CachingReaderState.ReaderClosed && _coreReader.EOF;
}
}
// Closes the stream, changes the ReadState to Closed, and sets all the properties back to zero.
public override void Close()
{
_coreReader.Close();
_cacheState = CachingReaderState.ReaderClosed;
}
// Returns the read state of the stream.
public override ReadState ReadState
{
get
{
return _coreReader.ReadState;
}
}
// Skips to the end tag of the current element.
public override void Skip()
{
//Skip on caching reader should move to the end of the subtree, past all cached events
switch (_cachedNode.NodeType)
{
case XmlNodeType.Element:
if (_coreReader.NodeType != XmlNodeType.EndElement && !_readAhead)
{ //will be true for IsDefault cases where we peek only one node ahead
int startDepth = _coreReader.Depth - 1;
while (_coreReader.Read() && _coreReader.Depth > startDepth)
;
}
_coreReader.Read();
_cacheState = CachingReaderState.ReaderClosed;
_cacheHandler(this);
break;
case XmlNodeType.Attribute:
MoveToElement();
goto case XmlNodeType.Element;
default:
Debug.Assert(_cacheState == CachingReaderState.Replay);
Read();
break;
}
}
// Gets the XmlNameTable associated with this implementation.
public override XmlNameTable NameTable
{
get
{
return _coreReaderNameTable;
}
}
// Resolves a namespace prefix in the current element's scope.
public override string LookupNamespace(string prefix)
{
return _coreReader.LookupNamespace(prefix);
}
// Resolves the entity reference for nodes of NodeType EntityReference.
public override void ResolveEntity()
{
throw new InvalidOperationException();
}
// Parses the attribute value into one or more Text and/or EntityReference node types.
public override bool ReadAttributeValue()
{
Debug.Assert(_cacheState == CachingReaderState.Replay);
if (_cachedNode.NodeType != XmlNodeType.Attribute)
{
return false;
}
_cachedNode = CreateDummyTextNode(_cachedNode.RawValue, _cachedNode.Depth + 1);
return true;
}
//
// IXmlLineInfo members
//
bool IXmlLineInfo.HasLineInfo()
{
return true;
}
int IXmlLineInfo.LineNumber
{
get
{
return _cachedNode.LineNumber;
}
}
int IXmlLineInfo.LinePosition
{
get
{
return _cachedNode.LinePosition;
}
}
//Private methods
internal void SetToReplayMode()
{
_cacheState = CachingReaderState.Replay;
_currentContentIndex = 0;
_currentAttrIndex = -1;
Read(); //Position on first node recorded to begin replaying
}
internal XmlReader GetCoreReader()
{
return _coreReader;
}
internal IXmlLineInfo GetLineInfo()
{
return _lineInfo;
}
private void ClearAttributesInfo()
{
_attributeCount = 0;
_currentAttrIndex = -1;
}
private ValidatingReaderNodeData AddAttribute(int attIndex)
{
Debug.Assert(attIndex <= _attributeEvents.Length);
ValidatingReaderNodeData attInfo = _attributeEvents[attIndex];
if (attInfo != null)
{
attInfo.Clear(XmlNodeType.Attribute);
return attInfo;
}
if (attIndex >= _attributeEvents.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
ValidatingReaderNodeData[] newAttributeEvents = new ValidatingReaderNodeData[_attributeEvents.Length * 2];
Array.Copy(_attributeEvents, 0, newAttributeEvents, 0, _attributeEvents.Length);
_attributeEvents = newAttributeEvents;
}
attInfo = _attributeEvents[attIndex];
if (attInfo == null)
{
attInfo = new ValidatingReaderNodeData(XmlNodeType.Attribute);
_attributeEvents[attIndex] = attInfo;
}
return attInfo;
}
private ValidatingReaderNodeData AddContent(XmlNodeType nodeType)
{
Debug.Assert(_contentIndex <= _contentEvents.Length);
ValidatingReaderNodeData contentInfo = _contentEvents[_contentIndex];
if (contentInfo != null)
{
contentInfo.Clear(nodeType);
_contentIndex++;
return contentInfo;
}
if (_contentIndex >= _contentEvents.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
ValidatingReaderNodeData[] newContentEvents = new ValidatingReaderNodeData[_contentEvents.Length * 2];
Array.Copy(_contentEvents, 0, newContentEvents, 0, _contentEvents.Length);
_contentEvents = newContentEvents;
}
contentInfo = _contentEvents[_contentIndex];
if (contentInfo == null)
{
contentInfo = new ValidatingReaderNodeData(nodeType);
_contentEvents[_contentIndex] = contentInfo;
}
_contentIndex++;
return contentInfo;
}
private void RecordAttributes()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.Element);
ValidatingReaderNodeData attInfo;
_attributeCount = _coreReader.AttributeCount;
if (_coreReader.MoveToFirstAttribute())
{
int attIndex = 0;
do
{
attInfo = AddAttribute(attIndex);
attInfo.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth);
attInfo.SetLineInfo(_lineInfo);
attInfo.RawValue = _coreReader.Value;
attIndex++;
} while (_coreReader.MoveToNextAttribute());
_coreReader.MoveToElement();
}
}
private int GetAttributeIndexWithoutPrefix(string name)
{
name = _coreReaderNameTable.Get(name);
if (name == null)
{
return -1;
}
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) && attribute.Prefix.Length == 0)
{
return i;
}
}
return -1;
}
private int GetAttributeIndexWithPrefix(string name)
{
name = _coreReaderNameTable.Get(name);
if (name == null)
{
return -1;
}
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.GetAtomizedNameWPrefix(_coreReaderNameTable), name))
{
return i;
}
}
return -1;
}
private ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth)
{
if (_textNode == null)
{
_textNode = new ValidatingReaderNodeData(XmlNodeType.Text);
}
_textNode.Depth = depth;
_textNode.RawValue = attributeValue;
return _textNode;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class DockContent : Form, IDockContent
{
public DockContent()
{
m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString));
m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged);
}
private DockContentHandler m_dockHandler = null;
[Browsable(false)]
public DockContentHandler DockHandler
{
get { return m_dockHandler; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get { return DockHandler.AllowEndUserDocking; }
set { DockHandler.AllowEndUserDocking = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_DockAreas_Description")]
[DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)]
public DockAreas DockAreas
{
get { return DockHandler.DockAreas; }
set { DockHandler.DockAreas = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AutoHidePortion_Description")]
[DefaultValue(0.25)]
public double AutoHidePortion
{
get { return DockHandler.AutoHidePortion; }
set { DockHandler.AutoHidePortion = value; }
}
[Localizable(true)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabText_Description")]
[DefaultValue(null)]
public string TabText
{
get { return DockHandler.TabText; }
set { DockHandler.TabText = value; }
}
private bool ShouldSerializeTabText()
{
return (DockHandler.TabText != null);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButton_Description")]
[DefaultValue(true)]
public bool CloseButton
{
get { return DockHandler.CloseButton; }
set { DockHandler.CloseButton = value; }
}
[Browsable(false)]
public DockPanel DockPanel
{
get { return DockHandler.DockPanel; }
set { DockHandler.DockPanel = value; }
}
[Browsable(false)]
public DockState DockState
{
get { return DockHandler.DockState; }
set { DockHandler.DockState = value; }
}
[Browsable(false)]
public DockPane Pane
{
get { return DockHandler.Pane; }
set { DockHandler.Pane = value; }
}
[Browsable(false)]
public bool IsHidden
{
get { return DockHandler.IsHidden; }
set { DockHandler.IsHidden = value; }
}
[Browsable(false)]
public DockState VisibleState
{
get { return DockHandler.VisibleState; }
set { DockHandler.VisibleState = value; }
}
[Browsable(false)]
public bool IsFloat
{
get { return DockHandler.IsFloat; }
set { DockHandler.IsFloat = value; }
}
[Browsable(false)]
public DockPane PanelPane
{
get { return DockHandler.PanelPane; }
set { DockHandler.PanelPane = value; }
}
[Browsable(false)]
public DockPane FloatPane
{
get { return DockHandler.FloatPane; }
set { DockHandler.FloatPane = value; }
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
protected virtual string GetPersistString()
{
return GetType().ToString();
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_HideOnClose_Description")]
[DefaultValue(false)]
public bool HideOnClose
{
get { return DockHandler.HideOnClose; }
set { DockHandler.HideOnClose = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_ShowHint_Description")]
[DefaultValue(DockState.Unknown)]
public DockState ShowHint
{
get { return DockHandler.ShowHint; }
set { DockHandler.ShowHint = value; }
}
[Browsable(false)]
public bool IsActivated
{
get { return DockHandler.IsActivated; }
}
public bool IsDockStateValid(DockState dockState)
{
return DockHandler.IsDockStateValid(dockState);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenu_Description")]
[DefaultValue(null)]
public ContextMenu TabPageContextMenu
{
get { return DockHandler.TabPageContextMenu; }
set { DockHandler.TabPageContextMenu = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")]
[DefaultValue(null)]
public ContextMenuStrip TabPageContextMenuStrip
{
get { return DockHandler.TabPageContextMenuStrip; }
set { DockHandler.TabPageContextMenuStrip = value; }
}
[Localizable(true)]
[Category("Appearance")]
[LocalizedDescription("DockContent_ToolTipText_Description")]
[DefaultValue(null)]
public string ToolTipText
{
get { return DockHandler.ToolTipText; }
set { DockHandler.ToolTipText = value; }
}
public new void Activate()
{
DockHandler.Activate();
}
public new void Hide()
{
DockHandler.Hide();
}
public new void Show()
{
DockHandler.Show();
}
public void Show(DockPanel dockPanel)
{
DockHandler.Show(dockPanel);
}
public void Show(DockPanel dockPanel, DockState dockState)
{
DockHandler.Show(dockPanel, dockState);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void Show(DockPanel dockPanel, Rectangle floatWindowBounds)
{
DockHandler.Show(dockPanel, floatWindowBounds);
}
public void Show(DockPane pane, IDockContent beforeContent)
{
DockHandler.Show(pane, beforeContent);
}
public void Show(DockPane previousPane, DockAlignment alignment, double proportion)
{
DockHandler.Show(previousPane, alignment, proportion);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void FloatAt(Rectangle floatWindowBounds)
{
DockHandler.FloatAt(floatWindowBounds);
}
public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex)
{
DockHandler.DockTo(paneTo, dockStyle, contentIndex);
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
DockHandler.DockTo(panel, dockStyle);
}
/// <summary>
/// setup and display save dialog and return dialog result and filename.
/// </summary>
/// <param name="fileName"></param>
/// <param name="saveDialogTitle"></param>
/// <param name="filter"></param>
/// <returns></returns>
public ArrayList ShowSaveFileDialog(string fileName, string saveDialogTitle, string filter)
{
ArrayList arl = new ArrayList();
if (fileName == null)
{
MessageBox.Show("Null filename ", "Bad Filename", MessageBoxButtons.OK, MessageBoxIcon.Warning);
fileName = string.Empty;
}
else if (fileName != string.Empty)
{
try
{
FileInfo fi = new FileInfo(fileName);
fileName = fi.FullName;
}
catch//(Exception ex)
{
MessageBox.Show("Problem with filename: " + fileName, "Bad Filename", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
string extension = filter != null && filter.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Length > 0 ? filter.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0] : "";
filter = filter == null ? "All files (*.*)|*.*" : filter;
saveDialogTitle = saveDialogTitle == null ? "Save File As..." : saveDialogTitle;
SaveFileDialog fd = new SaveFileDialog();
fd.RestoreDirectory = true;
fd.FileName = fileName;
fd.Title = saveDialogTitle;
fd.DefaultExt = extension;
fd.Filter = filter;
fd.FilterIndex = 1;
fd.AddExtension = true;
fd.CheckFileExists = false;
fd.CheckPathExists = true;
DialogResult dr = fd.ShowDialog(this);
arl.Add(dr);
arl.Add(fd.FileName);
return arl;
}
public ArrayList ShowOpenFileDialog(string fileName, string saveDialogTitle, string filter)
{
fileName = fileName == null ? "" : fileName;
string extension = filter != null && filter.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Length > 0 ? filter.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0] : "";
filter = filter == null ? "All files (*.*)|*.*" : filter;
OpenFileDialog fd = new OpenFileDialog();
fd.RestoreDirectory = true;
fd.FileName = fileName;
fd.Title = saveDialogTitle;
fd.DefaultExt = extension;
fd.Filter = filter;
fd.FilterIndex = 1;
fd.AddExtension = true;
fd.CheckFileExists = false;
fd.CheckPathExists = true;
DialogResult dr = fd.ShowDialog(this);
ArrayList arl = new ArrayList();
arl.Add(dr);
arl.Add(fd.FileName);
return arl;
}
#region Events
private void DockHandler_DockStateChanged(object sender, EventArgs e)
{
OnDockStateChanged(e);
}
private static readonly object DockStateChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("Pane_DockStateChanged_Description")]
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ServerCommunicationLinkOperationsExtensions
{
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// communication. To determine the status of the operation call
/// GetServerCommunicationLinkOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse BeginCreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// communication. To determine the status of the operation call
/// GetServerCommunicationLinkOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server communication
/// link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse CreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server communication
/// link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> CreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the Azure SQL server communication link with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).DeleteAsync(resourceGroupName, serverName, communicationLinkName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the Azure SQL server communication link with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return operations.DeleteAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a get server communication link request.
/// </returns>
public static ServerCommunicationLinkGetResponse Get(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).GetAsync(resourceGroupName, serverName, communicationLinkName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a get server communication link request.
/// </returns>
public static Task<ServerCommunicationLinkGetResponse> GetAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return operations.GetAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Server communication link create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse GetServerCommunicationLinkOperationStatus(this IServerCommunicationLinkOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).GetServerCommunicationLinkOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Server communication link create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> GetServerCommunicationLinkOperationStatusAsync(this IServerCommunicationLinkOperations operations, string operationStatusLink)
{
return operations.GetServerCommunicationLinkOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns information about Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server communication
/// link request.
/// </returns>
public static ServerCommunicationLinkListResponse List(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).ListAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server communication
/// link request.
/// </returns>
public static Task<ServerCommunicationLinkListResponse> ListAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName)
{
return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using Microsoft.Win32.SafeHandles;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
public partial class RSA : AsymmetricAlgorithm
{
public static RSA Create()
{
return new RSAImplementation.RSAOpenSsl();
}
}
internal static partial class RSAImplementation
{
#endif
public sealed partial class RSAOpenSsl : RSA
{
private const int BitsPerByte = 8;
// 65537 (0x10001) in big-endian form
private static readonly byte[] s_defaultExponent = { 0x01, 0x00, 0x01 };
private Lazy<SafeRsaHandle> _key;
public RSAOpenSsl()
: this(2048)
{
}
public RSAOpenSsl(int keySize)
{
KeySize = keySize;
_key = new Lazy<SafeRsaHandle>(GenerateKey);
}
public override int KeySize
{
set
{
if (KeySize == value)
{
return;
}
// Set the KeySize before FreeKey so that an invalid value doesn't throw away the key
base.KeySize = value;
FreeKey();
_key = new Lazy<SafeRsaHandle>(GenerateKey);
}
}
private void ForceSetKeySize(int newKeySize)
{
// In the event that a key was loaded via ImportParameters or an IntPtr/SafeHandle
// it could be outside of the bounds that we currently represent as "legal key sizes".
// Since that is our view into the underlying component it can be detached from the
// component's understanding. If it said it has opened a key, and this is the size, trust it.
KeySizeValue = newKeySize;
}
public override KeySizes[] LegalKeySizes
{
get
{
// OpenSSL seems to accept answers of all sizes.
// Choosing a non-multiple of 8 would make some calculations misalign
// (like assertions of (output.Length * 8) == KeySize).
// Choosing a number too small is insecure.
// Choosing a number too large will cause GenerateKey to take much
// longer than anyone would be willing to wait.
//
// So, copying the values from RSACryptoServiceProvider
return new[] { new KeySizes(384, 16384, 8) };
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding);
SafeRsaHandle key = _key.Value;
CheckInvalidKey(key);
byte[] buf = new byte[Interop.Crypto.RsaSize(key)];
int returnValue = Interop.Crypto.RsaPrivateDecrypt(
data.Length,
data,
buf,
key,
rsaPadding);
CheckReturn(returnValue);
// If the padding mode is RSA_NO_PADDING then the size of the decrypted block
// will be RSA_size, so let's just return buf.
//
// If any padding was used, then some amount (determined by the padding algorithm)
// will have been reduced, and only returnValue bytes were part of the decrypted
// body, so copy the decrypted bytes to an appropriately sized array before
// returning it.
if (returnValue == buf.Length)
{
return buf;
}
byte[] plainBytes = new byte[returnValue];
Buffer.BlockCopy(buf, 0, plainBytes, 0, returnValue);
return plainBytes;
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding);
SafeRsaHandle key = _key.Value;
CheckInvalidKey(key);
byte[] buf = new byte[Interop.Crypto.RsaSize(key)];
int returnValue = Interop.Crypto.RsaPublicEncrypt(
data.Length,
data,
buf,
key,
rsaPadding);
CheckReturn(returnValue);
return buf;
}
private static Interop.Crypto.RsaPadding GetInteropPadding(RSAEncryptionPadding padding)
{
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Interop.Crypto.RsaPadding.Pkcs1;
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Interop.Crypto.RsaPadding.OaepSHA1;
}
else
{
throw PaddingModeNotSupported();
}
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
// It's entirely possible that this line will cause the key to be generated in the first place.
SafeRsaHandle key = _key.Value;
CheckInvalidKey(key);
RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(key, includePrivateParameters);
bool hasPrivateKey = rsaParameters.D != null;
if (hasPrivateKey != includePrivateParameters || !HasConsistentPrivateKey(ref rsaParameters))
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return rsaParameters;
}
public override void ImportParameters(RSAParameters parameters)
{
ValidateParameters(ref parameters);
SafeRsaHandle key = Interop.Crypto.RsaCreate();
bool imported = false;
Interop.Crypto.CheckValidOpenSslHandle(key);
try
{
Interop.Crypto.SetRsaParameters(
key,
parameters.Modulus,
parameters.Modulus != null ? parameters.Modulus.Length : 0,
parameters.Exponent,
parameters.Exponent != null ? parameters.Exponent.Length : 0,
parameters.D,
parameters.D != null ? parameters.D.Length : 0,
parameters.P,
parameters.P != null ? parameters.P.Length : 0,
parameters.DP,
parameters.DP != null ? parameters.DP.Length : 0,
parameters.Q,
parameters.Q != null ? parameters.Q.Length : 0,
parameters.DQ,
parameters.DQ != null ? parameters.DQ.Length : 0,
parameters.InverseQ,
parameters.InverseQ != null ? parameters.InverseQ.Length : 0);
imported = true;
}
finally
{
if (!imported)
{
key.Dispose();
}
}
FreeKey();
_key = new Lazy<SafeRsaHandle>(() => key, isThreadSafe:true);
// Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere
// with the already loaded key.
ForceSetKeySize(BitsPerByte * Interop.Crypto.RsaSize(key));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
FreeKey();
}
base.Dispose(disposing);
}
private void FreeKey()
{
if (_key != null && _key.IsValueCreated)
{
SafeRsaHandle handle = _key.Value;
if (handle != null)
{
handle.Dispose();
}
}
}
private static void ValidateParameters(ref RSAParameters parameters)
{
if (parameters.Modulus == null || parameters.Exponent == null)
throw new CryptographicException(SR.Argument_InvalidValue);
if (!HasConsistentPrivateKey(ref parameters))
throw new CryptographicException(SR.Argument_InvalidValue);
}
private static bool HasConsistentPrivateKey(ref RSAParameters parameters)
{
if (parameters.D == null)
{
if (parameters.P != null ||
parameters.DP != null ||
parameters.Q != null ||
parameters.DQ != null ||
parameters.InverseQ != null)
{
return false;
}
}
else
{
if (parameters.P == null ||
parameters.DP == null ||
parameters.Q == null ||
parameters.DQ == null ||
parameters.InverseQ == null)
{
return false;
}
}
return true;
}
private static void CheckInvalidKey(SafeRsaHandle key)
{
if (key == null || key.IsInvalid)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
}
private static void CheckReturn(int returnValue)
{
if (returnValue == -1)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
private static void CheckBoolReturn(int returnValue)
{
if (returnValue == 1)
{
return;
}
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
private SafeRsaHandle GenerateKey()
{
SafeRsaHandle key = Interop.Crypto.RsaCreate();
bool generated = false;
Interop.Crypto.CheckValidOpenSslHandle(key);
try
{
using (SafeBignumHandle exponent = Interop.Crypto.CreateBignum(s_defaultExponent))
{
// The documentation for RSA_generate_key_ex does not say that it returns only
// 0 or 1, so the call marshals it back as a full Int32 and checks for a value
// of 1 explicitly.
int response = Interop.Crypto.RsaGenerateKeyEx(
key,
KeySize,
exponent);
CheckBoolReturn(response);
generated = true;
}
}
finally
{
if (!generated)
{
key.Dispose();
}
}
return key;
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
return OpenSslAsymmetricAlgorithmCore.HashData(data, offset, count, hashAlgorithm);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
return OpenSslAsymmetricAlgorithmCore.HashData(data, hashAlgorithm);
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return SignHash(hash, hashAlgorithm);
}
private byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithmName)
{
int algorithmNid = GetAlgorithmNid(hashAlgorithmName);
SafeRsaHandle rsa = _key.Value;
byte[] signature = new byte[Interop.Crypto.RsaSize(rsa)];
int signatureSize;
bool success = Interop.Crypto.RsaSign(
algorithmNid,
hash,
hash.Length,
signature,
out signatureSize,
rsa);
if (!success)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
Debug.Assert(
signatureSize == signature.Length,
"RSA_sign reported an unexpected signature size",
"RSA_sign reported signatureSize was {0}, when {1} was expected",
signatureSize,
signature.Length);
return signature;
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return VerifyHash(hash, signature, hashAlgorithm);
}
private bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithmName)
{
int algorithmNid = GetAlgorithmNid(hashAlgorithmName);
SafeRsaHandle rsa = _key.Value;
return Interop.Crypto.RsaVerify(
algorithmNid,
hash,
hash.Length,
signature,
signature.Length,
rsa);
}
private static int GetAlgorithmNid(HashAlgorithmName hashAlgorithmName)
{
// All of the current HashAlgorithmName values correspond to the SN values in OpenSSL 0.9.8.
// If there's ever a new one that doesn't, translate it here.
string sn = hashAlgorithmName.Name;
int nid = Interop.Crypto.ObjSn2Nid(sn);
if (nid == Interop.Crypto.NID_undef)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name);
}
return nid;
}
private static Exception PaddingModeNotSupported()
{
return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
private static Exception HashAlgorithmNameNullOrEmpty()
{
return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}
| |
/*
Copyright(c) 2013 Andrew Fray
Licensed under the MIT license. See the license.txt file for full details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using Object = System.Object;
namespace UnTest {
public class TestRunner {
public struct TestFailure {
public Exception FailureException;
public string SuiteName;
public string TestName;
public string FileName;
public int LineNumber;
public int ColumnNumber;
}
public struct ExecutionResults {
public int TotalTestsRun;
public IEnumerable<TestFailure> Failures;
}
public struct TestFailureMessage {
public string Subject;
public string Body;
}
// returns true if all tests passed
public static bool OutputTestResults(
ExecutionResults failures,
Action<string> writeLine) {
string executedTestsMessage = failures.TotalTestsRun.ToString()
+ " tests executed\n";
if (failures.Failures.Any() == false) {
writeLine(executedTestsMessage + "All tests passed!");
return true;
}
var failureOutput = TestRunner.CalculateFailureString(failures.Failures);
var consoleOutput = new System.Text.StringBuilder();
consoleOutput.Append(executedTestsMessage);
foreach(var failureLine in failureOutput) {
consoleOutput.Append(failureLine.Subject + "\n" + failureLine.Body);
}
writeLine(consoleOutput.ToString());
writeLine(failures.Failures.Count().ToString() + " test(s) failed\n");
return false;
}
// returns number of found tests.
public static int RunTestsInSuite(Type testSuite, List<TestFailure> failureList) {
var methodSearch = BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Static | BindingFlags.Instance;
// setups: find everything in current type,
// and private setups in bases. also any non-private setup in bases
// that aren't virtual.
var setupMethods = new List<MethodInfo>();
setupMethods
.AddRange(testSuite.GetMethods(methodSearch)
.Where(m => m.GetCustomAttributes(false).Any(
att => att.GetType().Name == typeof(TestSetup).Name)));
var chainType = testSuite.BaseType;
while(chainType != null) {
var chainSetups = chainType.GetMethods(
BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)
.Where(m => m.GetCustomAttributes(false).Any(
att => att.GetType().Name == typeof(TestSetup).Name))
.Where(m => m.IsVirtual == false);
setupMethods.AddRange(chainSetups);
chainType = chainType.BaseType;
}
var testMethods = testSuite.GetMethods(methodSearch | BindingFlags.DeclaredOnly)
.Where(m => m.GetCustomAttributes(false).Any(att => att.GetType().Name == typeof(Test).Name))
.ToArray();
return RunTestsInSuite(testSuite, failureList, setupMethods, testMethods);
}
// returns number of found tests
public static int RunTestsInSuite(Type testSuite, List<TestFailure> failureList,
IEnumerable<MethodInfo> setupMethods,
IEnumerable<MethodBase> testMethods) {
var instance = Activator.CreateInstance(testSuite);
return RunTestsInSuite(instance, failureList, setupMethods, testMethods);
}
// returns number of found tests
public static int RunTestsInSuite(Object suiteInstance, List<TestFailure> failureList,
IEnumerable<MethodInfo> setupMethods,
IEnumerable<MethodBase> testMethods) {
foreach(var test in testMethods) {
foreach(var setupMethod in setupMethods) {
setupMethod.Invoke(suiteInstance, null);
}
try {
test.Invoke(suiteInstance, null);
} catch (Exception e) {
var stackTrace = new StackTrace(e.InnerException, true);
var callStack = stackTrace.GetFrames();
var testFrame = GetTestFrameFromCallStack(callStack, test);
failureList.Add(new TestFailure {
FailureException = e.InnerException,
SuiteName = suiteInstance.GetType().Name,
TestName = test.Name,
FileName = testFrame.GetFileName(),
LineNumber = testFrame.GetFileLineNumber(),
ColumnNumber = testFrame.GetFileColumnNumber(),
});
}
}
return testMethods.Count();
}
// returns list of test failures
public static ExecutionResults RunAllTests() {
var testableAssemblies = FindAllTestableAssemblies();
return RunAllTestsInAssemblies (testableAssemblies);
}
public static IEnumerable<Assembly> FilterAssemblies(IEnumerable<Assembly> assembliesToFilter) {
return assembliesToFilter.Where(assembly => s_testableAssemblies.Any(
testableAssembly => assembly.FullName.Contains(testableAssembly)));
}
public static ExecutionResults RunAllTestsInAssemblies(
IEnumerable<Assembly> assembliesToTest) {
var failures = new List<TestFailure>();
int totalTestsRun = 0;
foreach(var testSuite in FindAllTestSuites(assembliesToTest)) {
totalTestsRun += RunTestsInSuite(testSuite, failures);
}
return new ExecutionResults {
TotalTestsRun = totalTestsRun,
Failures = failures
};
}
public static IEnumerable<TestFailureMessage> CalculateFailureString(
IEnumerable<TestFailure> failures) {
yield return new TestFailureMessage {
Subject = failures.Count().ToString() + " test failure(s)"
};
foreach(var failure in failures) {
var failureHeadline = string.Format(
"{0}({1},{2}): error {3}.{4} failed:",
new System.Object[] {
failure.FileName,
failure.LineNumber,
failure.ColumnNumber,
failure.SuiteName,
failure.TestName,
});
yield return new TestFailureMessage {
Subject = failureHeadline,
Body = failure.FailureException.ToString() + "\n"
};
}
}
//////////////////////////////////////////////////
private static string[] s_testableAssemblies = new string [] {
"Assembly-UnityScript-Editor-firstpass",
"Assembly-UnityScript-firstpass",
"Assembly-CSharp-Editor",
"Assembly-CSharp",
};
//////////////////////////////////////////////////
private static IEnumerable<Assembly> FindAllTestableAssemblies() {
return FilterAssemblies(AppDomain.CurrentDomain.GetAssemblies());
}
private static IEnumerable<Type> FindAllTestSuites(
IEnumerable<Assembly> testableAssemblies) {
return testableAssemblies.SelectMany(assembly => FindAllTestSuites(assembly));
}
private static IEnumerable<Type> FindAllTestSuites(
Assembly assemblyToTest) {
var allTypes = assemblyToTest.GetTypes();
foreach(var type in allTypes) {
try {
var allAttributes = type.GetCustomAttributes(false);
if(allAttributes
.Any(attribute => attribute.GetType().Name == typeof(TestSuite).Name)
== false) {
continue;
}
} catch (MissingMethodException) {
continue;
}
yield return type;
}
}
private static StackFrame GetTestFrameFromCallStack(
IEnumerable<StackFrame> callStack, MethodBase testFunction) {
return callStack.Reverse()
.FirstOrDefault(frame => frame.GetMethod() == testFunction);
}
}
}
| |
// <copyright file="TrigonometryTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Trigonometry tests.
/// </summary>
[TestFixture, Category("Functions")]
public class TrigonometryTest
{
/// <summary>
/// Can compute complex cosine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 1.0, 0.0)]
[TestCase(8.388608e6, 0.0, -0.90175467375875928, 0.0)]
[TestCase(-8.388608e6, 0.0, -0.90175467375875928, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 0.99999999999999289, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 0.99999999999999289, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, -0.90175467375876572, -5.1528001100635277e-8)]
[TestCase(-1.19209289550780998537e-7, -8.388608e6, double.PositiveInfinity, double.NegativeInfinity)]
public void CanComputeComplexCosine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Cos();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex sine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, 0.43224820225679778, 0.0)]
[TestCase(-8.388608e6, 0.0, -0.43224820225679778, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.19209289550780998537e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.19209289550780998537e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 0.43224820225680083, -1.0749753400787824e-7)]
[TestCase(-1.19209289550780998537e-7, -8.388608e6, double.NegativeInfinity, double.NegativeInfinity)]
public void CanComputeComplexSine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Sin();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex tangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, -0.47934123862654288, 0.0)]
[TestCase(-8.388608e6, 0.0, 0.47934123862654288, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078157e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078157e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, -0.47934123862653449, 1.4659977233982276e-7)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 0.47934123862653449, -1.4659977233982276e-7)]
public void CanComputeComplexTangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Tan();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute cosecant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(8388608, 2.3134856195559191)]
[TestCase(1.19209289550780998537e-7, 8388608.0000000376)]
[TestCase(-8388608, -2.3134856195559191)]
[TestCase(-1.19209289550780998537e-7, -8388608.0000000376)]
public void CanComputeCosecant(double value, double expected)
{
var actual = Trig.Csc(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute cosine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 1.0)]
[TestCase(8388608, -0.90175467375875928)]
[TestCase(1.19209289550780998537e-7, 0.99999999999999289)]
[TestCase(-8388608, -0.90175467375875928)]
[TestCase(-1.19209289550780998537e-7, 0.99999999999999289)]
public void CanComputeCosine(double value, double expected)
{
var actual = Trig.Cos(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute cotangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(8388608, -2.086196470108229)]
[TestCase(1.19209289550780998537e-7, 8388607.999999978)]
[TestCase(-8388608, 2.086196470108229)]
[TestCase(-1.19209289550780998537e-7, -8388607.999999978)]
public void CanComputeCotangent(double value, double expected)
{
var actual = Trig.Cot(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute hyperbolic cosecant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(8388608, 1.3670377960148449e-3643126)]
[TestCase(1.19209289550780998537e-7, 8388607.9999999978)]
[TestCase(-8388608, -1.3670377960148449e-3643126)]
[TestCase(-1.19209289550780998537e-7, -8388607.9999999978)]
public void CanComputeHyperbolicCosecant(double value, double expected)
{
var actual = Trig.Csch(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute hyperbolic cosine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 1.0)]
[TestCase(8388608, double.PositiveInfinity)]
[TestCase(1.19209289550780998537e-7, 1.0000000000000071)]
[TestCase(-8388608, double.PositiveInfinity)]
[TestCase(-1.19209289550780998537e-7, 1.0000000000000071)]
public void CanComputeHyperbolicCosine(double value, double expected)
{
var actual = Trig.Cosh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 15);
}
/// <summary>
/// Can compute hyperbolic cotangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(8388608, 1.0)]
[TestCase(1.19209289550780998537e-7, 8388608.0000000574)]
[TestCase(-8388608, -1.0)]
[TestCase(-1.19209289550780998537e-7, -8388608.0000000574)]
public void CanComputeHyperbolicCotangent(double value, double expected)
{
var actual = Trig.Coth(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute hyperbolic secant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 1.0)]
[TestCase(8388608, 1.3670377960148449e-3643126)]
[TestCase(1.19209289550780998537e-7, 0.99999999999999289)]
[TestCase(-8388608, 1.3670377960148449e-3643126)]
[TestCase(-1.19209289550780998537e-7, 0.99999999999999289)]
public void CanComputeHyperbolicSecant(double value, double expected)
{
var actual = Trig.Sech(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 15);
}
/// <summary>
/// Can compute hyperbolic sine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(8388608, double.PositiveInfinity)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078128e-7)]
[TestCase(-8388608, double.NegativeInfinity)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078128e-7)]
public void CanComputeHyperbolicSine(double value, double expected)
{
var actual = Trig.Sinh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 15);
}
/// <summary>
/// Can compute hyperbolic tangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(8388608, 1.0)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078043e-7)]
[TestCase(-8388608, -1.0)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078043e-7)]
public void CanComputeHyperbolicTangent(double value, double expected)
{
var actual = Trig.Tanh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 15);
}
/// <summary>
/// Can compute inverse cosecant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(8388608, 1.1920928955078097e-7)]
[TestCase(-8388608, -1.1920928955078097e-7)]
[TestCase(1, 1.5707963267948966)]
[TestCase(-1, -1.5707963267948966)]
public void CanComputeInverseCosecant(double value, double expected)
{
var actual = Trig.Acsc(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute inverse cosine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(1, 0)]
[TestCase(-1, 3.1415926535897931)]
[TestCase(1.19209289550780998537e-7, 1.570796207585607)]
[TestCase(-1.19209289550780998537e-7, 1.5707964460041861)]
public void CanComputeInverseCosine(double value, double expected)
{
var actual = Trig.Acos(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 15);
}
/// <summary>
/// Can compute inverse cotangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 1.5707963267948966)]
[TestCase(8388608, 1.1920928955078069e-7)]
[TestCase(-8388608, -1.1920928955078069e-7)]
[TestCase(1.19209289550780998537e-7, 1.5707962075856071)]
[TestCase(-1.19209289550780998537e-7, -1.5707962075856071)]
public void CanComputeInverseCotangent(double value, double expected)
{
var actual = Trig.Acot(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse hyperbolic cosecant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(8388608, 1.1920928955078097e-7)]
[TestCase(-8388608, -1.1920928955078097e-7)]
[TestCase(1.19209289550780998537e-7, 16.635532333438693)]
[TestCase(-1.19209289550780998537e-7, -16.635532333438693)]
public void CanComputeInverseHyperbolicCosecant(double value, double expected)
{
var actual = Trig.Acsch(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse hyperbolic cosine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(1.0, 0.0)]
[TestCase(8388608, 16.635532333438682)]
public void CanComputeInverseHyperbolicCosine(double value, double expected)
{
var actual = Trig.Acosh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse hyperbolic cotangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(8388608, 1.1920928955078181e-7)]
[TestCase(-8388608, -1.1920928955078181e-7)]
[TestCase(1, double.PositiveInfinity)]
[TestCase(-1, double.NegativeInfinity)]
public void CanComputeInverseHyperbolicCotangent(double value, double expected)
{
var actual = Trig.Acoth(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute inverse hyperbolic secant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0, double.PositiveInfinity)]
[TestCase(0.5, 1.3169578969248167)]
[TestCase(1, 0.0)]
public void CanComputeInverseHyperbolicSecant(double value, double expected)
{
var actual = Trig.Asech(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse hyperbolic sine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(8388608, 16.63553233343869)]
[TestCase(-8388608, -16.63553233343869)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078072e-7)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078072e-7)]
public void CanComputeInverseHyperbolicSine(double value, double expected)
{
var actual = Trig.Asinh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse hyperbolic tangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(1.0, double.PositiveInfinity)]
[TestCase(-1.0, double.NegativeInfinity)]
[TestCase(1.19209289550780998537e-7, 1.19209289550780998537e-7)]
[TestCase(-1.19209289550780998537e-7, -1.19209289550780998537e-7)]
public void CanComputeInverseHyperbolicTangent(double value, double expected)
{
var actual = Trig.Atanh(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute inverse secant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(8388608, 1.5707962075856071)]
[TestCase(-8388608, 1.5707964460041862)]
[TestCase(1.0, 0.0)]
[TestCase(-1.0, 3.1415926535897932)]
public void CanComputeInverseSecant(double value, double expected)
{
var actual = Trig.Asec(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse sine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(1.0, 1.5707963267948966)]
[TestCase(-1.0, -1.5707963267948966)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078128e-7)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078128e-7)]
public void CanComputeInverseSine(double value, double expected)
{
var actual = Trig.Asin(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute inverse tangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(8388608, 1.570796207585607)]
[TestCase(-8388608, -1.570796207585607)]
[TestCase(1.19209289550780998537e-7, 1.19209289550780998537e-7)]
[TestCase(-1.19209289550780998537e-7, -1.19209289550780998537e-7)]
public void CanComputeInverseTangent(double value, double expected)
{
var actual = Trig.Atan(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute secant.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 1.0)]
[TestCase(8388608, -1.1089490624226292)]
[TestCase(1.19209289550780998537e-7, 1.0000000000000071)]
[TestCase(-8388608, -1.1089490624226292)]
[TestCase(-1.19209289550780998537e-7, 1.0000000000000071)]
public void CanComputeSecant(double value, double expected)
{
var actual = Trig.Sec(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute sine.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(8388608, 0.43224820225679778)]
[TestCase(-8388608, -0.43224820225679778)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078072e-7)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078072e-7)]
public void CanComputeSine(double value, double expected)
{
var actual = Trig.Sin(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute tangent.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0, 0.0)]
[TestCase(8388608, -0.47934123862654288)]
[TestCase(-8388608, 0.47934123862654288)]
[TestCase(1.19209289550780998537e-7, 1.1920928955078157e-7)]
[TestCase(-1.19209289550780998537e-7, -1.1920928955078157e-7)]
public void CanComputeTangent(double value, double expected)
{
var actual = Trig.Tan(value);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can convert degree to grad.
/// </summary>
[Test]
public void CanConvertDegreeToGrad()
{
AssertHelpers.AlmostEqualRelative(90 / .9, Trig.DegreeToGrad(90), 15);
}
/// <summary>
/// Can convert degree to radian.
/// </summary>
[Test]
public void CanConvertDegreeToRadian()
{
AssertHelpers.AlmostEqualRelative(Math.PI / 2, Trig.DegreeToRadian(90), 15);
}
/// <summary>
/// Can convert grad to degree.
/// </summary>
[Test]
public void CanConvertGradToDegree()
{
AssertHelpers.AlmostEqualRelative(180, Trig.GradToDegree(200), 15);
}
/// <summary>
/// Can convert grad to radian.
/// </summary>
[Test]
public void CanConvertGradToRadian()
{
AssertHelpers.AlmostEqualRelative(Math.PI, Trig.GradToRadian(200), 15);
}
/// <summary>
/// Can convert radian to degree.
/// </summary>
[Test]
public void CanConvertRadianToDegree()
{
AssertHelpers.AlmostEqualRelative(60.0, Trig.RadianToDegree(Math.PI / 3.0), 14);
}
/// <summary>
/// Can convert radian to grad.
/// </summary>
[Test]
public void CanConvertRadianToGrad()
{
AssertHelpers.AlmostEqualRelative(200.0 / 3.0, Trig.RadianToGrad(Math.PI / 3.0), 14);
}
/// <summary>
/// Can compute complex cotangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(8.388608e6, 0.0, -2.086196470108229, 0.0)]
[TestCase(-8.388608e6, 0.0, 2.086196470108229, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 8388607.999999978, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -8388607.999999978, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, -2.0861964701080704, -6.3803383253713457e-7)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 2.0861964701080704, 6.3803383253713457e-7)]
public void CanComputeComplexCotangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Cot();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex secant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 1.0, 0.0)]
[TestCase(8.388608e6, 0.0, -1.1089490624226292, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.1089490624226292, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.0000000000000071, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 1.0000000000000071, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, -1.1089490624226177, 6.3367488045143761e-8)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1089490624226177, 6.3367488045143761e-8)]
public void CanComputeComplexSecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Sec();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex cosecant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(8.388608e6, 0.0, 2.3134856195559191, 0.0)]
[TestCase(-8.388608e6, 0.0, -2.3134856195559191, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 8388608.0000000376, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -8388608.0000000376, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 2.3134856195557596, 5.7534999050657057e-7)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -2.3134856195557596, -5.7534999050657057e-7)]
public void CanComputeComplexCosecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Csc();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex hyperbolic sine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(-8.388608e6, 0.0, double.NegativeInfinity, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078128e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078128e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, double.PositiveInfinity, double.PositiveInfinity)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, double.NegativeInfinity, double.NegativeInfinity)]
[TestCase(0.5, -0.5, 0.45730415318424922, -0.54061268571315335)]
public void CanComputeComplexHyperbolicSine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Sinh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex hyperbolic cosine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 1.0, 0.0)]
[TestCase(8.388608e6, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(-8.388608e6, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.0000000000000071, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 1.0000000000000071, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, double.PositiveInfinity, double.PositiveInfinity)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, double.PositiveInfinity, double.PositiveInfinity)]
[TestCase(0.5, -0.5, 0.9895848833999199, -0.24982639750046154)]
public void CanComputeComplexHyperbolicCosine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Cosh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex hyperbolic tangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, 1.0, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.0, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078043e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078043e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.0, 0.0)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.0, 0.0)]
[TestCase(0.5, -0.5, 0.56408314126749848, -0.40389645531602575)]
public void CanComputeComplexHyperbolicTangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Tanh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex hyperbolic cotangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(8.388608e6, 0.0, 1.0, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.0, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 8388608.0000000574, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -8388608.0000000574, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.0, 0.0)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.0, 0.0)]
[TestCase(0.5, -0.5, 1.1719451445243514, -0.8391395790248311)]
public void CanComputeComplexHyperbolicCotangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Coth();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex hyperbolic secant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 1.0, 0.0)]
[TestCase(8.388608e6, 0.0, 0.0, 0.0)]
[TestCase(-8.388608e6, 0.0, 0.0, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 0.99999999999999289, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 0.99999999999999289, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 0.0, 0.0)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -0.0, 0.0)]
[TestCase(0.5, -0.5, 0.94997886761549463, 0.23982763093808804)]
public void CanComputeComplexHyperbolicSecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Sech();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex hyperbolic cosecant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, double.PositiveInfinity, 0.0)]
[TestCase(8.388608e6, 0.0, 0.0, 0.0)]
[TestCase(-8.388608e6, 0.0, 0.0, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 8388607.9999999978, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -8388607.9999999978, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 0.0, 0.0)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 0.0, 0.0)]
[TestCase(0.5, -0.5, 0.91207426403881078, 1.0782296946540223)]
public void CanComputeComplexHyperbolicCosecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Csch();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse sine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, 1.5707963267948966, -16.635532333438682)]
[TestCase(-8.388608e6, 0.0, -1.5707963267948966, 16.635532333438682)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078128e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078128e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.5707963267948966, 16.635532333438682)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.5707963267948966, -16.635532333438682)]
[TestCase(0.5, -0.5, 0.4522784471511907, -0.53063753095251787)]
[TestCase(123400000000d, 0d, 1.57079632679489661923, -26.23184412897764390497)]
[TestCase(-123400000000d, 0d, -1.57079632679489661923, 26.23184412897764390497)]
public void CanComputeComplexInverseSine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Asin();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
/// <summary>
/// Can compute complex inverse cosine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 1.5707963267948966, 0.0)]
[TestCase(8.388608e6, 0.0, 0.0, 16.635532333438682)]
[TestCase(-8.388608e6, 0.0, 3.1415926535897931, -16.635532333438682)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.570796207585607, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 1.5707964460041861, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.4210854715202073e-14, -16.635532333438682)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 3.1415926535897789, 16.63553233343868)]
[TestCase(0.5, -0.5, 1.1185178796437059, 0.53063753095251787)]
[TestCase(123400000000d, 0d, 0d, 26.23184412897764390497)]
[TestCase(-123400000000d, 0d, 3.14159265358979323846, -26.23184412897764390497)]
public void CanComputeComplexInverseCosine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acos();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse tangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, 0.0, 0.0)]
[TestCase(8.388608e6, 0.0, 1.570796207585607, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.570796207585607, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078043e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078043e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.570796207585607, 0.0)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.570796207585607, 0.0)]
[TestCase(0.5, -0.5, 0.5535743588970452, -0.40235947810852507)]
public void CanComputeComplexInverseTangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Atan();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse cotangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(0.0, 0.0, Math.PI / 2.0, 0.0)]
[TestCase(8.388608e6, 0.0, 1.1920928955078069e-7, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.1920928955078069e-7, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.5707962075856071, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.5707962075856071, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.1920928955078069e-7, -1.6907571720583645e-21)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1920928955078069e-7, 1.6907571720583645e-21)]
[TestCase(0.5, -0.5, 1.0172219678978514, 0.40235947810852509)]
public void CanComputeComplexInverseCotangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acot();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse secant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 1.5707962075856071, 0.0)]
[TestCase(-8.388608e6, 0.0, 1.5707964460041862, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 0.0, 16.635532333438686)]
[TestCase(-1.19209289550780998537e-7, 0.0, 3.1415926535897932, -16.635532333438686)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.5707962075856071, 1.6940658945086007e-21)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 1.5707964460041862, -1.6940658945086007e-21)]
[TestCase(0.5, -0.5, 0.90455689430238136, -1.0612750619050357)]
public void CanComputeComplexInverseSecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Asec();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse cosecant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 1.1920928955078153e-7, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.1920928955078153e-7, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.5707963267948966, -16.635532333438686)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.5707963267948966, 16.635532333438686)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.1920928955078153e-7, -1.6940658945086007e-21)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1920928955078153e-7, 1.6940658945086007e-21)]
[TestCase(0.5, -0.5, 0.66623943249251526, 1.0612750619050357)]
public void CanComputeComplexInverseCosecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acsc();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse hyperbolic sine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 16.63553233343869, 0.0)]
[TestCase(-8.388608e6, 0.0, -16.63553233343869, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078072e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078072e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 16.63553233343869, 1.4210854715201873e-14)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -16.63553233343869, -1.4210854715201873e-14)]
[TestCase(0.5, -0.5, 0.53063753095251787, -0.4522784471511907)]
public void CanComputeComplexInverseHyperbolicSine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Asinh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 12);
}
/// <summary>
/// Can compute complex inverse hyperbolic cosine.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 16.635532333438682, 0.0)]
[TestCase(-8.388608e6, 0.0, 16.635532333438682, 3.1415926535897931)]
[TestCase(1.19209289550780998537e-7, 0.0, 0.0, 1.570796207585607)]
[TestCase(-1.19209289550780998537e-7, 0.0, 0.0, 1.5707964460041861)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 16.635532333438682, 1.4210854715202073e-14)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 16.635532333438682, -3.1415926535897789)]
[TestCase(0.5, -0.5, 0.53063753095251787, -1.1185178796437059)]
public void CanComputeComplexInverseHyperbolicCosine(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acosh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse hyperbolic tangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 1.1920928955078125e-7, -1.5707963267948966)]
[TestCase(-8.388608e6, 0.0, -1.1920928955078125e-7, 1.5707963267948966)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078157e-7, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078157e-7, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.1920928955078125e-7, 1.5707963267948966)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1920928955078125e-7, -1.5707963267948966)]
[TestCase(0.5, -0.5, 0.40235947810852509, -0.55357435889704525)]
public void CanComputeComplexInverseHyperbolicTangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Atanh();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse hyperbolic cotangent.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 1.1920928955078181e-7, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.1920928955078181e-7, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 1.1920928955078157e-7, -1.5707963267948966)]
[TestCase(-1.19209289550780998537e-7, 0.0, -1.1920928955078157e-7, 1.5707963267948966)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.1920928955078181e-7, -1.6940658945086212e-21)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1920928955078181e-7, 1.6940658945086212e-21)]
[TestCase(0.5, -0.5, 0.40235947810852509, 1.0172219678978514)]
public void CanComputeComplexInverseHyperbolicCotangent(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acoth();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse hyperbolic secant.
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 0.0, 1.5707962075856071)]
[TestCase(-8.388608e6, 0.0, 0.0, 1.5707964460041862)]
[TestCase(1.19209289550780998537e-7, 0.0, 16.635532333438686, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, 16.635532333438686, 3.1415926535897932)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.6940658945086007e-21, -1.5707962075856071)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, 1.6940658945086007e-21, 1.5707964460041862)]
[TestCase(0.5, -0.5, 1.0612750619050357, 0.90455689430238136)]
public void CanComputeComplexInverseHyperbolicSecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Asech();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 14);
}
/// <summary>
/// Can compute complex inverse hyperbolic cosecant
/// </summary>
/// <param name="real">Input complex real part.</param>
/// <param name="imag">Input complex imaginary part.</param>
/// <param name="expectedReal">Expected complex real part.</param>
/// <param name="expectedImag">Expected complex imaginary part.</param>
[TestCase(8.388608e6, 0.0, 1.1920928955078097e-7, 0.0)]
[TestCase(-8.388608e6, 0.0, -1.1920928955078097e-7, 0.0)]
[TestCase(1.19209289550780998537e-7, 0.0, 16.635532333438693, 0.0)]
[TestCase(-1.19209289550780998537e-7, 0.0, -16.635532333438693, 0.0)]
[TestCase(8.388608e6, 1.19209289550780998537e-7, 1.1920928955078076e-7, -1.6940658945085851e-21)]
[TestCase(-8.388608e6, -1.19209289550780998537e-7, -1.1920928955078076e-7, 1.6940658945085851e-21)]
[TestCase(0.5, -0.5, 1.0612750619050357, 0.66623943249251526)]
public void CanComputeComplexInverseHyperbolicCosecant(double real, double imag, double expectedReal, double expectedImag)
{
var actual = new Complex(real, imag).Acsch();
var expected = new Complex(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, actual, 13);
}
}
}
| |
// 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.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Runtime;
using Internal.Runtime.CompilerHelpers;
namespace System.Runtime.CompilerServices
{
internal static partial class ClassConstructorRunner
{
//==============================================================================================================
// Ensures the class constructor for the given type has run.
//
// Called by the runtime when it finds a class whose static class constructor has probably not run
// (probably because it checks in the initialized flag without thread synchronization).
//
// The context structure passed by reference lives in the image of one of the application's modules.
// The contents are thus fixed (do not require pinning) and the address can be used as a unique
// identifier for the context.
//
// This guarantee is violated in one specific case: where a class constructor cycle would cause a deadlock. If
// so, per ECMA specs, this method returns without guaranteeing that the .cctor has run.
//
// No attempt is made to detect or break deadlocks due to other synchronization mechanisms.
//==============================================================================================================
#if !CORERT
[RuntimeExport("CheckStaticClassConstruction")]
public static unsafe void* CheckStaticClassConstruction(void* returnValue, StaticClassConstructionContext* pContext)
{
EnsureClassConstructorRun(pContext);
return returnValue;
}
#else
private static unsafe object CheckStaticClassConstructionReturnGCStaticBase(StaticClassConstructionContext* context, object gcStaticBase)
{
EnsureClassConstructorRun(context);
return gcStaticBase;
}
private static unsafe IntPtr CheckStaticClassConstructionReturnNonGCStaticBase(StaticClassConstructionContext* context, IntPtr nonGcStaticBase)
{
EnsureClassConstructorRun(context);
return nonGcStaticBase;
}
private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, Int32 typeTlsIndex, StaticClassConstructionContext* context)
{
object threadStaticBase = ThreadStatics.GetThreadStaticBaseForType(pModuleData, typeTlsIndex);
EnsureClassConstructorRun(context);
return threadStaticBase;
}
#endif
public static unsafe void EnsureClassConstructorRun(StaticClassConstructionContext* pContext)
{
IntPtr pfnCctor = pContext->cctorMethodAddress;
NoisyLog("EnsureClassConstructorRun, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
// If we were called from MRT, this check is redundant but harmless. This is in case someone within classlib
// (cough, Reflection) needs to call this explicitly.
if (pContext->initialized == 1)
{
NoisyLog("Cctor already run, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
return;
}
CctorHandle cctor = Cctor.GetCctor(pContext);
Cctor[] cctors = cctor.Array;
int cctorIndex = cctor.Index;
try
{
Lock cctorLock = cctors[cctorIndex].Lock;
if (DeadlockAwareAcquire(cctor, pfnCctor))
{
int currentManagedThreadId = CurrentManagedThreadId;
try
{
NoisyLog("Acquired cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
cctors[cctorIndex].HoldingThread = currentManagedThreadId;
if (pContext->initialized == 0) // Check again in case some thread raced us while we were acquiring the lock.
{
TypeInitializationException priorException = cctors[cctorIndex].Exception;
if (priorException != null)
throw priorException;
try
{
NoisyLog("Calling cctor, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
Call<int>(pfnCctor);
// Insert a memory barrier here to order any writes executed as part of static class
// construction above with respect to the initialized flag update we're about to make
// below. This is important since the fast path for checking the cctor uses a normal read
// and doesn't come here so without the barrier it could observe initialized == 1 but
// still see uninitialized static fields on the class.
Interlocked.MemoryBarrier();
NoisyLog("Set type inited, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
pContext->initialized = 1;
}
catch (Exception e)
{
TypeInitializationException wrappedException = new TypeInitializationException(null, SR.TypeInitialization_Type_NoTypeAvailable, e);
cctors[cctorIndex].Exception = wrappedException;
throw wrappedException;
}
}
}
finally
{
cctors[cctorIndex].HoldingThread = ManagedThreadIdNone;
NoisyLog("Releasing cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
cctorLock.Release();
}
}
else
{
// Cctor cycle resulted in a deadlock. We will break the guarantee and return without running the
// .cctor.
}
}
finally
{
Cctor.Release(cctor);
}
NoisyLog("EnsureClassConstructorRun complete, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
}
//=========================================================================================================
// Return value:
// true - lock acquired.
// false - deadlock detected. Lock not acquired.
//=========================================================================================================
private static bool DeadlockAwareAcquire(CctorHandle cctor, IntPtr pfnCctor)
{
const int WaitIntervalSeedInMS = 1; // seed with 1ms and double every time through the loop
const int WaitIntervalLimitInMS = WaitIntervalSeedInMS << 7; // limit of 128ms
int waitIntervalInMS = WaitIntervalSeedInMS;
int cctorIndex = cctor.Index;
Cctor[] cctors = cctor.Array;
Lock lck = cctors[cctorIndex].Lock;
if (lck.IsAcquired)
return false; // Thread recursively triggered the same cctor.
if (lck.TryAcquire(waitIntervalInMS))
return true;
// We couldn't acquire the lock. See if this .cctor is involved in a cross-thread deadlock. If so, break
// the deadlock by breaking the guarantee - we'll skip running the .cctor and let the caller take his chances.
int currentManagedThreadId = CurrentManagedThreadId;
int unmarkCookie = -1;
try
{
// We'll spin in a forever-loop of checking for a deadlock state, then waiting a short time, then
// checking for a deadlock state again, and so on. This is because the BlockedRecord info has a built-in
// lag time - threads don't report themselves as blocking until they've been blocked for a non-trivial
// amount of time.
//
// If the threads are deadlocked for any reason other a class constructor cycling, this loop will never
// terminate - this is by design. If the user code inside the class constructors were to
// deadlock themselves, then that's a bug in user code.
for (;;)
{
using (LockHolder.Hold(s_cctorGlobalLock))
{
// Ask the guy who holds the cctor lock we're trying to acquire who he's waiting for. Keep
// walking down that chain until we either discover a cycle or reach a non-blocking state. Note
// that reaching a non-blocking state is not proof that we've avoided a deadlock due to the
// BlockingRecord reporting lag.
CctorHandle cctorWalk = cctor;
int chainStepCount = 0;
for (; chainStepCount < Cctor.Count; chainStepCount++)
{
int cctorWalkIndex = cctorWalk.Index;
Cctor[] cctorWalkArray = cctorWalk.Array;
int holdingThread = cctorWalkArray[cctorWalkIndex].HoldingThread;
if (holdingThread == currentManagedThreadId)
{
// Deadlock detected. We will break the guarantee and return without running the .cctor.
DebugLog("A class constructor was skipped due to class constructor cycle. cctor={0}, thread={1}",
pfnCctor, currentManagedThreadId);
// We are maintaining an invariant that the BlockingRecords never show a cycle because,
// before we add a record, we first check for a cycle. As a result, once we've said
// we're waiting, we are committed to waiting and will not need to skip running this
// .cctor.
Debug.Assert(unmarkCookie == -1);
return false;
}
if (holdingThread == ManagedThreadIdNone)
{
// No one appears to be holding this cctor lock. Give the current thread some more time
// to acquire the lock.
break;
}
cctorWalk = BlockingRecord.GetCctorThatThreadIsBlockedOn(holdingThread);
if (cctorWalk.Array == null)
{
// The final thread in the chain appears to be blocked on nothing. Give the current
// thread some more time to acquire the lock.
break;
}
}
// We don't allow cycles in the BlockingRecords, so we must always enumerate at most each entry,
// but never more.
Debug.Assert(chainStepCount < Cctor.Count);
// We have not discovered a deadlock, so let's register the fact that we're waiting on another
// thread and continue to wait. It is important that we only signal that we are blocked after
// we check for a deadlock because, otherwise, we give all threads involved in the deadlock the
// opportunity to break it themselves and that leads to "ping-ponging" between the cctors
// involved in the cycle, allowing intermediate cctor results to be observed.
//
// The invariant here is that we never 'publish' a BlockingRecord that forms a cycle. So it is
// important that the look-for-cycle-and-then-publish-wait-status operation be atomic with
// respect to other updates to the BlockingRecords.
if (unmarkCookie == -1)
{
NoisyLog("Mark thread blocked, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
unmarkCookie = BlockingRecord.MarkThreadAsBlocked(currentManagedThreadId, cctor);
}
} // _cctorGlobalLock scope
if (waitIntervalInMS < WaitIntervalLimitInMS)
waitIntervalInMS *= 2;
// We didn't find a cycle yet, try to take the lock again.
if (lck.TryAcquire(waitIntervalInMS))
return true;
} // infinite loop
}
finally
{
if (unmarkCookie != -1)
{
NoisyLog("Unmark thread blocked, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
BlockingRecord.UnmarkThreadAsBlocked(unmarkCookie);
}
}
}
//==============================================================================================================
// These structs are allocated on demand whenever the runtime tries to run a class constructor. Once the
// the class constructor has been successfully initialized, we reclaim this structure. The structure is long-
// lived only if the class constructor threw an exception.
//==============================================================================================================
private unsafe struct Cctor
{
public Lock Lock;
public TypeInitializationException Exception;
public int HoldingThread;
private int _refCount;
private StaticClassConstructionContext* _pContext;
//==========================================================================================================
// Gets the Cctor entry associated with a specific class constructor context (creating it if necessary.)
//==========================================================================================================
public static CctorHandle GetCctor(StaticClassConstructionContext* pContext)
{
#if DEBUG
const int Grow = 2;
#else
const int Grow = 10;
#endif
using (LockHolder.Hold(s_cctorGlobalLock))
{
Cctor[] resultArray = null;
int resultIndex = -1;
if (s_count != 0)
{
// Search for the cctor context in our existing arrays
for (int cctorIndex = 0; cctorIndex < s_cctorArraysCount; ++cctorIndex)
{
Cctor[] segment = s_cctorArrays[cctorIndex];
for (int i = 0; i < segment.Length; i++)
{
if (segment[i]._pContext == pContext)
{
resultArray = segment;
resultIndex = i;
break;
}
}
if (resultArray != null)
break;
}
}
if (resultArray == null)
{
// look for an empty entry in an existing array
for (int cctorIndex = 0; cctorIndex < s_cctorArraysCount; ++cctorIndex)
{
Cctor[] segment = s_cctorArrays[cctorIndex];
for (int i = 0; i < segment.Length; i++)
{
if (segment[i]._pContext == default(StaticClassConstructionContext*))
{
resultArray = segment;
resultIndex = i;
break;
}
}
if (resultArray != null)
break;
}
if (resultArray == null)
{
// allocate a new array
resultArray = new Cctor[Grow];
if (s_cctorArraysCount == s_cctorArrays.Length)
{
// grow the container
Array.Resize(ref s_cctorArrays, (s_cctorArrays.Length * 2) + 1);
}
// store the array in the container, this cctor gets index 0
s_cctorArrays[s_cctorArraysCount] = resultArray;
s_cctorArraysCount++;
resultIndex = 0;
}
Debug.Assert(resultArray[resultIndex]._pContext == default(StaticClassConstructionContext*));
resultArray[resultIndex]._pContext = pContext;
resultArray[resultIndex].Lock = new Lock();
s_count++;
}
Interlocked.Increment(ref resultArray[resultIndex]._refCount);
return new CctorHandle(resultArray, resultIndex);
}
}
public static int Count
{
get
{
Debug.Assert(s_cctorGlobalLock.IsAcquired);
return s_count;
}
}
public static void Release(CctorHandle cctor)
{
using (LockHolder.Hold(s_cctorGlobalLock))
{
Cctor[] cctors = cctor.Array;
int cctorIndex = cctor.Index;
if (0 == Interlocked.Decrement(ref cctors[cctorIndex]._refCount))
{
if (cctors[cctorIndex].Exception == null)
{
cctors[cctorIndex] = new Cctor();
s_count--;
}
}
}
}
}
private struct CctorHandle
{
public CctorHandle(Cctor[] array, int index)
{
_array = array;
_index = index;
}
public Cctor[] Array { get { return _array; } }
public int Index { get { return _index; } }
private Cctor[] _array;
private int _index;
}
//==============================================================================================================
// Keeps track of threads that are blocked on a cctor lock (alas, we don't have ThreadLocals here in
// System.Private.CoreLib so we have to use a side table.)
//
// This is used for cross-thread deadlock detection.
//
// - Data is only entered here if a thread has been blocked past a certain timeout (otherwise, it's certainly
// not participating of a deadlock.)
// - Reads and writes to _blockingRecord are guarded by _cctorGlobalLock.
// - BlockingRecords for individual threads are created on demand. Since this is a rare event, we won't attempt
// to recycle them directly (however,
// ManagedThreadId's are themselves recycled pretty quickly - and threads that inherit the managed id also
// inherit the BlockingRecord.)
//==============================================================================================================
private struct BlockingRecord
{
public int ManagedThreadId; // ManagedThreadId of the blocked thread
public CctorHandle BlockedOn;
public static int MarkThreadAsBlocked(int managedThreadId, CctorHandle blockedOn)
{
#if DEBUG
const int Grow = 2;
#else
const int Grow = 10;
#endif
using (LockHolder.Hold(s_cctorGlobalLock))
{
if (s_blockingRecords == null)
s_blockingRecords = new BlockingRecord[Grow];
int found;
for (found = 0; found < s_nextBlockingRecordIndex; found++)
{
if (s_blockingRecords[found].ManagedThreadId == managedThreadId)
break;
}
if (found == s_nextBlockingRecordIndex)
{
if (s_nextBlockingRecordIndex == s_blockingRecords.Length)
{
BlockingRecord[] newBlockingRecords = new BlockingRecord[s_blockingRecords.Length + Grow];
for (int i = 0; i < s_blockingRecords.Length; i++)
{
newBlockingRecords[i] = s_blockingRecords[i];
}
s_blockingRecords = newBlockingRecords;
}
s_blockingRecords[s_nextBlockingRecordIndex].ManagedThreadId = managedThreadId;
s_nextBlockingRecordIndex++;
}
s_blockingRecords[found].BlockedOn = blockedOn;
return found;
}
}
public static void UnmarkThreadAsBlocked(int blockRecordIndex)
{
// This method must never throw
s_cctorGlobalLock.Acquire();
s_blockingRecords[blockRecordIndex].BlockedOn = new CctorHandle(null, 0);
s_cctorGlobalLock.Release();
}
public static CctorHandle GetCctorThatThreadIsBlockedOn(int managedThreadId)
{
Debug.Assert(s_cctorGlobalLock.IsAcquired);
for (int i = 0; i < s_nextBlockingRecordIndex; i++)
{
if (s_blockingRecords[i].ManagedThreadId == managedThreadId)
return s_blockingRecords[i].BlockedOn;
}
return new CctorHandle(null, 0);
}
private static BlockingRecord[] s_blockingRecords;
private static int s_nextBlockingRecordIndex;
}
private static Lock s_cctorGlobalLock;
// These three statics are used by ClassConstructorRunner.Cctor but moved out to avoid an unnecessary
// extra class constructor call.
//
// Because Cctor's are mutable structs, we have to give our callers raw references to the underlying arrays
// for this collection to be usable. This also means once we place a Cctor in an array, we can't grow or
// reallocate the array.
private static Cctor[][] s_cctorArrays;
private static int s_cctorArraysCount;
private static int s_count;
// Eager construction called from LibraryInitialize Cctor.GetCctor uses _cctorGlobalLock.
internal static void Initialize()
{
s_cctorArrays = new Cctor[10][];
s_cctorGlobalLock = new Lock();
}
[Conditional("ENABLE_NOISY_CCTOR_LOG")]
private static void NoisyLog(string format, IntPtr cctorMethod, int threadId)
{
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
Debug.WriteLine(format, ToHexString(cctorMethod), ToHexString(threadId));
#endif // DEBUG
}
[Conditional("DEBUG")]
private static void DebugLog(string format, IntPtr cctorMethod, int threadId)
{
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
Debug.WriteLine(format, ToHexString(cctorMethod), ToHexString(threadId));
#endif
}
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
private static string ToHexString(int num)
{
return ToHexStringUnsignedLong((ulong)num, false, 8);
}
private static string ToHexString(IntPtr num)
{
return ToHexStringUnsignedLong((ulong)num, false, 16);
}
private static char GetHexChar(uint u)
{
if (u < 10)
return unchecked((char)('0' + u));
return unchecked((char)('a' + (u - 10)));
}
public static unsafe string ToHexStringUnsignedLong(ulong u, bool zeroPrepad, int numChars)
{
char[] chars = new char[numChars];
int i = numChars - 1;
for (; i >= 0; i--)
{
chars[i] = GetHexChar((uint)(u % 16));
u = u / 16;
if ((i == 0) || (!zeroPrepad && (u == 0)))
break;
}
string str;
fixed (char* p = &chars[i])
{
str = new String(p, 0, numChars - i);
}
return str;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace System
{
/// <summary>Provides access to and processing of a terminfo database.</summary>
internal static class TermInfo
{
internal enum WellKnownNumbers
{
Columns = 0,
Lines = 2,
MaxColors = 13,
}
internal enum WellKnownStrings
{
Bell = 1,
Clear = 5,
CursorAddress = 10,
CursorLeft = 14,
CursorPositionReport = 294,
OrigPairs = 297,
OrigColors = 298,
SetAnsiForeground = 359,
SetAnsiBackground = 360,
CursorInvisible = 13,
CursorVisible = 16,
FromStatusLine = 47,
ToStatusLine = 135,
KeyBackspace = 55,
KeyClear = 57,
KeyDelete = 59,
KeyDown = 61,
KeyF1 = 66,
KeyF10 = 67,
KeyF2 = 68,
KeyF3 = 69,
KeyF4 = 70,
KeyF5 = 71,
KeyF6 = 72,
KeyF7 = 73,
KeyF8 = 74,
KeyF9 = 75,
KeyHome = 76,
KeyInsert = 77,
KeyLeft = 79,
KeyPageDown = 81,
KeyPageUp = 82,
KeyRight = 83,
KeyScrollForward = 84,
KeyScrollReverse = 85,
KeyUp = 87,
KeypadXmit = 89,
KeyBackTab = 148,
KeyBegin = 158,
KeyEnd = 164,
KeyEnter = 165,
KeyHelp = 168,
KeyPrint = 176,
KeySBegin = 186,
KeySDelete = 191,
KeySelect = 193,
KeySHelp = 198,
KeySHome = 199,
KeySLeft = 201,
KeySPrint = 207,
KeySRight = 210,
KeyF11 = 216,
KeyF12 = 217,
KeyF13 = 218,
KeyF14 = 219,
KeyF15 = 220,
KeyF16 = 221,
KeyF17 = 222,
KeyF18 = 223,
KeyF19 = 224,
KeyF20 = 225,
KeyF21 = 226,
KeyF22 = 227,
KeyF23 = 228,
KeyF24 = 229,
}
/// <summary>Provides a terminfo database.</summary>
internal sealed class Database
{
/// <summary>The name of the terminfo file.</summary>
private readonly string _term;
/// <summary>Raw data of the database instance.</summary>
private readonly byte[] _data;
/// <summary>The number of bytes in the names section of the database.</summary>
private readonly int _nameSectionNumBytes;
/// <summary>The number of bytes in the Booleans section of the database.</summary>
private readonly int _boolSectionNumBytes;
/// <summary>The number of shorts in the numbers section of the database.</summary>
private readonly int _numberSectionNumShorts;
/// <summary>The number of offsets in the strings section of the database.</summary>
private readonly int _stringSectionNumOffsets;
/// <summary>The number of bytes in the strings table of the database.</summary>
private readonly int _stringTableNumBytes;
/// <summary>Extended / user-defined entries in the terminfo database.</summary>
private readonly Dictionary<string, string> _extendedStrings;
/// <summary>Initializes the database instance.</summary>
/// <param name="term">The name of the terminal.</param>
/// <param name="data">The data from the terminfo file.</param>
private Database(string term, byte[] data)
{
_term = term;
_data = data;
// See "man term" for the file format.
if (ReadInt16(data, 0) != 0x11A) // magic number octal 0432
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
_nameSectionNumBytes = ReadInt16(data, 2);
_boolSectionNumBytes = ReadInt16(data, 4);
_numberSectionNumShorts = ReadInt16(data, 6);
_stringSectionNumOffsets = ReadInt16(data, 8);
_stringTableNumBytes = ReadInt16(data, 10);
if (_nameSectionNumBytes < 0 ||
_boolSectionNumBytes < 0 ||
_numberSectionNumShorts < 0 ||
_stringSectionNumOffsets < 0 ||
_stringTableNumBytes < 0)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// In addition to the main section of bools, numbers, and strings, there is also
// an "extended" section. This section contains additional entries that don't
// have well-known indices, and are instead named mappings. As such, we parse
// all of this data now rather than on each request, as the mapping is fairly complicated.
// This function relies on the data stored above, so it's the last thing we run.
// (Note that the extended section also includes other Booleans and numbers, but we don't
// have any need for those now, so we don't parse them.)
int extendedBeginning = RoundUpToEven(StringsTableOffset + _stringTableNumBytes);
_extendedStrings = ParseExtendedStrings(data, extendedBeginning) ?? new Dictionary<string, string>();
}
/// <summary>The name of the associated terminfo, if any.</summary>
public string Term { get { return _term; } }
/// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary>
/// <returns>The database, or null if it could not be found.</returns>
internal static Database ReadActiveDatabase()
{
string term = Environment.GetEnvironmentVariable("TERM");
return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null;
}
/// <summary>
/// The default locations in which to search for terminfo databases.
/// This is the ordering of well-known locations used by ncurses.
/// </summary>
private static readonly string[] _terminfoLocations = new string[] {
"/etc/terminfo",
"/lib/terminfo",
"/usr/share/terminfo",
};
/// <summary>Read the database for the specified terminal.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database ReadDatabase(string term)
{
// This follows the same search order as prescribed by ncurses.
Database db;
// First try a location specified in the TERMINFO environment variable.
string terminfo = Environment.GetEnvironmentVariable("TERMINFO");
if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null)
{
return db;
}
// Then try in the user's home directory.
string home = PersistedFiles.GetHomeDirectory();
if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null)
{
return db;
}
// Then try a set of well-known locations.
foreach (string terminfoLocation in _terminfoLocations)
{
if ((db = ReadDatabase(term, terminfoLocation)) != null)
{
return db;
}
}
// Couldn't find one
return null;
}
/// <summary>Attempt to open as readonly the specified file path.</summary>
/// <param name="filePath">The path to the file to open.</param>
/// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param>
/// <returns>true if the file was successfully opened; otherwise, false.</returns>
private static bool TryOpen(string filePath, out SafeFileHandle fd)
{
fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY, 0);
if (fd.IsInvalid)
{
// Don't throw in this case, as we'll be polling multiple locations looking for the file.
fd = null;
return false;
}
return true;
}
/// <summary>Read the database for the specified terminal from the specified directory.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <param name="directoryPath">The path to the directory containing terminfo database files.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database ReadDatabase(string term, string directoryPath)
{
if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath))
{
return null;
}
SafeFileHandle fd;
if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux)
!TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac)
{
return null;
}
using (fd)
{
// Read in all of the terminfo data
long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length
Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning
const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max
const int HeaderLength = 12;
if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
int fileLen = (int)termInfoLength;
byte[] data = new byte[fileLen];
if (ConsolePal.Read(fd, data, 0, fileLen) != fileLen)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// Create the database from the data
return new Database(term, data);
}
}
/// <summary>The offset into data where the names section begins.</summary>
private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes
/// <summary>The offset into data where the Booleans section begins.</summary>
private int BooleansOffset { get { return NamesOffset + _nameSectionNumBytes; } } // after the names section
/// <summary>The offset into data where the numbers section begins.</summary>
private int NumbersOffset { get { return RoundUpToEven(BooleansOffset + _boolSectionNumBytes); } } // after the Booleans section, at an even position
/// <summary>
/// The offset into data where the string offsets section begins. We index into this section
/// to find the location within the strings table where a string value exists.
/// </summary>
private int StringOffsetsOffset { get { return NumbersOffset + (_numberSectionNumShorts * 2); } }
/// <summary>The offset into data where the string table exists.</summary>
private int StringsTableOffset { get { return StringOffsetsOffset + (_stringSectionNumOffsets * 2); } }
/// <summary>Gets a string from the strings section by the string's well-known index.</summary>
/// <param name="stringTableIndex">The index of the string to find.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string GetString(WellKnownStrings stringTableIndex)
{
int index = (int)stringTableIndex;
Debug.Assert(index >= 0);
if (index >= _stringSectionNumOffsets)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return null;
}
int tableIndex = ReadInt16(_data, StringOffsetsOffset + (index * 2));
if (tableIndex == -1)
{
// Some terminfo files may have enough entries, but may not actually
// have it filled in for this particular string.
return null;
}
return ReadString(_data, StringsTableOffset + tableIndex);
}
/// <summary>Gets a string from the extended strings section.</summary>
/// <param name="name">The name of the string as contained in the extended names section.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string GetExtendedString(string name)
{
Debug.Assert(name != null);
string value;
return _extendedStrings.TryGetValue(name, out value) ?
value :
null;
}
/// <summary>Gets a number from the numbers section by the number's well-known index.</summary>
/// <param name="numberIndex">The index of the string to find.</param>
/// <returns>The number if it's in the database; otherwise, -1.</returns>
public int GetNumber(WellKnownNumbers numberIndex)
{
int index = (int)numberIndex;
Debug.Assert(index >= 0);
if (index >= _numberSectionNumShorts)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return -1;
}
return ReadInt16(_data, NumbersOffset + (index * 2));
}
/// <summary>Parses the extended string information from the terminfo data.</summary>
/// <returns>
/// A dictionary of the name to value mapping. As this section of the terminfo isn't as well
/// defined as the earlier portions, and may not even exist, the parsing is more lenient about
/// errors, returning an empty collection rather than throwing.
/// </returns>
private static Dictionary<string, string> ParseExtendedStrings(byte[] data, int extendedBeginning)
{
const int ExtendedHeaderSize = 10;
if (extendedBeginning + ExtendedHeaderSize >= data.Length)
{
// Exit out as there's no extended information.
return null;
}
// Read in extended counts, and exit out if we got any incorrect info
int extendedBoolCount = ReadInt16(data, extendedBeginning);
int extendedNumberCount = ReadInt16(data, extendedBeginning + 2);
int extendedStringCount = ReadInt16(data, extendedBeginning + 4);
int extendedStringNumOffsets = ReadInt16(data, extendedBeginning + 6);
int extendedStringTableByteSize = ReadInt16(data, extendedBeginning + 8);
if (extendedBoolCount < 0 ||
extendedNumberCount < 0 ||
extendedStringCount < 0 ||
extendedStringNumOffsets < 0 ||
extendedStringTableByteSize < 0)
{
// The extended header contained invalid data. Bail.
return null;
}
// Skip over the extended bools. We don't need them now and can add this in later
// if needed. Also skip over extended numbers, for the same reason.
// Get the location where the extended string offsets begin. These point into
// the extended string table.
int extendedOffsetsStart =
extendedBeginning + // go past the normal data
ExtendedHeaderSize + // and past the extended header
RoundUpToEven(extendedBoolCount) + // and past all of the extended Booleans
(extendedNumberCount * 2); // and past all of the extended numbers
// Get the location where the extended string table begins. This area contains
// null-terminated strings.
int extendedStringTableStart =
extendedOffsetsStart +
(extendedStringCount * 2) + // and past all of the string offsets
((extendedBoolCount + extendedNumberCount + extendedStringCount) * 2); // and past all of the name offsets
// Get the location where the extended string table ends. We shouldn't read past this.
int extendedStringTableEnd =
extendedStringTableStart +
extendedStringTableByteSize;
if (extendedStringTableEnd > data.Length)
{
// We don't have enough data to parse everything. Bail.
return null;
}
// Now we need to parse all of the extended string values. These aren't necessarily
// "in order", meaning the offsets aren't guaranteed to be increasing. Instead, we parse
// the offsets in order, pulling out each string it references and storing them into our
// results list in the order of the offsets.
var values = new List<string>(extendedStringCount);
int lastEnd = 0;
for (int i = 0; i < extendedStringCount; i++)
{
int offset = extendedStringTableStart + ReadInt16(data, extendedOffsetsStart + (i * 2));
if (offset < 0 || offset >= data.Length)
{
// If the offset is invalid, bail.
return null;
}
// Add the string
int end = FindNullTerminator(data, offset);
values.Add(Encoding.ASCII.GetString(data, offset, end - offset));
// Keep track of where the last string ends. The name strings will come after that.
lastEnd = Math.Max(end, lastEnd);
}
// Now parse all of the names.
var names = new List<string>(extendedBoolCount + extendedNumberCount + extendedStringCount);
for (int pos = lastEnd + 1; pos < extendedStringTableEnd; pos++)
{
int end = FindNullTerminator(data, pos);
names.Add(Encoding.ASCII.GetString(data, pos, end - pos));
pos = end;
}
// The names are in order for the Booleans, then the numbers, and then the strings.
// Skip over the bools and numbers, and associate the names with the values.
var extendedStrings = new Dictionary<string, string>(extendedStringCount);
for (int iName = extendedBoolCount + extendedNumberCount, iValue = 0;
iName < names.Count && iValue < values.Count;
iName++, iValue++)
{
extendedStrings.Add(names[iName], values[iValue]);
}
return extendedStrings;
}
private static int RoundUpToEven(int i) { return i % 2 == 1 ? i + 1 : i; }
/// <summary>Read a 16-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The 16-bit value read.</returns>
private static short ReadInt16(byte[] buffer, int pos)
{
return (short)
((((int)buffer[pos + 1]) << 8) |
((int)buffer[pos] & 0xff));
}
/// <summary>Reads a string from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The string read from the specified position.</returns>
private static string ReadString(byte[] buffer, int pos)
{
int end = FindNullTerminator(buffer, pos);
return Encoding.ASCII.GetString(buffer, pos, end - pos);
}
/// <summary>Finds the null-terminator for a string that begins at the specified position.</summary>
private static int FindNullTerminator(byte[] buffer, int pos)
{
int termPos = pos;
while (termPos < buffer.Length && buffer[termPos] != '\0') termPos++;
return termPos;
}
}
/// <summary>Provides support for evaluating parameterized terminfo database format strings.</summary>
internal static class ParameterizedStrings
{
/// <summary>A cached stack to use to avoid allocating a new stack object for every evaluation.</summary>
[ThreadStatic]
private static LowLevelStack<FormatParam> t_cachedStack;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[] t_cachedOneElementArgsArray;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[] t_cachedTwoElementArgsArray;
/// <summary>Evaluates a terminfo formatting string, using the supplied argument.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg">The argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg)
{
FormatParam[] args = t_cachedOneElementArgsArray;
if (args == null)
{
t_cachedOneElementArgsArray = args = new FormatParam[1];
}
args[0] = arg;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg1">The first argument to the format string.</param>
/// <param name="arg2">The second argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg1, FormatParam arg2)
{
FormatParam[] args = t_cachedTwoElementArgsArray;
if (args == null)
{
t_cachedTwoElementArgsArray = args = new FormatParam[2];
}
args[0] = arg1;
args[1] = arg2;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="args">The arguments to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, params FormatParam[] args)
{
if (format == null)
{
throw new ArgumentNullException(nameof(format));
}
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
// Initialize the stack to use for processing.
LowLevelStack<FormatParam> stack = t_cachedStack;
if (stack == null)
{
t_cachedStack = stack = new LowLevelStack<FormatParam>();
}
else
{
stack.Clear();
}
// "dynamic" and "static" variables are much less often used (the "dynamic" and "static"
// terminology appears to just refer to two different collections rather than to any semantic
// meaning). As such, we'll only initialize them if we really need them.
FormatParam[] dynamicVars = null, staticVars = null;
int pos = 0;
return EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
// EvaluateInternal may throw IndexOutOfRangeException and InvalidOperationException
// if the format string is malformed or if it's inconsistent with the parameters provided.
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments and processing data structures.</summary>
/// <param name="format">The format string.</param>
/// <param name="pos">The position in <paramref name="format"/> to start processing.</param>
/// <param name="args">The arguments to the format string.</param>
/// <param name="stack">The stack to use as the format string is evaluated.</param>
/// <param name="dynamicVars">A lazily-initialized collection of variables.</param>
/// <param name="staticVars">A lazily-initialized collection of variables.</param>
/// <returns>
/// The formatted string; this may be empty if the evaluation didn't yield any output.
/// The evaluation stack will have a 1 at the top if all processing was completed at invoked level
/// of recursion, and a 0 at the top if we're still inside of a conditional that requires more processing.
/// </returns>
private static string EvaluateInternal(
string format, ref int pos, FormatParam[] args, LowLevelStack<FormatParam> stack,
ref FormatParam[] dynamicVars, ref FormatParam[] staticVars)
{
// Create a StringBuilder to store the output of this processing. We use the format's length as an
// approximation of an upper-bound for how large the output will be, though with parameter processing,
// this is just an estimate, sometimes way over, sometimes under.
StringBuilder output = StringBuilderCache.Acquire(format.Length);
// Format strings support conditionals, including the equivalent of "if ... then ..." and
// "if ... then ... else ...", as well as "if ... then ... else ... then ..."
// and so on, where an else clause can not only be evaluated for string output but also
// as a conditional used to determine whether to evaluate a subsequent then clause.
// We use recursion to process these subsequent parts, and we track whether we're processing
// at the same level of the initial if clause (or whether we're nested).
bool sawIfConditional = false;
// Process each character in the format string, starting from the position passed in.
for (; pos < format.Length; pos++)
{
// '%' is the escape character for a special sequence to be evaluated.
// Anything else just gets pushed to output.
if (format[pos] != '%')
{
output.Append(format[pos]);
continue;
}
// We have a special parameter sequence to process. Now we need
// to look at what comes after the '%'.
++pos;
switch (format[pos])
{
// Output appending operations
case '%': // Output the escaped '%'
output.Append('%');
break;
case 'c': // Pop the stack and output it as a char
output.Append((char)stack.Pop().Int32);
break;
case 's': // Pop the stack and output it as a string
output.Append(stack.Pop().String);
break;
case 'd': // Pop the stack and output it as an integer
output.Append(stack.Pop().Int32);
break;
case 'o':
case 'X':
case 'x':
case ':':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// printf strings of the format "%[[:]flags][width[.precision]][doxXs]" are allowed
// (with a ':' used in front of flags to help differentiate from binary operations, as flags can
// include '-' and '+'). While above we've special-cased common usage (e.g. %d, %s),
// for more complicated expressions we delegate to printf.
int printfEnd = pos;
for (; printfEnd < format.Length; printfEnd++) // find the end of the printf format string
{
char ec = format[printfEnd];
if (ec == 'd' || ec == 'o' || ec == 'x' || ec == 'X' || ec == 's')
{
break;
}
}
if (printfEnd >= format.Length)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
string printfFormat = format.Substring(pos - 1, printfEnd - pos + 2); // extract the format string
if (printfFormat.Length > 1 && printfFormat[1] == ':')
{
printfFormat = printfFormat.Remove(1, 1);
}
output.Append(FormatPrintF(printfFormat, stack.Pop().Object)); // do the printf formatting and append its output
break;
// Stack pushing operations
case 'p': // Push the specified parameter (1-based) onto the stack
pos++;
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
stack.Push(args[format[pos] - '1']);
break;
case 'l': // Pop a string and push its length
stack.Push(stack.Pop().String.Length);
break;
case '{': // Push integer literal, enclosed between braces
pos++;
int intLit = 0;
while (format[pos] != '}')
{
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
intLit = (intLit * 10) + (format[pos] - '0');
pos++;
}
stack.Push(intLit);
break;
case '\'': // Push literal character, enclosed between single quotes
stack.Push((int)format[pos + 1]);
Debug.Assert(format[pos + 2] == '\'');
pos += 2;
break;
// Storing and retrieving "static" and "dynamic" variables
case 'P': // Pop a value and store it into either static or dynamic variables based on whether the a-z variable is capitalized
pos++;
int setIndex;
FormatParam[] targetVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out setIndex);
targetVars[setIndex] = stack.Pop();
break;
case 'g': // Push a static or dynamic variable; which is based on whether the a-z variable is capitalized
pos++;
int getIndex;
FormatParam[] sourceVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out getIndex);
stack.Push(sourceVars[getIndex]);
break;
// Binary operations
case '+':
case '-':
case '*':
case '/':
case 'm':
case '^': // arithmetic
case '&':
case '|': // bitwise
case '=':
case '>':
case '<': // comparison
case 'A':
case 'O': // logical
int second = stack.Pop().Int32; // it's a stack... the second value was pushed last
int first = stack.Pop().Int32;
char c = format[pos];
stack.Push(
c == '+' ? (first + second) :
c == '-' ? (first - second) :
c == '*' ? (first * second) :
c == '/' ? (first / second) :
c == 'm' ? (first % second) :
c == '^' ? (first ^ second) :
c == '&' ? (first & second) :
c == '|' ? (first | second) :
c == '=' ? AsInt(first == second) :
c == '>' ? AsInt(first > second) :
c == '<' ? AsInt(first < second) :
c == 'A' ? AsInt(AsBool(first) && AsBool(second)) :
c == 'O' ? AsInt(AsBool(first) || AsBool(second)) :
0); // not possible; we just validated above
break;
// Unary operations
case '!':
case '~':
int value = stack.Pop().Int32;
stack.Push(
format[pos] == '!' ? AsInt(!AsBool(value)) :
~value);
break;
// Some terminfo files appear to have a fairly liberal interpretation of %i. The spec states that %i increments the first two arguments,
// but some uses occur when there's only a single argument. To make sure we accommodate these files, we increment the values
// of up to (but not requiring) two arguments.
case 'i':
if (args.Length > 0)
{
args[0] = 1 + args[0].Int32;
if (args.Length > 1)
args[1] = 1 + args[1].Int32;
}
break;
// Conditional of the form %? if-part %t then-part %e else-part %;
// The "%e else-part" is optional.
case '?':
sawIfConditional = true;
break;
case 't':
// We hit the end of the if-part and are about to start the then-part.
// The if-part left its result on the stack; pop and evaluate.
bool conditionalResult = AsBool(stack.Pop().Int32);
// Regardless of whether it's true, run the then-part to get past it.
// If the conditional was true, output the then results.
pos++;
string thenResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (conditionalResult)
{
output.Append(thenResult);
}
Debug.Assert(format[pos] == 'e' || format[pos] == ';');
// We're past the then; the top of the stack should now be a Boolean
// indicating whether this conditional has more to be processed (an else clause).
if (!AsBool(stack.Pop().Int32))
{
// Process the else clause, and if the conditional was false, output the else results.
pos++;
string elseResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (!conditionalResult)
{
output.Append(elseResult);
}
// Now we should be done (any subsequent elseif logic will have been handled in the recursive call).
if (!AsBool(stack.Pop().Int32))
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
// If we're in a nested processing, return to our parent.
if (!sawIfConditional)
{
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
// Otherwise, we're done processing the conditional in its entirety.
sawIfConditional = false;
break;
case 'e':
case ';':
// Let our caller know why we're exiting, whether due to the end of the conditional or an else branch.
stack.Push(AsInt(format[pos] == ';'));
return StringBuilderCache.GetStringAndRelease(output);
// Anything else is an error
default:
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
/// <summary>Converts an Int32 to a Boolean, with 0 meaning false and all non-zero values meaning true.</summary>
/// <param name="i">The integer value to convert.</param>
/// <returns>true if the integer was non-zero; otherwise, false.</returns>
private static bool AsBool(Int32 i) { return i != 0; }
/// <summary>Converts a Boolean to an Int32, with true meaning 1 and false meaning 0.</summary>
/// <param name="b">The Boolean value to convert.</param>
/// <returns>1 if the Boolean is true; otherwise, 0.</returns>
private static int AsInt(bool b) { return b ? 1 : 0; }
/// <summary>Formats an argument into a printf-style format string.</summary>
/// <param name="format">The printf-style format string.</param>
/// <param name="arg">The argument to format. This must be an Int32 or a String.</param>
/// <returns>The formatted string.</returns>
private static unsafe string FormatPrintF(string format, object arg)
{
Debug.Assert(arg is string || arg is Int32);
// Determine how much space is needed to store the formatted string.
string stringArg = arg as string;
int neededLength = stringArg != null ?
Interop.Sys.SNPrintF(null, 0, format, stringArg) :
Interop.Sys.SNPrintF(null, 0, format, (int)arg);
if (neededLength == 0)
{
return string.Empty;
}
if (neededLength < 0)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
// Allocate the needed space, format into it, and return the data as a string.
byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
fixed (byte* ptr = bytes)
{
int length = stringArg != null ?
Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) :
Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg);
if (length != neededLength)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
}
return Encoding.ASCII.GetString(bytes, 0, neededLength);
}
/// <summary>Gets the lazily-initialized dynamic or static variables collection, based on the supplied variable name.</summary>
/// <param name="c">The name of the variable.</param>
/// <param name="dynamicVars">The lazily-initialized dynamic variables collection.</param>
/// <param name="staticVars">The lazily-initialized static variables collection.</param>
/// <param name="index">The index to use to index into the variables.</param>
/// <returns>The variables collection.</returns>
private static FormatParam[] GetDynamicOrStaticVariables(
char c, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars, out int index)
{
if (c >= 'A' && c <= 'Z')
{
index = c - 'A';
return staticVars ?? (staticVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else if (c >= 'a' && c <= 'z')
{
index = c - 'a';
return dynamicVars ?? (dynamicVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
/// <summary>
/// Represents a parameter to a terminfo formatting string.
/// It is a discriminated union of either an integer or a string,
/// with characters represented as integers.
/// </summary>
public struct FormatParam
{
/// <summary>The integer stored in the parameter.</summary>
private readonly int _int32;
/// <summary>The string stored in the parameter.</summary>
private readonly string _string; // null means an Int32 is stored
/// <summary>Initializes the parameter with an integer value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(Int32 value) : this(value, null) { }
/// <summary>Initializes the parameter with a string value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(String value) : this(0, value ?? string.Empty) { }
/// <summary>Initializes the parameter.</summary>
/// <param name="intValue">The integer value.</param>
/// <param name="stringValue">The string value.</param>
private FormatParam(Int32 intValue, String stringValue)
{
_int32 = intValue;
_string = stringValue;
}
/// <summary>Implicit converts an integer into a parameter.</summary>
public static implicit operator FormatParam(int value)
{
return new FormatParam(value);
}
/// <summary>Implicit converts a string into a parameter.</summary>
public static implicit operator FormatParam(string value)
{
return new FormatParam(value);
}
/// <summary>Gets the integer value of the parameter. If a string was stored, 0 is returned.</summary>
public int Int32 { get { return _int32; } }
/// <summary>Gets the string value of the parameter. If an Int32 or a null String were stored, an empty string is returned.</summary>
public string String { get { return _string ?? string.Empty; } }
/// <summary>Gets the string or the integer value as an object.</summary>
public object Object { get { return _string ?? (object)_int32; } }
}
/// <summary>Provides a basic stack data structure.</summary>
/// <typeparam name="T">Specifies the type of data in the stack.</typeparam>
private sealed class LowLevelStack<T> // System.Console.dll doesn't reference System.Collections.dll
{
private const int DefaultSize = 4;
private T[] _arr;
private int _count;
public LowLevelStack() { _arr = new T[DefaultSize]; }
public T Pop()
{
if (_count == 0)
{
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
}
T item = _arr[--_count];
_arr[_count] = default(T);
return item;
}
public void Push(T item)
{
if (_arr.Length == _count)
{
T[] newArr = new T[_arr.Length * 2];
Array.Copy(_arr, 0, newArr, 0, _arr.Length);
_arr = newArr;
}
_arr[_count++] = item;
}
public void Clear()
{
Array.Clear(_arr, 0, _count);
_count = 0;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace HarmonyLib
{
/// <summary>A reflection helper to read and write private elements</summary>
/// <typeparam name="T">The result type defined by GetValue()</typeparam>
///
public class Traverse<T>
{
readonly Traverse traverse;
Traverse()
{
}
/// <summary>Creates a traverse instance from an existing instance</summary>
/// <param name="traverse">The existing <see cref="Traverse"/> instance</param>
///
public Traverse(Traverse traverse)
{
this.traverse = traverse;
}
/// <summary>Gets/Sets the current value</summary>
/// <value>The value to read or write</value>
///
public T Value
{
get => traverse.GetValue<T>();
set => traverse.SetValue(value);
}
}
/// <summary>A reflection helper to read and write private elements</summary>
///
public class Traverse
{
static readonly AccessCache Cache;
readonly Type _type;
readonly object _root;
readonly MemberInfo _info;
readonly MethodBase _method;
readonly object[] _params;
[MethodImpl(MethodImplOptions.Synchronized)]
static Traverse()
{
if (Cache is null)
Cache = new AccessCache();
}
/// <summary>Creates a new traverse instance from a class/type</summary>
/// <param name="type">The class/type</param>
/// <returns>A <see cref="Traverse"/> instance</returns>
///
public static Traverse Create(Type type)
{
return new Traverse(type);
}
/// <summary>Creates a new traverse instance from a class T</summary>
/// <typeparam name="T">The class</typeparam>
/// <returns>A <see cref="Traverse"/> instance</returns>
///
public static Traverse Create<T>()
{
return Create(typeof(T));
}
/// <summary>Creates a new traverse instance from an instance</summary>
/// <param name="root">The object</param>
/// <returns>A <see cref="Traverse"/> instance</returns>
///
public static Traverse Create(object root)
{
return new Traverse(root);
}
/// <summary>Creates a new traverse instance from a named type</summary>
/// <param name="name">The type name, for format see <see cref="AccessTools.TypeByName"/></param>
/// <returns>A <see cref="Traverse"/> instance</returns>
///
public static Traverse CreateWithType(string name)
{
return new Traverse(AccessTools.TypeByName(name));
}
/// <summary>Creates a new and empty traverse instance</summary>
///
Traverse()
{
}
/// <summary>Creates a new traverse instance from a class/type</summary>
/// <param name="type">The class/type</param>
///
public Traverse(Type type)
{
_type = type;
}
/// <summary>Creates a new traverse instance from an instance</summary>
/// <param name="root">The object</param>
///
public Traverse(object root)
{
_root = root;
_type = root?.GetType();
}
Traverse(object root, MemberInfo info, object[] index)
{
_root = root;
_type = root?.GetType() ?? info.GetUnderlyingType();
_info = info;
_params = index;
}
Traverse(object root, MethodInfo method, object[] parameter)
{
_root = root;
_type = method.ReturnType;
_method = method;
_params = parameter;
}
/// <summary>Gets the current value</summary>
/// <value>The value</value>
///
public object GetValue()
{
if (_info is FieldInfo)
return ((FieldInfo)_info).GetValue(_root);
if (_info is PropertyInfo)
return ((PropertyInfo)_info).GetValue(_root, AccessTools.all, null, _params, CultureInfo.CurrentCulture);
if (_method is object)
return _method.Invoke(_root, _params);
if (_root is null && _type is object) return _type;
return _root;
}
/// <summary>Gets the current value</summary>
/// <typeparam name="T">The type of the value</typeparam>
/// <value>The value</value>
///
public T GetValue<T>()
{
var value = GetValue();
if (value is null) return default;
return (T)value;
}
/// <summary>Invokes the current method with arguments and returns the result</summary>
/// <param name="arguments">The method arguments</param>
/// <value>The value returned by the method</value>
///
public object GetValue(params object[] arguments)
{
if (_method is null)
throw new Exception("cannot get method value without method");
return _method.Invoke(_root, arguments);
}
/// <summary>Invokes the current method with arguments and returns the result</summary>
/// <typeparam name="T">The type of the value</typeparam>
/// <param name="arguments">The method arguments</param>
/// <value>The value returned by the method</value>
///
public T GetValue<T>(params object[] arguments)
{
if (_method is null)
throw new Exception("cannot get method value without method");
return (T)_method.Invoke(_root, arguments);
}
/// <summary>Sets a value of the current field or property</summary>
/// <param name="value">The value</param>
/// <returns>The same traverse instance</returns>
///
public Traverse SetValue(object value)
{
if (_info is FieldInfo)
((FieldInfo)_info).SetValue(_root, value, AccessTools.all, null, CultureInfo.CurrentCulture);
if (_info is PropertyInfo)
((PropertyInfo)_info).SetValue(_root, value, AccessTools.all, null, _params, CultureInfo.CurrentCulture);
if (_method is object)
throw new Exception($"cannot set value of method {_method.FullDescription()}");
return this;
}
/// <summary>Gets the type of the current field or property</summary>
/// <returns>The type</returns>
///
public Type GetValueType()
{
if (_info is FieldInfo)
return ((FieldInfo)_info).FieldType;
if (_info is PropertyInfo)
return ((PropertyInfo)_info).PropertyType;
return null;
}
Traverse Resolve()
{
if (_root is null)
{
if (_info is FieldInfo fieldInfo && fieldInfo.IsStatic)
return new Traverse(GetValue());
if (_info is PropertyInfo propertyInfo && propertyInfo.GetGetMethod().IsStatic)
return new Traverse(GetValue());
if (_method is object && _method.IsStatic)
return new Traverse(GetValue());
if (_type is object)
return this;
}
return new Traverse(GetValue());
}
/// <summary>Moves the current traverse instance to a inner type</summary>
/// <param name="name">The type name</param>
/// <returns>A traverse instance</returns>
///
public Traverse Type(string name)
{
if (name is null) throw new ArgumentNullException(nameof(name));
if (_type is null) return new Traverse();
var type = AccessTools.Inner(_type, name);
if (type is null) return new Traverse();
return new Traverse(type);
}
/// <summary>Moves the current traverse instance to a field</summary>
/// <param name="name">The type name</param>
/// <returns>A traverse instance</returns>
///
public Traverse Field(string name)
{
if (name is null) throw new ArgumentNullException(nameof(name));
var resolved = Resolve();
if (resolved._type is null) return new Traverse();
var info = Cache.GetFieldInfo(resolved._type, name);
if (info is null) return new Traverse();
if (info.IsStatic is false && resolved._root is null) return new Traverse();
return new Traverse(resolved._root, info, null);
}
/// <summary>Moves the current traverse instance to a field</summary>
/// <typeparam name="T">The type of the field</typeparam>
/// <param name="name">The type name</param>
/// <returns>A traverse instance</returns>
///
public Traverse<T> Field<T>(string name)
{
return new Traverse<T>(Field(name));
}
/// <summary>Gets all fields of the current type</summary>
/// <returns>A list of field names</returns>
///
public List<string> Fields()
{
var resolved = Resolve();
return AccessTools.GetFieldNames(resolved._type);
}
/// <summary>Moves the current traverse instance to a property</summary>
/// <param name="name">The type name</param>
/// <param name="index">Optional property index</param>
/// <returns>A traverse instance</returns>
///
public Traverse Property(string name, object[] index = null)
{
if (name is null) throw new ArgumentNullException(nameof(name));
var resolved = Resolve();
if (resolved._type is null) return new Traverse();
var info = Cache.GetPropertyInfo(resolved._type, name);
if (info is null) return new Traverse();
return new Traverse(resolved._root, info, index);
}
/// <summary>Moves the current traverse instance to a field</summary>
/// <typeparam name="T">The type of the property</typeparam>
/// <param name="name">The type name</param>
/// <param name="index">Optional property index</param>
/// <returns>A traverse instance</returns>
///
public Traverse<T> Property<T>(string name, object[] index = null)
{
return new Traverse<T>(Property(name, index));
}
/// <summary>Gets all properties of the current type</summary>
/// <returns>A list of property names</returns>
///
public List<string> Properties()
{
var resolved = Resolve();
return AccessTools.GetPropertyNames(resolved._type);
}
/// <summary>Moves the current traverse instance to a method</summary>
/// <param name="name">The name of the method</param>
/// <param name="arguments">The arguments defining the argument types of the method overload</param>
/// <returns>A traverse instance</returns>
///
public Traverse Method(string name, params object[] arguments)
{
if (name is null) throw new ArgumentNullException(nameof(name));
var resolved = Resolve();
if (resolved._type is null) return new Traverse();
var types = AccessTools.GetTypes(arguments);
var method = Cache.GetMethodInfo(resolved._type, name, types);
if (method is null) return new Traverse();
return new Traverse(resolved._root, (MethodInfo)method, arguments);
}
/// <summary>Moves the current traverse instance to a method</summary>
/// <param name="name">The name of the method</param>
/// <param name="paramTypes">The argument types of the method</param>
/// <param name="arguments">The arguments for the method</param>
/// <returns>A traverse instance</returns>
///
public Traverse Method(string name, Type[] paramTypes, object[] arguments = null)
{
if (name is null) throw new ArgumentNullException(nameof(name));
var resolved = Resolve();
if (resolved._type is null) return new Traverse();
var method = Cache.GetMethodInfo(resolved._type, name, paramTypes);
if (method is null) return new Traverse();
return new Traverse(resolved._root, (MethodInfo)method, arguments);
}
/// <summary>Gets all methods of the current type</summary>
/// <returns>A list of method names</returns>
///
public List<string> Methods()
{
var resolved = Resolve();
return AccessTools.GetMethodNames(resolved._type);
}
/// <summary>Checks if the current traverse instance is for a field</summary>
/// <returns>True if its a field</returns>
///
public bool FieldExists()
{
return _info is object && _info is FieldInfo;
}
/// <summary>Checks if the current traverse instance is for a property</summary>
/// <returns>True if its a property</returns>
///
public bool PropertyExists()
{
return _info is object && _info is PropertyInfo;
}
/// <summary>Checks if the current traverse instance is for a method</summary>
/// <returns>True if its a method</returns>
///
public bool MethodExists()
{
return _method is object;
}
/// <summary>Checks if the current traverse instance is for a type</summary>
/// <returns>True if its a type</returns>
///
public bool TypeExists()
{
return _type is object;
}
/// <summary>Iterates over all fields of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="action">The action receiving a <see cref="Traverse"/> instance for each field</param>
///
public static void IterateFields(object source, Action<Traverse> action)
{
var sourceTrv = Create(source);
AccessTools.GetFieldNames(source).ForEach(f => action(sourceTrv.Field(f)));
}
/// <summary>Iterates over all fields of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="target">Target object</param>
/// <param name="action">The action receiving a pair of <see cref="Traverse"/> instances for each field pair</param>
///
public static void IterateFields(object source, object target, Action<Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetFieldNames(source).ForEach(f => action(sourceTrv.Field(f), targetTrv.Field(f)));
}
/// <summary>Iterates over all fields of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="target">Target object</param>
/// <param name="action">The action receiving a dot path representing the field pair and the <see cref="Traverse"/> instances</param>
///
public static void IterateFields(object source, object target, Action<string, Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetFieldNames(source).ForEach(f => action(f, sourceTrv.Field(f), targetTrv.Field(f)));
}
/// <summary>Iterates over all properties of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="action">The action receiving a <see cref="Traverse"/> instance for each property</param>
///
public static void IterateProperties(object source, Action<Traverse> action)
{
var sourceTrv = Create(source);
AccessTools.GetPropertyNames(source).ForEach(f => action(sourceTrv.Property(f)));
}
/// <summary>Iterates over all properties of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="target">Target object</param>
/// <param name="action">The action receiving a pair of <see cref="Traverse"/> instances for each property pair</param>
///
public static void IterateProperties(object source, object target, Action<Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetPropertyNames(source).ForEach(f => action(sourceTrv.Property(f), targetTrv.Property(f)));
}
/// <summary>Iterates over all properties of the current type and executes a traverse action</summary>
/// <param name="source">Original object</param>
/// <param name="target">Target object</param>
/// <param name="action">The action receiving a dot path representing the property pair and the <see cref="Traverse"/> instances</param>
///
public static void IterateProperties(object source, object target, Action<string, Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetPropertyNames(source).ForEach(f => action(f, sourceTrv.Property(f), targetTrv.Property(f)));
}
/// <summary>A default field action that copies fields to fields</summary>
///
public static Action<Traverse, Traverse> CopyFields = (from, to) => { _ = to.SetValue(from.GetValue()); };
/// <summary>Returns a string that represents the current traverse</summary>
/// <returns>A string representation</returns>
///
public override string ToString()
{
var value = _method ?? GetValue();
return value?.ToString();
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: JournalConverter.cs
//
// Description: Implements the Converter to limit journal views to 9 items.
//
// Created: 1/31/05 by SujalP
//
// Copyright (C) 2005 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
// Disable unknown #pragma warning for pragmas we use to exclude certain PreSharp violations
#pragma warning disable 1634, 1691
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Data;
using MS.Internal;
namespace System.Windows.Navigation
{
/// <summary>
/// This class returns an IEnumerable that is limited in length - it is used by the NavigationWindow
/// style to limit how many entries are shown in the back and forward drop down buttons. Not
/// intended to be used in any other situations.
/// </summary>
public sealed class JournalEntryListConverter : IValueConverter
{
/// <summary>
/// This method from IValueConverter returns an IEnumerable which in turn will yield the
/// ViewLimit limited collection of journal back and forward stack entries.
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
#pragma warning disable 6506
return (value != null) ? ((JournalEntryStack)value).GetLimitedJournalEntryStackEnumerable() : null;
#pragma warning restore 6506
}
/// <summary>
/// This method from IValueConverter returns an IEnumerable which was originally passed to Convert
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
/// <summary>
/// Describes the position of the journal entry relative to the current page.
/// </summary>
public enum JournalEntryPosition
{
/// <summary>
/// The entry is on the BackStack
/// </summary>
Back,
/// <summary>
/// The current page
/// </summary>
Current,
/// <summary>
/// The entry on the ForwardStack
/// </summary>
Forward,
}
/// <summary>
/// Puts all of the journal entries into a single list, for an IE7-style menu.
/// </summary>
public sealed class JournalEntryUnifiedViewConverter : IMultiValueConverter
{
/// <summary>
/// The DependencyProperty for the JournalEntryPosition property.
/// </summary>
public static readonly DependencyProperty JournalEntryPositionProperty =
DependencyProperty.RegisterAttached(
"JournalEntryPosition",
typeof(JournalEntryPosition),
typeof(JournalEntryUnifiedViewConverter),
new PropertyMetadata(JournalEntryPosition.Current));
/// <summary>
/// Helper for reading the JournalEntryPosition property.
/// </summary>
public static JournalEntryPosition GetJournalEntryPosition(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return ((JournalEntryPosition)element.GetValue(JournalEntryPositionProperty));
}
/// <summary>
/// Helper for setting the JournalEntryPosition property.
/// </summary>
public static void SetJournalEntryPosition(DependencyObject element, JournalEntryPosition position)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(JournalEntryPositionProperty, position);
}
/// <summary>
/// This method from IValueConverter returns an IEnumerable which in turn will yield the
/// single list containing all of the menu items.
/// </summary>
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values != null && values.Length == 2)
{
JournalEntryStack backStack = values[0] as JournalEntryStack;
JournalEntryStack forwardStack = values[1] as JournalEntryStack;
if (backStack != null && forwardStack != null)
{
LimitedJournalEntryStackEnumerable limitedBackStack = (LimitedJournalEntryStackEnumerable)backStack.GetLimitedJournalEntryStackEnumerable();
LimitedJournalEntryStackEnumerable limitedForwardStack = (LimitedJournalEntryStackEnumerable)forwardStack.GetLimitedJournalEntryStackEnumerable();
return new UnifiedJournalEntryStackEnumerable(limitedBackStack, limitedForwardStack);
}
}
return null;
}
/// <summary>
/// This method is unused.
/// </summary>
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return new object[] { Binding.DoNothing };
}
}
// Merges LimitedBack and Forward Stack into one list and
internal class UnifiedJournalEntryStackEnumerable : IEnumerable, INotifyCollectionChanged
{
internal UnifiedJournalEntryStackEnumerable(LimitedJournalEntryStackEnumerable backStack, LimitedJournalEntryStackEnumerable forwardStack)
{
_backStack = backStack;
_backStack.CollectionChanged += new NotifyCollectionChangedEventHandler(StacksChanged);
_forwardStack = forwardStack;
_forwardStack.CollectionChanged += new NotifyCollectionChangedEventHandler(StacksChanged);
}
public IEnumerator GetEnumerator()
{
if (_items == null)
{
// Reserve space so this will not have to reallocate. The most it will ever be is
// 9 for the forward stack, 9 for the back stack, 1 for the title bar
_items = new ArrayList(19);
// Add ForwardStack in reverse order
foreach (JournalEntry o in _forwardStack)
{
_items.Insert(0, o);
JournalEntryUnifiedViewConverter.SetJournalEntryPosition(o, JournalEntryPosition.Forward);
}
DependencyObject current = new DependencyObject();
current.SetValue(JournalEntry.NameProperty, SR.Get(SRID.NavWindowMenuCurrentPage));
// "Current Page"
_items.Add(current);
foreach (JournalEntry o in _backStack)
{
_items.Add(o);
JournalEntryUnifiedViewConverter.SetJournalEntryPosition(o, JournalEntryPosition.Back);
}
}
return _items.GetEnumerator();
}
internal void StacksChanged(object sender, NotifyCollectionChangedEventArgs e)
{
_items = null;
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
private LimitedJournalEntryStackEnumerable _backStack, _forwardStack;
private ArrayList _items;
}
}
| |
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 WebAPIDI.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;
}
}
}
| |
// 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.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
/// <summary>Characters that can't be used in a pipe's name.</summary>
private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>Prefix to prepend to all pipe names.</summary>
private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_");
internal static string GetPipePath(string serverName, string pipeName)
{
if (serverName != "." && serverName != Interop.Sys.GetHostName())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
}
if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
// Match Windows constraint
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0)
{
// Since pipes are stored as files in the file system, we don't support
// pipe names that are actually paths or that otherwise have invalid
// filename characters in them.
throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars);
}
// Return the pipe path. The pipe is created directly under %TMPDIR%. We don't bother
// putting it into subdirectories, as the pipe will only exist on disk for the
// duration between when the server starts listening and the client connects, after
// which the pipe will be deleted.
return s_pipePrefix + pipeName;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
if (safePipeHandle.NamedPipeSocket == null)
{
Interop.Sys.FileStatus status;
int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
(status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
[SecurityCritical]
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
private void UninitializeAsyncHandle()
{
// nop
}
private unsafe int ReadCore(Span<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, receive on the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Read syscall as is done
// for reading an anonymous pipe. However, for a non-blocking socket, Read could
// end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case
// is already handled by Socket.Receive, so we use it here.
try
{
return socket.Receive(buffer, SocketFlags.None);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, read from the file descriptor.
fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference())
{
int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length));
Debug.Assert(result <= buffer.Length);
return result;
}
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, send to the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Write syscall as is done
// for writing to anonymous pipe. However, for a non-blocking socket, Write could
// end up returning EWOULDBLOCK rather than blocking waiting for space available.
// Such a case is already handled by Socket.Send, so we use it here.
try
{
while (buffer.Length > 0)
{
int bytesWritten = socket.Send(buffer, SocketFlags.None);
buffer = buffer.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, write the file descriptor.
fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference())
{
while (buffer.Length > 0)
{
int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length));
buffer = buffer.Slice(bytesWritten);
}
}
}
private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
Socket socket = InternalHandle.NamedPipeSocket;
try
{
// TODO #22608:
// Remove all of this cancellation workaround once Socket.ReceiveAsync
// that accepts a CancellationToken is available.
// If a cancelable token is used and there's no data, issue a zero-length read so that
// we're asynchronously notified when data is available, and concurrently monitor the
// supplied cancellation token. If cancellation is requested, we will end up "leaking"
// the zero-length read until data becomes available, at which point it'll be satisfied.
// But it's very rare to reuse a stream after an operation has been canceled, so even if
// we do incur such a situation, it's likely to be very short lived.
if (cancellationToken.CanBeCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
if (socket.Available == 0)
{
Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None);
if (!t.IsCompletedSuccessfully)
{
var cancelTcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs))
{
if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false))
{
t.GetAwaiter().GetResult(); // propagate any failure
}
cancellationToken.ThrowIfCancellationRequested();
// At this point there was data available. In the rare case where multiple concurrent
// ReadAsyncs are issued against the PipeStream, worst case is the reads that lose
// the race condition for the data will end up in a non-cancelable state as part of
// the actual async receive operation.
}
}
}
}
// Issue the asynchronous read.
return await (destination.TryGetArray(out ArraySegment<byte> buffer) ?
socket.ReceiveAsync(buffer, SocketFlags.None) :
socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
// TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync
// accepts a Memory<T> in the near future.
byte[] buffer;
int offset, count;
if (source.DangerousTryGetArray(out ArraySegment<byte> segment))
{
buffer = segment.Array;
offset = segment.Offset;
count = segment.Count;
}
else
{
buffer = source.ToArray();
offset = 0;
count = buffer.Length;
}
while (count > 0)
{
// cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if
// cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and
// most writes will complete immediately as they simply store data into the socket's buffer. The only time we end
// up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation.
cancellationToken.ThrowIfCancellationRequested();
int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
Debug.Assert(bytesWritten <= count);
count -= bytesWritten;
offset += bytesWritten;
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private IOException GetIOExceptionForSocketException(SocketException e)
{
if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
{
State = PipeState.Broken;
}
return new IOException(e.Message, e);
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// For named pipes on sockets, we could potentially partially implement this
// via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However,
// that would require polling, and it wouldn't actually mean that the other
// end has read all of the data, just that the data has left this end's buffer.
throw new PlatformNotSupportedException(); // not fully implementable on unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static void CreateDirectory(string directoryPath)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(
HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe
int* fds = stackalloc int[2];
CreateAnonymousPipe(inheritability, fds);
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
internal int CheckPipeCall(int result)
{
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException(); // OS does not support getting pipe size
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, just return the buffer size that was passed to the constructor.
return _handle != null ?
CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
_outBufferSize;
}
internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
{
var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
Interop.Sys.PipeFlags.O_CLOEXEC : 0;
Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags));
}
internal static void ConfigureSocket(
Socket s, SafePipeHandle pipeHandle,
PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
{
if (inBufferSize > 0)
{
s.ReceiveBufferSize = inBufferSize;
}
if (outBufferSize > 0)
{
s.SendBufferSize = outBufferSize;
}
if (inheritability != HandleInheritability.Inheritable)
{
Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt
}
switch (direction)
{
case PipeDirection.In:
s.Shutdown(SocketShutdown.Send);
break;
case PipeDirection.Out:
s.Shutdown(SocketShutdown.Receive);
break;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace SocketHttpListener.Net
{
/// <summary>
/// Provides a collection container for instances of the <see cref="Cookie"/> class.
/// </summary>
[Serializable]
public class CookieCollection : ICollection, IEnumerable
{
#region Private Fields
private List<Cookie> _list;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CookieCollection"/> class.
/// </summary>
public CookieCollection ()
{
_list = new List<Cookie> ();
}
#endregion
#region Internal Properties
internal IList<Cookie> List {
get {
return _list;
}
}
internal IEnumerable<Cookie> Sorted {
get {
var list = new List<Cookie> (_list);
if (list.Count > 1)
list.Sort (compareCookieWithinSorted);
return list;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of cookies in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of cookies in the collection.
/// </value>
public int Count {
get {
return _list.Count;
}
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
/// <value>
/// <c>true</c> if the collection is read-only; otherwise, <c>false</c>.
/// The default value is <c>true</c>.
/// </value>
public bool IsReadOnly {
// LAMESPEC: So how is one supposed to create a writable CookieCollection instance?
// We simply ignore this property, as this collection is always writable.
get {
return true;
}
}
/// <summary>
/// Gets a value indicating whether the access to the collection is thread safe.
/// </summary>
/// <value>
/// <c>true</c> if the access to the collection is thread safe; otherwise, <c>false</c>.
/// The default value is <c>false</c>.
/// </value>
public bool IsSynchronized {
get {
return false;
}
}
/// <summary>
/// Gets the <see cref="Cookie"/> at the specified <paramref name="index"/> from
/// the collection.
/// </summary>
/// <value>
/// A <see cref="Cookie"/> at the specified <paramref name="index"/> in the collection.
/// </value>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the <see cref="Cookie"/>
/// to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public Cookie this [int index] {
get {
if (index < 0 || index >= _list.Count)
throw new ArgumentOutOfRangeException ("index");
return _list [index];
}
}
/// <summary>
/// Gets the <see cref="Cookie"/> with the specified <paramref name="name"/> from
/// the collection.
/// </summary>
/// <value>
/// A <see cref="Cookie"/> with the specified <paramref name="name"/> in the collection.
/// </value>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the <see cref="Cookie"/> to find.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
public Cookie this [string name] {
get {
if (name == null)
throw new ArgumentNullException ("name");
foreach (var cookie in Sorted)
if (cookie.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase))
return cookie;
return null;
}
}
/// <summary>
/// Gets an object used to synchronize access to the collection.
/// </summary>
/// <value>
/// An <see cref="Object"/> used to synchronize access to the collection.
/// </value>
public Object SyncRoot {
get {
return _sync ?? (_sync = ((ICollection) _list).SyncRoot);
}
}
#endregion
#region Private Methods
private static int compareCookieWithinSort (Cookie x, Cookie y)
{
return (x.Name.Length + x.Value.Length) - (y.Name.Length + y.Value.Length);
}
private static int compareCookieWithinSorted (Cookie x, Cookie y)
{
var ret = 0;
return (ret = x.Version - y.Version) != 0
? ret
: (ret = x.Name.CompareTo (y.Name)) != 0
? ret
: y.Path.Length - x.Path.Length;
}
private static CookieCollection parseRequest (string value)
{
var cookies = new CookieCollection ();
Cookie cookie = null;
var version = 0;
var pairs = splitCookieHeaderValue (value);
for (int i = 0; i < pairs.Length; i++) {
var pair = pairs [i].Trim ();
if (pair.Length == 0)
continue;
if (pair.StartsWith ("$version", StringComparison.InvariantCultureIgnoreCase)) {
version = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
}
else if (pair.StartsWith ("$path", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Path = pair.GetValueInternal ("=");
}
else if (pair.StartsWith ("$domain", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Domain = pair.GetValueInternal ("=");
}
else if (pair.StartsWith ("$port", StringComparison.InvariantCultureIgnoreCase)) {
var port = pair.Equals ("$port", StringComparison.InvariantCultureIgnoreCase)
? "\"\""
: pair.GetValueInternal ("=");
if (cookie != null)
cookie.Port = port;
}
else {
if (cookie != null)
cookies.Add (cookie);
string name;
string val = String.Empty;
var pos = pair.IndexOf ('=');
if (pos == -1) {
name = pair;
}
else if (pos == pair.Length - 1) {
name = pair.Substring (0, pos).TrimEnd (' ');
}
else {
name = pair.Substring (0, pos).TrimEnd (' ');
val = pair.Substring (pos + 1).TrimStart (' ');
}
cookie = new Cookie (name, val);
if (version != 0)
cookie.Version = version;
}
}
if (cookie != null)
cookies.Add (cookie);
return cookies;
}
private static CookieCollection parseResponse (string value)
{
var cookies = new CookieCollection ();
Cookie cookie = null;
var pairs = splitCookieHeaderValue (value);
for (int i = 0; i < pairs.Length; i++) {
var pair = pairs [i].Trim ();
if (pair.Length == 0)
continue;
if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Version = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
}
else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
var buffer = new StringBuilder (pair.GetValueInternal ("="), 32);
if (i < pairs.Length - 1)
buffer.AppendFormat (", {0}", pairs [++i].Trim ());
DateTime expires;
if (!DateTime.TryParseExact (
buffer.ToString (),
new [] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
CultureInfo.CreateSpecificCulture ("en-US"),
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
out expires))
expires = DateTime.Now;
if (cookie != null && cookie.Expires == DateTime.MinValue)
cookie.Expires = expires.ToLocalTime ();
}
else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
var max = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
var expires = DateTime.Now.AddSeconds ((double) max);
if (cookie != null)
cookie.Expires = expires;
}
else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Path = pair.GetValueInternal ("=");
}
else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Domain = pair.GetValueInternal ("=");
}
else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
? "\"\""
: pair.GetValueInternal ("=");
if (cookie != null)
cookie.Port = port;
}
else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Comment = pair.GetValueInternal ("=").UrlDecode ();
}
else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.CommentUri = pair.GetValueInternal ("=").Trim ('"').ToUri ();
}
else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Discard = true;
}
else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Secure = true;
}
else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.HttpOnly = true;
}
else {
if (cookie != null)
cookies.Add (cookie);
string name;
string val = String.Empty;
var pos = pair.IndexOf ('=');
if (pos == -1) {
name = pair;
}
else if (pos == pair.Length - 1) {
name = pair.Substring (0, pos).TrimEnd (' ');
}
else {
name = pair.Substring (0, pos).TrimEnd (' ');
val = pair.Substring (pos + 1).TrimStart (' ');
}
cookie = new Cookie (name, val);
}
}
if (cookie != null)
cookies.Add (cookie);
return cookies;
}
private int searchCookie (Cookie cookie)
{
var name = cookie.Name;
var path = cookie.Path;
var domain = cookie.Domain;
var version = cookie.Version;
for (int i = _list.Count - 1; i >= 0; i--) {
var c = _list [i];
if (c.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase) &&
c.Path.Equals (path, StringComparison.InvariantCulture) &&
c.Domain.Equals (domain, StringComparison.InvariantCultureIgnoreCase) &&
c.Version == version)
return i;
}
return -1;
}
private static string [] splitCookieHeaderValue (string value)
{
return new List<string> (value.SplitHeaderValue (',', ';')).ToArray ();
}
#endregion
#region Internal Methods
internal static CookieCollection Parse (string value, bool response)
{
return response
? parseResponse (value)
: parseRequest (value);
}
internal void SetOrRemove (Cookie cookie)
{
var pos = searchCookie (cookie);
if (pos == -1) {
if (!cookie.Expired)
_list.Add (cookie);
return;
}
if (!cookie.Expired) {
_list [pos] = cookie;
return;
}
_list.RemoveAt (pos);
}
internal void SetOrRemove (CookieCollection cookies)
{
foreach (Cookie cookie in cookies)
SetOrRemove (cookie);
}
internal void Sort ()
{
if (_list.Count > 1)
_list.Sort (compareCookieWithinSort);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="cookie"/> to the collection.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void Add (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
var pos = searchCookie (cookie);
if (pos == -1) {
_list.Add (cookie);
return;
}
_list [pos] = cookie;
}
/// <summary>
/// Adds the specified <paramref name="cookies"/> to the collection.
/// </summary>
/// <param name="cookies">
/// A <see cref="CookieCollection"/> that contains the cookies to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookies"/> is <see langword="null"/>.
/// </exception>
public void Add (CookieCollection cookies)
{
if (cookies == null)
throw new ArgumentNullException ("cookies");
foreach (Cookie cookie in cookies)
Add (cookie);
}
/// <summary>
/// Copies the elements of the collection to the specified <see cref="Array"/>, starting at
/// the specified <paramref name="index"/> in the <paramref name="array"/>.
/// </summary>
/// <param name="array">
/// An <see cref="Array"/> that represents the destination of the elements copied from
/// the collection.
/// </param>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/>
/// at which copying begins.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="array"/> is multidimensional.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The number of elements in the collection is greater than the available space from
/// <paramref name="index"/> to the end of the destination <paramref name="array"/>.
/// </para>
/// </exception>
/// <exception cref="InvalidCastException">
/// The elements in the collection cannot be cast automatically to the type of the destination
/// <paramref name="array"/>.
/// </exception>
public void CopyTo (Array array, int index)
{
if (array == null)
throw new ArgumentNullException ("array");
if (index < 0)
throw new ArgumentOutOfRangeException ("index", "Less than zero.");
if (array.Rank > 1)
throw new ArgumentException ("Multidimensional.", "array");
if (array.Length - index < _list.Count)
throw new ArgumentException (
"The number of elements in this collection is greater than the available space of the destination array.");
if (!array.GetType ().GetElementType ().IsAssignableFrom (typeof (Cookie)))
throw new InvalidCastException (
"The elements in this collection cannot be cast automatically to the type of the destination array.");
((IList) _list).CopyTo (array, index);
}
/// <summary>
/// Copies the elements of the collection to the specified array of <see cref="Cookie"/>,
/// starting at the specified <paramref name="index"/> in the <paramref name="array"/>.
/// </summary>
/// <param name="array">
/// An array of <see cref="Cookie"/> that represents the destination of the elements
/// copied from the collection.
/// </param>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/>
/// at which copying begins.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
/// <exception cref="ArgumentException">
/// The number of elements in the collection is greater than the available space from
/// <paramref name="index"/> to the end of the destination <paramref name="array"/>.
/// </exception>
public void CopyTo (Cookie [] array, int index)
{
if (array == null)
throw new ArgumentNullException ("array");
if (index < 0)
throw new ArgumentOutOfRangeException ("index", "Less than zero.");
if (array.Length - index < _list.Count)
throw new ArgumentException (
"The number of elements in this collection is greater than the available space of the destination array.");
_list.CopyTo (array, index);
}
/// <summary>
/// Gets the enumerator used to iterate through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance used to iterate through the collection.
/// </returns>
public IEnumerator GetEnumerator ()
{
return _list.GetEnumerator ();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using Max.Domain.Mapping;
using Max.Domain.Mapping.Implementation;
using Sample.Contracts;
namespace Sample.WcfService.Mapping
{
public static partial class GeneratedMapperExtensions
{
#region Mapper extionsions for Contact
public static Collection<Contact> MapToContactCollection(this Mapper mapper, IEnumerable<Sample.Business.Contact> source)
{
Collection<Contact> target = new Collection<Contact>();
foreach(var item in source) target.Add(mapper.MapToContact(item));
return target;
}
public static Contact MapToContact(this Mapper mapper, Sample.Business.Contact source)
{
if (source == null)
return null;
else
return mapper.MapToContact(source, new Contact());
}
internal static Contact MapToContact(this Mapper mapper, Sample.Business.Contact source, Contact target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Contact)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateContact(source, target);
// Return mapped target:
return target;
}
internal static void UpdateContact(this Mapper mapper, Sample.Business.Contact source, Contact target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Contact on.");
// Perform base type mapping:
mapper.UpdateBaseObject(source, target);
// Perform mapping of properties:
target.Id = source.ContactID;
target.Title = source.Title;
target.FirstName = source.FirstName;
target.MiddleName = source.MiddleName;
target.LastName = source.LastName;
target.Suffix = source.Suffix;
target.EmailAddress = source.EmailAddress;
target.Phone = source.Phone;
// Call partial AfterUpdate method:
AfterUpdateContact(mapper, source, target);
}
static partial void AfterUpdateContact(this Mapper mapper, Sample.Business.Contact source, Contact target);
#endregion
#region Mapper extionsions for Employee
public static Collection<Employee> MapToEmployeeCollection(this Mapper mapper, IEnumerable<Sample.Business.Employee> source)
{
Collection<Employee> target = new Collection<Employee>();
foreach(var item in source) target.Add(mapper.MapToEmployee(item));
return target;
}
public static Employee MapToEmployee(this Mapper mapper, Sample.Business.Employee source)
{
if (source == null)
return null;
else if (source is Sample.Business.SalesPerson)
return mapper.MapToSalesPerson((Sample.Business.SalesPerson)source);
else
return mapper.MapToEmployee(source, new Employee());
}
internal static Employee MapToEmployee(this Mapper mapper, Sample.Business.Employee source, Employee target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Employee)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateEmployee(source, target);
// Return mapped target:
return target;
}
internal static void UpdateEmployee(this Mapper mapper, Sample.Business.Employee source, Employee target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Employee on.");
// Perform base type mapping:
mapper.UpdateSystemObject(source, target);
// Perform mapping of properties:
target.Id = source.EmployeeID;
target.Contact = mapper.MapToContact(source.Contact);
target.Gender = source.Gender;
target.BirthDate = source.BirthDate;
target.HireDate = source.HireDate;
target.ManagerId = source.ManagerID;
// Call partial AfterUpdate method:
AfterUpdateEmployee(mapper, source, target);
}
static partial void AfterUpdateEmployee(this Mapper mapper, Sample.Business.Employee source, Employee target);
#endregion
#region Mapper extionsions for EmployeeItem
public static Collection<EmployeeItem> MapToEmployeeItemCollection(this Mapper mapper, IEnumerable<Sample.Business.Employee> source)
{
Collection<EmployeeItem> target = new Collection<EmployeeItem>();
foreach(var item in source) target.Add(mapper.MapToEmployeeItem(item));
return target;
}
public static EmployeeItem MapToEmployeeItem(this Mapper mapper, Sample.Business.Employee source)
{
if (source == null)
return null;
else
return mapper.MapToEmployeeItem(source, new EmployeeItem());
}
internal static EmployeeItem MapToEmployeeItem(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (EmployeeItem)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateEmployeeItem(source, target);
// Return mapped target:
return target;
}
internal static void UpdateEmployeeItem(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map EmployeeItem on.");
// Perform base type mapping:
mapper.UpdateSystemObject(source, target);
// Perform mapping of properties:
target.Id = source.EmployeeID;
target.Gender = source.Gender;
target.BirthDate = source.BirthDate;
target.ManagerId = source.ManagerID;
mapper.MapEmployeeItemTitleProperty(source, target);
mapper.MapEmployeeItemFirstNameProperty(source, target);
mapper.MapEmployeeItemMiddleNameProperty(source, target);
mapper.MapEmployeeItemLastNameProperty(source, target);
mapper.MapEmployeeItemManagerFirstNameProperty(source, target);
mapper.MapEmployeeItemManagerMiddleNameProperty(source, target);
mapper.MapEmployeeItemManagerLastNameProperty(source, target);
// Call partial AfterUpdate method:
AfterUpdateEmployeeItem(mapper, source, target);
}
static partial void AfterUpdateEmployeeItem(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target);
static void MapEmployeeItemTitleProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Contact;
if (item1 == null) break;
var item2 = item1.Title;
target.Title = item2;
} while (false);
}
static void MapEmployeeItemFirstNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Contact;
if (item1 == null) break;
var item2 = item1.FirstName;
target.FirstName = item2;
} while (false);
}
static void MapEmployeeItemMiddleNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Contact;
if (item1 == null) break;
var item2 = item1.MiddleName;
target.MiddleName = item2;
} while (false);
}
static void MapEmployeeItemLastNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Contact;
if (item1 == null) break;
var item2 = item1.LastName;
target.LastName = item2;
} while (false);
}
static void MapEmployeeItemManagerFirstNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Manager;
if (item1 == null) break;
var item2 = item1.Contact;
if (item2 == null) break;
var item3 = item2.FirstName;
target.ManagerFirstName = item3;
} while (false);
}
static void MapEmployeeItemManagerMiddleNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Manager;
if (item1 == null) break;
var item2 = item1.Contact;
if (item2 == null) break;
var item3 = item2.MiddleName;
target.ManagerMiddleName = item3;
} while (false);
}
static void MapEmployeeItemManagerLastNameProperty(this Mapper mapper, Sample.Business.Employee source, EmployeeItem target)
{
do
{
var item0 = source;
var item1 = item0.Manager;
if (item1 == null) break;
var item2 = item1.Contact;
if (item2 == null) break;
var item3 = item2.LastName;
target.ManagerLastName = item3;
} while (false);
}
#endregion
#region Mapper extionsions for Manager
public static Collection<Manager> MapToManagerCollection(this Mapper mapper, IEnumerable<Sample.Business.Employee> source)
{
Collection<Manager> target = new Collection<Manager>();
foreach(var item in source) target.Add(mapper.MapToManager(item));
return target;
}
public static Manager MapToManager(this Mapper mapper, Sample.Business.Employee source)
{
if (source == null)
return null;
else
return mapper.MapToManager(source, new Manager());
}
internal static Manager MapToManager(this Mapper mapper, Sample.Business.Employee source, Manager target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Manager)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateManager(source, target);
// Return mapped target:
return target;
}
internal static void UpdateManager(this Mapper mapper, Sample.Business.Employee source, Manager target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Manager on.");
// Perform base type mapping:
mapper.UpdateSystemObject(source, target);
// Perform mapping of properties:
target.Id = source.EmployeeID;
target.Contact = mapper.MapToContact(source.Contact);
target.Gender = source.Gender;
target.BirthDate = source.BirthDate;
target.HireDate = source.HireDate;
foreach(var item in source.Subordinates) target.Subordinates.Add(mapper.MapToSubordinate((Sample.Business.Employee)item));
// Call partial AfterUpdate method:
AfterUpdateManager(mapper, source, target);
}
static partial void AfterUpdateManager(this Mapper mapper, Sample.Business.Employee source, Manager target);
#endregion
#region Mapper extionsions for SalesPerson
public static Collection<SalesPerson> MapToSalesPersonCollection(this Mapper mapper, IEnumerable<Sample.Business.SalesPerson> source)
{
Collection<SalesPerson> target = new Collection<SalesPerson>();
foreach(var item in source) target.Add(mapper.MapToSalesPerson(item));
return target;
}
public static SalesPerson MapToSalesPerson(this Mapper mapper, Sample.Business.SalesPerson source)
{
if (source == null)
return null;
else
return mapper.MapToSalesPerson(source, new SalesPerson());
}
internal static SalesPerson MapToSalesPerson(this Mapper mapper, Sample.Business.SalesPerson source, SalesPerson target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (SalesPerson)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateSalesPerson(source, target);
// Return mapped target:
return target;
}
internal static void UpdateSalesPerson(this Mapper mapper, Sample.Business.SalesPerson source, SalesPerson target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map SalesPerson on.");
// Perform base type mapping:
mapper.UpdateEmployee(source, target);
// Perform mapping of properties:
target.SalesQuota = source.SalesQuota;
target.Bonus = source.Bonus;
target.CommissionPct = source.CommissionPct;
target.SalesYTD = source.SalesYTD;
mapper.MapSalesPersonTerritorySalesYTDProperty(source, target);
// Call partial AfterUpdate method:
AfterUpdateSalesPerson(mapper, source, target);
}
static partial void AfterUpdateSalesPerson(this Mapper mapper, Sample.Business.SalesPerson source, SalesPerson target);
static void MapSalesPersonTerritorySalesYTDProperty(this Mapper mapper, Sample.Business.SalesPerson source, SalesPerson target)
{
do
{
var item0 = source;
var item1 = item0.Territory;
if (item1 == null) break;
var item2 = item1.SalesYTD;
target.TerritorySalesYTD = item2;
} while (false);
}
#endregion
#region Mapper extionsions for Subordinate
public static Collection<Subordinate> MapToSubordinateCollection(this Mapper mapper, IEnumerable<Sample.Business.Employee> source)
{
Collection<Subordinate> target = new Collection<Subordinate>();
foreach(var item in source) target.Add(mapper.MapToSubordinate(item));
return target;
}
public static Subordinate MapToSubordinate(this Mapper mapper, Sample.Business.Employee source)
{
if (source == null)
return null;
else
return mapper.MapToSubordinate(source, new Subordinate());
}
internal static Subordinate MapToSubordinate(this Mapper mapper, Sample.Business.Employee source, Subordinate target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
// If so, return mapped instance:
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Subordinate)mappedTarget;
// Else, register mapping and map target:
mapper.RegisterMapping(source, target);
mapper.UpdateSubordinate(source, target);
// Return mapped target:
return target;
}
internal static void UpdateSubordinate(this Mapper mapper, Sample.Business.Employee source, Subordinate target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Subordinate on.");
// Perform base type mapping:
mapper.UpdateSystemObject(source, target);
// Perform mapping of properties:
target.Id = source.EmployeeID;
target.Contact = mapper.MapToContact(source.Contact);
target.Gender = source.Gender;
target.BirthDate = source.BirthDate;
target.HireDate = source.HireDate;
// Call partial AfterUpdate method:
AfterUpdateSubordinate(mapper, source, target);
}
static partial void AfterUpdateSubordinate(this Mapper mapper, Sample.Business.Employee source, Subordinate target);
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Scrollbar/Slider Control
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/UI/tk2dUIScrollbar")]
public class tk2dUIScrollbar : MonoBehaviour
{
/// <summary>
/// XAxis - horizontal, YAxis - vertical
/// </summary>
public enum Axes { XAxis, YAxis }
/// <summary>
/// Whole bar uiItem. Used to record clicks/touches to move thumb directly to that locations
/// </summary>
public tk2dUIItem barUIItem;
/// <summary>
/// Lenght of the scrollbar
/// </summary>
public float scrollBarLength;
/// <summary>
/// Scroll thumb button. Events will be taken from this.
/// </summary>
public tk2dUIItem thumbBtn;
/// <summary>
/// Generally same as thumbBtn, but sometimes you want a thumb that user can't interactive with.
/// </summary>
public Transform thumbTransform;
/// <summary>
/// Length of the scroll thumb
/// </summary>
public float thumbLength;
/// <summary>
/// Button up, moves list up. Not required.
/// </summary>
public tk2dUIItem upButton;
//direct reference to hover button of up button (if exists)
private tk2dUIHoverItem hoverUpButton;
/// <summary>
/// Button down, moves list down. Not required
/// </summary>
public tk2dUIItem downButton;
//direct reference to hover button of up button (if exists)
private tk2dUIHoverItem hoverDownButton;
/// <summary>
/// Disable up/down buttons will scroll
/// </summary>
public float buttonUpDownScrollDistance = 1f;
/// <summary>
/// Allows for mouse scroll wheel to scroll list while hovered. Requires hover to be active.
/// </summary>
public bool allowScrollWheel = true;
/// <summary>
/// Axes while scrolling will occur.
/// </summary>
public Axes scrollAxes = Axes.YAxis;
/// <summary>
/// Highlighted progress bar control used to move a highlighted bar. Not required.
/// </summary>
public tk2dUIProgressBar highlightProgressBar;
[SerializeField]
[HideInInspector]
private tk2dUILayout barLayoutItem = null;
public tk2dUILayout BarLayoutItem {
get { return barLayoutItem; }
set {
if (barLayoutItem != value) {
if (barLayoutItem != null) {
barLayoutItem.OnReshape -= LayoutReshaped;
}
barLayoutItem = value;
if (barLayoutItem != null) {
barLayoutItem.OnReshape += LayoutReshaped;
}
}
}
}
private bool isScrollThumbButtonDown = false;
private bool isTrackHoverOver = false;
private float percent = 0; //0-1
private Vector3 moveThumbBtnOffset = Vector3.zero;
//which, if any up down scrollbuttons are currently down
private int scrollUpDownButtonState = 0; //0=nothing, -1=up, 1-down
private float timeOfUpDownButtonPressStart = 0; //time of scroll up/down button press
private float repeatUpDownButtonHoldCounter = 0; //counts how many moves are made by holding
private const float WITHOUT_SCROLLBAR_FIXED_SCROLL_WHEEL_PERCENT = .1f; //distance to be scroll if not attached to ScrollableArea
private const float INITIAL_TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD = .55f;
private const float TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD = .45f;
/// <summary>
/// Event, on scrolling
/// </summary>
public event System.Action<tk2dUIScrollbar> OnScroll;
public string SendMessageOnScrollMethodName = "";
public GameObject SendMessageTarget
{
get
{
if (barUIItem != null)
{
return barUIItem.sendMessageTarget;
}
else return null;
}
set
{
if (barUIItem != null && barUIItem.sendMessageTarget != value)
{
barUIItem.sendMessageTarget = value;
#if UNITY_EDITOR
tk2dUtil.SetDirty(barUIItem);
#endif
}
}
}
/// <summary>
/// Percent scrolled. 0-1
/// </summary>
public float Value
{
get { return percent; }
set
{
percent = Mathf.Clamp(value, 0f, 1f);
if (OnScroll != null) { OnScroll(this); }
SetScrollThumbPosition();
if (SendMessageTarget != null && SendMessageOnScrollMethodName.Length > 0)
{
SendMessageTarget.SendMessage( SendMessageOnScrollMethodName, this, SendMessageOptions.RequireReceiver );
}
}
}
/// <summary>
/// Manually set scrolling percent without firing OnScroll event
/// </summary>
public void SetScrollPercentWithoutEvent(float newScrollPercent)
{
percent = Mathf.Clamp(newScrollPercent, 0f, 1f);
SetScrollThumbPosition();
}
void OnEnable()
{
if (barUIItem != null)
{
barUIItem.OnDown += ScrollTrackButtonDown;
barUIItem.OnHoverOver += ScrollTrackButtonHoverOver;
barUIItem.OnHoverOut += ScrollTrackButtonHoverOut;
}
if (thumbBtn != null)
{
thumbBtn.OnDown += ScrollThumbButtonDown;
thumbBtn.OnRelease += ScrollThumbButtonRelease;
}
if (upButton != null)
{
upButton.OnDown += ScrollUpButtonDown;
upButton.OnUp += ScrollUpButtonUp;
}
if (downButton != null)
{
downButton.OnDown += ScrollDownButtonDown;
downButton.OnUp += ScrollDownButtonUp;
}
if (barLayoutItem != null)
{
barLayoutItem.OnReshape += LayoutReshaped;
}
}
void OnDisable()
{
if (barUIItem != null)
{
barUIItem.OnDown -= ScrollTrackButtonDown;
barUIItem.OnHoverOver -= ScrollTrackButtonHoverOver;
barUIItem.OnHoverOut -= ScrollTrackButtonHoverOut;
}
if (thumbBtn != null)
{
thumbBtn.OnDown -= ScrollThumbButtonDown;
thumbBtn.OnRelease -= ScrollThumbButtonRelease;
}
if (upButton != null)
{
upButton.OnDown -= ScrollUpButtonDown;
upButton.OnUp -= ScrollUpButtonUp;
}
if (downButton != null)
{
downButton.OnDown -= ScrollDownButtonDown;
downButton.OnUp -= ScrollDownButtonUp;
}
if (isScrollThumbButtonDown)
{
if (tk2dUIManager.Instance__NoCreate != null)
{
tk2dUIManager.Instance.OnInputUpdate -= MoveScrollThumbButton;
}
isScrollThumbButtonDown = false;
}
if (isTrackHoverOver)
{
if (tk2dUIManager.Instance__NoCreate != null)
{
tk2dUIManager.Instance.OnScrollWheelChange -= TrackHoverScrollWheelChange;
}
isTrackHoverOver = false;
}
if (scrollUpDownButtonState != 0)
{
tk2dUIManager.Instance.OnInputUpdate -= CheckRepeatScrollUpDownButton;
scrollUpDownButtonState = 0;
}
if (barLayoutItem != null)
{
barLayoutItem.OnReshape -= LayoutReshaped;
}
}
void Awake()
{
if (upButton != null)
{
hoverUpButton = upButton.GetComponent<tk2dUIHoverItem>();
}
if (downButton != null)
{
hoverDownButton = downButton.GetComponent<tk2dUIHoverItem>();
}
}
void Start()
{
SetScrollThumbPosition();
}
private void TrackHoverScrollWheelChange(float mouseWheelChange)
{
if (mouseWheelChange > 0)
{
ScrollUpFixed();
}
else if(mouseWheelChange<0)
{
ScrollDownFixed();
}
}
private void SetScrollThumbPosition()
{
if (thumbTransform != null)
{
float pos= -((scrollBarLength - thumbLength) * Value)/* + ((scrollBarLength - thumbLength) / 2.0f)*/;
Vector3 thumbLocalPos = thumbTransform.localPosition;
if (scrollAxes == Axes.XAxis)
{
thumbLocalPos.x = -pos;
}
else if (scrollAxes == Axes.YAxis)
{
thumbLocalPos.y = pos;
}
thumbTransform.localPosition = thumbLocalPos;
}
if (highlightProgressBar != null)
{
highlightProgressBar.Value = Value;
}
}
private void MoveScrollThumbButton()
{
ScrollToPosition(CalculateClickWorldPos(thumbBtn) + moveThumbBtnOffset);
}
private Vector3 CalculateClickWorldPos(tk2dUIItem btn)
{
Camera viewingCamera = tk2dUIManager.Instance.GetUICameraForControl( gameObject );
Vector2 pos = btn.Touch.position;
Vector3 worldPos = viewingCamera.ScreenToWorldPoint(new Vector3(pos.x, pos.y, btn.transform.position.z - viewingCamera.transform.position.z));
worldPos.z = btn.transform.position.z;
return worldPos;
}
private void ScrollToPosition(Vector3 worldPos)
{
Vector3 localPos=thumbTransform.parent.InverseTransformPoint(worldPos);
float axisPos = 0;
if (scrollAxes == Axes.XAxis)
{
axisPos = localPos.x;
}
else if (scrollAxes == Axes.YAxis)
{
axisPos = -localPos.y;
}
Value = (axisPos / (scrollBarLength - thumbLength));
}
private void ScrollTrackButtonDown()
{
ScrollToPosition(CalculateClickWorldPos(barUIItem));
}
private void ScrollTrackButtonHoverOver()
{
if (allowScrollWheel)
{
if (!isTrackHoverOver)
{
tk2dUIManager.Instance.OnScrollWheelChange += TrackHoverScrollWheelChange;
}
isTrackHoverOver = true;
}
}
private void ScrollTrackButtonHoverOut()
{
if (isTrackHoverOver)
{
tk2dUIManager.Instance.OnScrollWheelChange -= TrackHoverScrollWheelChange;
}
isTrackHoverOver = false;
}
private void ScrollThumbButtonDown()
{
if (!isScrollThumbButtonDown)
{
tk2dUIManager.Instance.OnInputUpdate += MoveScrollThumbButton;
}
isScrollThumbButtonDown = true;
Vector3 newWorldPos = CalculateClickWorldPos(thumbBtn);
moveThumbBtnOffset = thumbBtn.transform.position - newWorldPos;
moveThumbBtnOffset.z = 0;
if (hoverUpButton != null)
{
hoverUpButton.IsOver = true;
}
if (hoverDownButton != null)
{
hoverDownButton.IsOver = true;
}
}
private void ScrollThumbButtonRelease()
{
if (isScrollThumbButtonDown)
{
tk2dUIManager.Instance.OnInputUpdate -= MoveScrollThumbButton;
}
isScrollThumbButtonDown = false;
if (hoverUpButton != null)
{
hoverUpButton.IsOver = false;
}
if (hoverDownButton != null)
{
hoverDownButton.IsOver = false;
}
}
private void ScrollUpButtonDown()
{
timeOfUpDownButtonPressStart = Time.realtimeSinceStartup;
repeatUpDownButtonHoldCounter = 0;
if (scrollUpDownButtonState == 0)
{
tk2dUIManager.Instance.OnInputUpdate += CheckRepeatScrollUpDownButton;
}
scrollUpDownButtonState = -1;
ScrollUpFixed();
}
private void ScrollUpButtonUp()
{
if (scrollUpDownButtonState != 0)
{
tk2dUIManager.Instance.OnInputUpdate -= CheckRepeatScrollUpDownButton;
}
scrollUpDownButtonState = 0;
}
private void ScrollDownButtonDown()
{
timeOfUpDownButtonPressStart = Time.realtimeSinceStartup;
repeatUpDownButtonHoldCounter = 0;
if (scrollUpDownButtonState == 0)
{
tk2dUIManager.Instance.OnInputUpdate += CheckRepeatScrollUpDownButton;
}
scrollUpDownButtonState = 1;
ScrollDownFixed();
}
private void ScrollDownButtonUp()
{
if (scrollUpDownButtonState != 0)
{
tk2dUIManager.Instance.OnInputUpdate -= CheckRepeatScrollUpDownButton;
}
scrollUpDownButtonState = 0;
}
public void ScrollUpFixed()
{
ScrollDirection(-1);
}
public void ScrollDownFixed()
{
ScrollDirection(1);
}
private void CheckRepeatScrollUpDownButton()
{
if (scrollUpDownButtonState != 0)
{
float timePassed = Time.realtimeSinceStartup - timeOfUpDownButtonPressStart;
if (repeatUpDownButtonHoldCounter == 0)
{
if (timePassed > INITIAL_TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD)
{
repeatUpDownButtonHoldCounter++;
timePassed -= INITIAL_TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD;
ScrollDirection(scrollUpDownButtonState);
}
}
else //greater then 0
{
if (timePassed > TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD)
{
repeatUpDownButtonHoldCounter++;
timePassed -= TIME_TO_REPEAT_UP_DOWN_SCROLL_BUTTON_SCROLLING_ON_HOLD;
ScrollDirection(scrollUpDownButtonState);
}
}
}
}
public void ScrollDirection(int dir)
{
if (scrollAxes == Axes.XAxis)
{
Value = Value - CalcScrollPercentOffsetButtonScrollDistance() * dir * buttonUpDownScrollDistance;
}
else
{
Value = Value + CalcScrollPercentOffsetButtonScrollDistance() * dir * buttonUpDownScrollDistance;
}
}
private float CalcScrollPercentOffsetButtonScrollDistance()
{
return WITHOUT_SCROLLBAR_FIXED_SCROLL_WHEEL_PERCENT;
}
private void LayoutReshaped(Vector3 dMin, Vector3 dMax)
{
scrollBarLength += (scrollAxes == Axes.XAxis) ? (dMax.x - dMin.x) : (dMax.y - dMin.y);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MO.Core.Window.Api {
public class RKernel32 {
/* BOOL WINAPI CloseHandle(
* __in HANDLE hObject) */
[DllImport("KERNEL32.DLL")]
public static extern bool CloseHandle(
IntPtr handle);
/* HANDLE WINAPI CreateRemoteThread(
* __in HANDLE hProcess,
* __in LPSECURITY_ATTRIBUTES lpThreadAttributes,
* __in SIZE_T dwStackSize,
* __in LPTHREAD_START_ROUTINE lpStartAddress,
* __in LPVOID lpParameter,
* __in DWORD dwCreationFlags,
* __out LPDWORD lpThreadId) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr CreateRemoteThread(
IntPtr hProcess,
int lpThreadAttributes,
int dwStackSize,
uint lpStartAddress,
IntPtr lpParameter,
int dwCreationFlags,
int lpThreadId);
/* HANDLE WINAPI CreateToolhelp32Snapshot(
* __in DWORD dwFlags,
* __in DWORD th32ProcessID) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr CreateToolhelp32Snapshot(
ETh32cs dwFlags,
int th32ProcessID);
/* BOOL WINAPI FreeLibrary(
* __in HMODULE hModule) */
[DllImport("kernel32")]
public extern static bool FreeLibrary(IntPtr hModule);
/* DWORD WINAPI GetCurrentThreadId(void); */
[DllImport("KERNEL32.DLL")]
public static extern int GetCurrentThreadId();
/* HMODULE GetModuleHandle(
* LPCTSTR lpModuleName
* ) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr GetModuleHandle(
string lpModuleName);
/* BOOL WINAPI GetExitCodeThread(
* __in HANDLE hThread,
* __out LPDWORD lpExitCode) */
[DllImport("KERNEL32.DLL")]
public static extern bool GetExitCodeThread(
IntPtr hThread,
ref uint lpExitCode);
/* WINBASEAPI DWORD WINAPI GetLastError(VOID) */
[DllImport("KERNEL32.DLL")]
public static extern int GetLastError();
/* FARPROC WINAPI GetProcAddress(
* __in HMODULE hModule,
* __in LPCSTR lpProcName) */
[DllImport("kernel32", CharSet = CharSet.Ansi)]
public extern static IntPtr GetProcAddress(
IntPtr hModule,
string lpProcName);
/* void WINAPI GetSystemInfo(
* __out LPSYSTEM_INFO lpSystemInfo) */
[DllImport("KERNEL32.DLL")]
public static extern void GetSystemInfo(ref SSystemInfo pSI);
/* PVOID WINAPI ImageDirectoryEntryToData(
* __in PVOID Base,
* __in BOOLEAN MappedAsImage,
* __in USHORT DirectoryEntry,
* __out PULONG Size) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr ImageDirectoryEntryToData(
IntPtr Base,
bool MappedAsImage,
UInt16 DirectoryEntry,
ref UInt32 Size);
/* HMODULE WINAPI LoadLibrary(
* __in LPCTSTR lpFileName) */
[DllImport("KERNEL32.DLL")]
public extern static IntPtr LoadLibrary(string lpLibFileName);
/* BOOL WINAPI Module32First(
* __in HANDLE hSnapshot,
* __inout LPMODULEENTRY32 lpme) */
[DllImport("KERNEL32.DLL")]
public static extern bool Module32First(
IntPtr hSnapshot,
ref SModuleEntry32 lpme);
/* BOOL WINAPI Module32Next(
* __in HANDLE hSnapshot,
* __out LPMODULEENTRY32 lpme) */
[DllImport("KERNEL32.DLL")]
public static extern bool Module32Next(
IntPtr hSnapshot,
ref SModuleEntry32 lpme);
/* HANDLE WINAPI OpenProcess(
* __in DWORD dwDesiredAccess,
* __in BOOL bInheritHandle,
* __in DWORD dwProcessId) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr OpenProcess(
EProcessAccess dwDesiredAccess,
bool bInheritHandle,
int dwProcessId);
/* void WINAPI OutputDebugString(
* __in_opt LPCTSTR lpOutputString) */
[DllImport("KERNEL32.DLL", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void OutputDebugString(char[] message);
/* BOOL WINAPI Process32First(
* __in HANDLE hSnapshot,
* __inout LPPROCESSENTRY32 lppe) */
[DllImport("KERNEL32.DLL ")]
public static extern bool Process32First(
IntPtr handle,
ref SProcessEntry32 pe);
/* BOOL WINAPI Process32Next(
* __in HANDLE hSnapshot,
* __out LPPROCESSENTRY32 lppe) */
[DllImport("KERNEL32.DLL ")]
public static extern bool Process32Next(
IntPtr handle,
ref SProcessEntry32 pe);
/* BOOL WINAPI ReadProcessMemory(
* __in HANDLE hProcess,
* __in LPCVOID lpBaseAddress,
* __out LPVOID lpBuffer,
* __in SIZE_T nSize,
* __out SIZE_T* lpNumberOfBytesRead) */
[DllImport("KERNEL32.DLL", SetLastError = true)]
public static extern Int32 ReadProcessMemory(
IntPtr hProcess,
uint lpBaseAddress,
byte[] buffer,
int size,
out int lpNumberOfBytesRead);
/* BOOL WINAPI Thread32First(
* __in HANDLE hSnapshot,
* __in_out LPTHREADENTRY32 lpte) */
[DllImport("KERNEL32.DLL")]
public static extern bool Thread32First(
IntPtr hSnapshot,
ref SThreadEntry32 lpte);
/* BOOL WINAPI Thread32Next(
* __in HANDLE hSnapshot,
* __out LPTHREADENTRY32 lpte) */
[DllImport("KERNEL32.DLL")]
public static extern bool Thread32Next(
IntPtr hSnapshot,
ref SThreadEntry32 lpte);
/* LPVOID WINAPI VirtualAllocEx(
* __in HANDLE hProcess,
* __in_opt LPVOID lpAddress,
* __in SIZE_T dwSize,
* __in DWORD flAllocationType,
* __in DWORD flProtect) */
[DllImport("KERNEL32.DLL")]
public static extern IntPtr VirtualAllocEx(
IntPtr hProcess,
int lpAddress,
uint dwSize,
int flAllocationType,
int flProtect);
/* BOOL WINAPI VirtualFreeEx(
* __in HANDLE hProcess,
* __in LPVOID lpAddress,
* __in SIZE_T dwSize,
* __in DWORD dwFreeType) */
[DllImport("KERNEL32.DLL")]
public static extern bool VirtualFreeEx(
IntPtr hProcess,
IntPtr lpAddress,
uint dwSize,
uint dwFreeType);
/* BOOL VirtualProtect(
* LPVOID lpAddress,
* DWORD dwSize,
* DWORD flNewProtect,
* PDWORD lpflOldProtect) */
[DllImport("KERNEL32.DLL ")]
public static extern bool VirtualProtect(
uint lpAddress,
uint dwSize,
uint flNewProtect,
ref uint lpflOldProtect);
/* BOOL WINAPI VirtualProtectEx(
* __in HANDLE hProcess,
* __in LPVOID lpAddress,
* __in SIZE_T dwSize,
* __in DWORD flNewProtect,
* __out PDWORD lpflOldProtect) */
[DllImport("KERNEL32.DLL ")]
public static extern bool VirtualProtectEx(
IntPtr hProcess,
uint lpAddress,
uint dwSize,
uint flNewProtect,
ref uint lpflOldProtect);
/* SIZE_T WINAPI VirtualQuery(
* __in_opt LPCVOID lpAddress,
* __out PMEMORY_BASIC_INFORMATION lpBuffer,
* __in SIZE_T dwLength) */
[DllImport("KERNEL32.DLL", SetLastError = true)]
public static extern int VirtualQuery(
uint lpAddress,
ref SMemoryBasicInformation lpBuffer,
int dwLength);
/* SIZE_T WINAPI VirtualQueryEx(
* __in HANDLE hProcess,
* __in_opt LPCVOID lpAddress,
* __out PMEMORY_BASIC_INFORMATION lpBuffer,
* __in SIZE_T dwLength) */
[DllImport("KERNEL32.DLL", SetLastError = true)]
public static extern int VirtualQueryEx(
IntPtr hProcess,
uint lpAddress,
ref SMemoryBasicInformation lpBuffer,
int dwLength
);
/* DWORD WINAPI WaitForSingleObject(
* __in HANDLE hHandle,
* __in DWORD dwMilliseconds) */
[DllImport("KERNEL32.DLL")]
public static extern uint WaitForSingleObject(
IntPtr hHandle,
uint dwMilliseconds);
/* BOOL WINAPI WriteProcessMemory(
* __in HANDLE hProcess,
* __in LPVOID lpBaseAddress,
* __in LPCVOID lpBuffer,
* __in SIZE_T nSize,
* __out SIZE_T* lpNumberOfBytesWritten) */
[DllImport("KERNEL32.DLL")]
public static extern Int32 WriteProcessMemory(
IntPtr hProcess,
uint lpBaseAddress,
byte[] lpBuffer,
int nSize,
out int lpNumberOfBytesWritten);
}
}
| |
using Microsoft.AspNet.Identity;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Security.Claims;
namespace DocumentDB.AspNet.Identity
{
public class UserStore<TUser> : IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>, IUserStore<TUser>, IUserEmailStore<TUser>, IUserLockoutStore<TUser, string>,
IUserTwoFactorStore<TUser, string>, IUserPhoneNumberStore<TUser>, IQueryableUserStore<TUser, String>
where TUser : IdentityUser
{
private bool _disposed;
private readonly string _database;
private readonly string _collection;
private readonly Uri _documentCollection;
private readonly DocumentClient _client;
public UserStore(Uri endPoint, string authKey, string database, string collection, bool ensureDatabaseAndCollection = false) : this(new DocumentClient(endPoint, authKey), database, collection, ensureDatabaseAndCollection)
{
}
public UserStore(DocumentClient client, string database, string collection, bool ensureDatabaseAndCollection = false)
{
if (client == null)
{
throw new ArgumentException("client");
}
_client = client;
if (string.IsNullOrEmpty(database))
{
throw new ArgumentException("database");
}
_database = database;
if (string.IsNullOrEmpty(collection))
{
throw new ArgumentException("collection");
}
_collection = collection;
if (ensureDatabaseAndCollection)
{
Task.Run(async () =>
{
await CreateDatabaseIfNotExistsAsync();
await CreateCollectionIfNotExistsAsync();
}).Wait();
}
_documentCollection = UriFactory.CreateDocumentCollectionUri(_database, _collection);
}
private async Task CreateDatabaseIfNotExistsAsync()
{
bool databaseEnsured;
try
{
await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_database));
databaseEnsured = true;
}
catch (DocumentClientException exception)
{
if (exception.StatusCode == System.Net.HttpStatusCode.NotFound)
{
databaseEnsured = false;
}
else
{
throw;
}
}
if (!databaseEnsured)
{
await _client.CreateDatabaseAsync(new Database {Id = _database});
}
}
private async Task CreateCollectionIfNotExistsAsync()
{
bool collectionEnsured;
try
{
await _client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(_database, _collection));
collectionEnsured = true;
}
catch (DocumentClientException exception)
{
if (exception.StatusCode == System.Net.HttpStatusCode.NotFound)
{
collectionEnsured = false;
}
else
{
throw;
}
}
if (!collectionEnsured)
{
await _client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(_database),
new DocumentCollection { Id = _collection },
new RequestOptions { OfferThroughput = 400 });
}
}
public async Task<IEnumerable<TUser>> GetUsers(Expression<Func<TUser, bool>> predicate)
{
var query = _client.CreateDocumentQuery<TUser>(_documentCollection)
.Where(predicate)
.AsDocumentQuery();
var results = new List<TUser>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<TUser>());
}
return results;
}
public async Task AddLoginAsync(TUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
if (!user.Logins.Any(x => x.LoginProvider == login.LoginProvider && x.ProviderKey == login.ProviderKey))
{
user.Logins.Add(login);
}
await UpdateUserAsync(user);
}
public async Task<TUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null)
{
throw new ArgumentNullException("login");
}
return (from user in await GetUsers(user => user.Logins != null)
from userLogin in user.Logins
where userLogin.LoginProvider == login.LoginProvider && userLogin.ProviderKey == userLogin.ProviderKey
select user).FirstOrDefault();
}
public Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.Logins.ToIList());
}
public Task RemoveLoginAsync(TUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
user.Logins.Remove(u => u.LoginProvider == login.LoginProvider && u.ProviderKey == login.ProviderKey);
return Task.FromResult(0);
}
public async Task CreateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrEmpty(user.Id))
{
user.Id = Guid.NewGuid().ToString();
}
await _client.CreateDocumentAsync(_documentCollection, user);
}
public async Task DeleteAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var doc = _client.CreateDocumentQuery(_documentCollection).FirstOrDefault(u => u.Id == user.Id);
if (doc != null)
{
await _client.DeleteDocumentAsync(doc.SelfLink);
}
}
public async Task<TUser> FindByIdAsync(string userId)
{
ThrowIfDisposed();
if (userId == null)
{
throw new ArgumentNullException("userId");
}
return (await GetUsers(user => user.Id == userId)).FirstOrDefault();
}
public async Task<TUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
if (userName == null)
{
throw new ArgumentNullException("userName");
}
return (await GetUsers(user => user.UserName == userName)).FirstOrDefault();
}
public async Task UpdateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await UpdateUserAsync(user);
}
public Task AddClaimAsync(TUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (!user.Claims.Any(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value))
{
user.Claims.Add(new IdentityUserClaim
{
ClaimType = claim.Type,
ClaimValue = claim.Value
});
}
return Task.FromResult(0);
}
public Task<IList<Claim>> GetClaimsAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IList<Claim> result = user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult(result);
}
public Task RemoveClaimAsync(TUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.Claims.RemoveAll(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value);
return Task.FromResult(0);
}
public Task AddToRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
if (!user.Roles.Any(x => x.Equals(roleName)))
{
user.Roles.Add(roleName);
}
return Task.FromResult(0);
}
public Task<IList<string>> GetRolesAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var result = user.Roles.ToIList();
return Task.FromResult(result);
}
public Task<bool> IsInRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
var isInRole = user.Roles.Any(x => x.Equals(roleName));
return Task.FromResult(isInRole);
}
public Task RemoveFromRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
user.Roles.Remove(x => x.Equals(roleName));
return Task.FromResult(0);
}
public Task<string> GetPasswordHashAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PasswordHash != null);
}
public Task SetPasswordHashAsync(TUser user, string passwordHash)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
public Task<string> GetSecurityStampAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.SecurityStamp);
}
public Task SetSecurityStampAsync(TUser user, string stamp)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
public async Task<TUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
if (email == null)
{
throw new ArgumentNullException("email");
}
return (await GetUsers(user => user.Email == email)).FirstOrDefault();
}
public Task<string> GetEmailAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.Email);
}
public Task<bool> GetEmailConfirmedAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.EmailConfirmed);
}
public Task SetEmailAsync(TUser user, string email)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (email == null)
{
throw new ArgumentNullException("email");
}
user.Email = email;
return Task.FromResult(0);
}
public Task SetEmailConfirmedAsync(TUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
public Task<int> GetAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.AccessFailedCount);
}
public Task<bool> GetLockoutEnabledAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.LockoutEnabled);
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.LockoutEnd);
}
public Task<int> IncrementAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
public Task ResetAccessFailedCountAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
public Task SetLockoutEnabledAsync(TUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
public Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnd = lockoutEnd;
return Task.FromResult(0);
}
public Task<bool> GetTwoFactorEnabledAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.TwoFactorEnabled);
}
public Task SetTwoFactorEnabledAsync(TUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.TwoFactorEnabled = enabled;
return Task.FromResult(0);
}
public Task<string> GetPhoneNumberAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumber);
}
public Task<bool> GetPhoneNumberConfirmedAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumberConfirmed);
}
public Task SetPhoneNumberAsync(TUser user, string phoneNumber)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (phoneNumber == null)
{
throw new ArgumentNullException("phoneNumber");
}
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
public Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
private async Task UpdateUserAsync(TUser user)
{
var existingUser = (await GetUsers(u => u.Id == user.Id)).FirstOrDefault();
if (existingUser == null)
{
throw new InvalidOperationException("You can't call Update on a User you haven't created yet.");
}
await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_database, _collection, user.Id), user);
}
public void Dispose()
{
_disposed = true;
}
public IQueryable<TUser> Users => _client.CreateDocumentQuery<TUser>(_documentCollection);
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using Microsoft.Xrm.Sdk;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Adxstudio.Xrm.Resources;
namespace Adxstudio.Xrm.Web.Mvc.Html
{
/// <summary>
/// View helpers for rendering an grid of SharePoint folders and files within Adxstudio Portals applications.
/// </summary>
/// <remarks>Requires Bootstrap 3, jQuery and the following files: ~/js/jquery.bootstrap-pagination.js, ~/js/sharepoint-grid.js</remarks>
public static class SharePointGridExtensions
{
private static readonly string DefaultAddFilesModalTitle = ResourceManager.GetString("Add_Files");
private static readonly string DefaultAddFilesModalPrimaryButtonText = ResourceManager.GetString("Add_Files");
private static readonly string DefaultAddFilesModalAttachFileLabel = ResourceManager.GetString("Default_AddFiles_ModalAttachFileLabel");
private static readonly string DefaultAddFilesModalOverwriteFieldLabel = ResourceManager.GetString("Overwrite_Existing_Files_Label_Text");
private static readonly string DefaultAddFolderModalTitle = ResourceManager.GetString("New_Folder_Button_Text");
private static readonly string DefaultAddFolderModalPrimaryButtonText = ResourceManager.GetString("Default_AddFolder_Button_Text");
private static readonly string DefaultAddFolderModalNameLabel = ResourceManager.GetString("Name_DefaultText");
private static readonly string DefaultAddModalCancelButtonText = ResourceManager.GetString("Cancel_DefaultText");
private static readonly string DefaultAddModalDestinationLabel = ResourceManager.GetString("Destination_Label_Text");
private const string DefaultAddModalFormLeftColumnCssClass = "col-sm-3";
private const string DefaultAddModalFormRightColumnCssClass = "col-sm-9";
private static readonly string DefaultDeleteFileModalTitle = "<span class='fa fa-trash-o' aria-hidden='true'></span> " + ResourceManager.GetString("Default_Delete_File_ModalTitle");
private static readonly string DefaultDeleteFileModalConfirmation = ResourceManager.GetString("File_Deletion_Confirmation_Message");
private static readonly string DefaultDeleteFolderModalTitle = "<span class='fa fa-trash-o' aria-hidden='true'></span> " + ResourceManager.GetString("Default_Delete_Folder_ModalTitle");
private static readonly string DefaultDeleteFolderModalConfirmation = ResourceManager.GetString("Folder_Deletion_Confirmation_Message");
private static readonly string DefaultDeleteModalPrimaryButtonText = ResourceManager.GetString("Delete_Button_Text");
private static readonly string DefaultDeleteModalCancelButtonText = ResourceManager.GetString("Cancel_DefaultText");
private static readonly string DefaultFileNameColumnTitle = ResourceManager.GetString("Name_DefaultText");
private static readonly string DefaultModalDismissButtonSrText = ResourceManager.GetString("Close_DefaultText");
private static readonly string DefaultModifiedColumnTitle = ResourceManager.GetString("Default_Modified_Column_Title");
private static readonly string DefaultParentFolderPrefix = ResourceManager.GetString("Upto_Text");
private static readonly string DefaultSharePointGridTitle = ResourceManager.GetString("Document_Library_Title_Text");
private static readonly string DefaultSharePointGridLoadingMessage = "<span class='fa fa-spinner fa-pulse' aria-hidden='true'></span> " + ResourceManager.GetString("Default_Grid_Loading_Message");
private static readonly string DefaultSharePointGridErrorMessage = ResourceManager.GetString("Error_Completing_Request_Error_Message");
private static readonly string DefaultSharePointGridAccessDeniedMessage = ResourceManager.GetString("Access_Denied_No_Permissions_To_View_These_Folders_Message");
private static readonly string DefaultSharePointGridEmptyMessage = ResourceManager.GetString("Default_SharePoint_Grid_Empty_Message");
private static readonly string DefaultAddFilesButtonLabel = "<span class='fa fa-plus-circle' aria-hidden='true'></span> " + ResourceManager.GetString("Add_Files");
private static readonly string DefaultAddFolderButtonLabel = "<span class='fa fa-folder' aria-hidden='true'></span> " + ResourceManager.GetString("New_Folder_Button_Text");
private const string DefaultToolbarButtonLabel = "<span class='fa fa-chevron-circle-down fa-fw' aria-hidden='true'></span>";
private static readonly string DefaultDeleteButtonLabel = "<span class='fa fa-trash-o fa-fw' aria-hidden='true'></span> " + ResourceManager.GetString("Delete_Button_Text");
/// <summary>
/// Render a SharePoint grid of files and folders associated with a target entity and provide a modal dialog to add new files.
/// </summary>
/// <param name="html">Extension method target, provides support for HTML rendering and access to view context/data.</param>
/// <param name="target">EntityReference for the target entity record <see cref="EntityReference"/></param>
/// <param name="serviceUrlGet">URL to the service that handles the get data request.</param>
/// <param name="createEnabled">Boolean indicating whether adding files and folders is enabled or not.</param>
/// <param name="deleteEnabled">Boolean indicating whether deleting files and folders is enabled or not.</param>
/// <param name="serviceUrlAddFiles">URL to the service that handles the add files request.</param>
/// <param name="serviceUrlAddFolder">URL to the service that handles the add folder request.</param>
/// <param name="serviceUrlDelete">URL to the service that handles the delete item request.</param>
/// <param name="pageSize">Number of records to display per page.</param>
/// <param name="title">Title of the SharePoint grid.</param>
/// <param name="fileNameColumnLabel">Text displayed for the file name column header.</param>
/// <param name="modifiedColumnLabel">Text displayed for the modified on column header.</param>
/// <param name="parentFolderPrefix">Text displayed for the parent folder.</param>
/// <param name="loadingMessage">Message to be displayed during loading of SharePoint grid.</param>
/// <param name="errorMessage">Message to be displayed if an error occurs loading SharePoint grid.</param>
/// <param name="accessDeniedMessage">Message to be displayed if the user does not have the appropriate permissions to view the SharePoint grid.</param>
/// <param name="emptyMessage">Message to be displayed if there are no files or folders found.</param>
/// <param name="addFilesButtonLabel">Text displayed for the button that launches the add files modal.</param>
/// <param name="addFolderButtonLabel">Text displayed for the button that launches the add folder modal.</param>
/// <param name="toolbarButtonLabel">Text displayed for the toolbar button dropdown.</param>
/// <param name="deleteButtonLabel">Text displayed for the delete button.</param>
/// <param name="modalAddFilesSize">Size of the add files modal <see cref="BootstrapExtensions.BootstrapModalSize"/>.</param>
/// <param name="modalAddFilesCssClass">CSS class assigned to the add files modal element.</param>
/// <param name="modalAddFilesTitle">Text assigned to the add files modal title.</param>
/// <param name="modalAddFilesDismissButtonSrText">Text assigned to the add files modal dismiss button for screen readers only.</param>
/// <param name="modalAddFilesPrimaryButtonText">Text assigned to the add files modal primary button.</param>
/// <param name="modalAddFilesCancelButtonText">Text assigned to the add files modal cancel button.</param>
/// <param name="modalAddFilesTitleCssClass">CSS class assigned to the add files title.</param>
/// <param name="modalAddFilesPrimaryButtonCssClass">CSS class assigned to the add files modal primary button.</param>
/// <param name="modalAddFilesCancelButtonCssClass">CSS class assigned to the add files modal cancel button.</param>
/// <param name="modalAddFilesAttachFileLabel">Text displayed for the label of the add files modal file input.</param>
/// <param name="modalAddFilesAttachFileAccept">The accept attribute specifies the MIME types of files that the server accepts through file upload.
/// To specify more than one value, separate the values with a comma (e.g. audio/*,video/*,image/*).</param>
/// <param name="modalAddFilesDisplayOverwriteField">Boolean value that indicates if the add files modal should display an overwrite checkbox.</param>
/// <param name="modalAddFilesOverwriteFieldLabel">Text displayed for the label of the add files modal overwrite existing file checkbox.</param>
/// <param name="modalAddFilesOverwriteFieldDefaultValue">Default value assigned to the add files modal overwrite checkbox.</param>
/// <param name="modalAddFilesDestinationFolderLabel">Text displayed for the destination folder label.</param>
/// <param name="modalAddFilesFormRightColumnCssClass">CSS class assigned to the add files modal form's left column.</param>
/// <param name="modalAddFilesFormLeftColumnCssClass">CSS class assigned to the add files modal form's right column.</param>
/// <param name="modalAddFilesHtmlAttributes">Collection of HTML attributes to be assigned to the add files modal element.</param>
/// <param name="modalAddFolderSize">Size of the add folder modal <see cref="BootstrapExtensions.BootstrapModalSize"/>.</param>
/// <param name="modalAddFolderCssClass">CSS class assigned to the add folder modal element.</param>
/// <param name="modalAddFolderTitle">Text assigned to the add folder modal title.</param>
/// <param name="modalAddFolderDismissButtonSrText">Text assigned to the add folder modal dismiss button for screen readers only.</param>
/// <param name="modalAddFolderPrimaryButtonText">Text assigned to the add folder modal primary button.</param>
/// <param name="modalAddFolderCancelButtonText">Text assigned to the add folder modal cancel button.</param>
/// <param name="modalAddFolderTitleCssClass">CSS class assigned to the add folder title.</param>
/// <param name="modalAddFolderPrimaryButtonCssClass">CSS class assigned to the add folder modal primary button.</param>
/// <param name="modalAddFolderCancelButtonCssClass">CSS class assigned to the add folder modal cancel button.</param>
/// <param name="modalAddFolderNameLabel">Text displayed for the label of the add folder modal file input.</param>
/// <param name="modalAddFolderDestinationFolderLabel">Text displayed for the destination folder label.</param>
/// <param name="modalAddFolderFormRightColumnCssClass">CSS class assigned to the add folder modal form's left column.</param>
/// <param name="modalAddFolderFormLeftColumnCssClass">CSS class assigned to the add folder modal form's right column.</param>
/// <param name="modalAddFolderHtmlAttributes">Collection of HTML attributes to be assigned to the add folder modal element.</param>
/// <param name="modalDeleteFileSize">Size of the delete file modal <see cref="BootstrapExtensions.BootstrapModalSize"/>.</param>
/// <param name="modalDeleteFileCssClass">CSS class assigned to the delete file modal element.</param>
/// <param name="modalDeleteFileTitle">Text assigned to the delete file modal title.</param>
/// <param name="modalDeleteFileConfirmation">Text displayed for the confirmation message of the delete file modal.</param>
/// <param name="modalDeleteFileDismissButtonSrText">Text assigned to the delete file modal dismiss button for screen readers only.</param>
/// <param name="modalDeleteFilePrimaryButtonText">Text assigned to the delete file modal primary button.</param>
/// <param name="modalDeleteFileCancelButtonText">Text assigned to the delete file modal cancel button.</param>
/// <param name="modalDeleteFileTitleCssClass">CSS class assigned to the delete file title.</param>
/// <param name="modalDeleteFilePrimaryButtonCssClass">CSS class assigned to the delete file modal primary button.</param>
/// <param name="modalDeleteFileCancelButtonCssClass">CSS class assigned to the delete file modal cancel button.</param>
/// <param name="modalDeleteFileHtmlAttributes">Collection of HTML attributes to be assigned to the delete file modal element.</param>
/// <param name="modalDeleteFolderSize">Size of the delete folder modal <see cref="BootstrapExtensions.BootstrapModalSize"/>.</param>
/// <param name="modalDeleteFolderCssClass">CSS class assigned to the delete folder modal element.</param>
/// <param name="modalDeleteFolderTitle">Text assigned to the delete folder modal title.</param>
/// <param name="modalDeleteFolderConfirmation">Text displayed for the confirmation message of the delete folder modal.</param>
/// <param name="modalDeleteFolderDismissButtonSrText">Text assigned to the delete folder modal dismiss button for screen readers only.</param>
/// <param name="modalDeleteFolderPrimaryButtonText">Text assigned to the delete folder modal primary button.</param>
/// <param name="modalDeleteFolderCancelButtonText">Text assigned to the delete folder modal cancel button.</param>
/// <param name="modalDeleteFolderTitleCssClass">CSS class assigned to the delete folder title.</param>
/// <param name="modalDeleteFolderPrimaryButtonCssClass">CSS class assigned to the delete folder modal primary button.</param>
/// <param name="modalDeleteFolderCancelButtonCssClass">CSS class assigned to the delete folder modal cancel button.</param>
/// <param name="modalDeleteFolderHtmlAttributes">Collection of HTML attributes to be assigned to the delete folder modal element.</param>
public static IHtmlString SharePointGrid(this HtmlHelper html, EntityReference target, string serviceUrlGet, bool createEnabled = false, bool deleteEnabled = false,
string serviceUrlAddFiles = null, string serviceUrlAddFolder = null, string serviceUrlDelete = null, int pageSize = 0,
string title = null, string fileNameColumnLabel = null, string modifiedColumnLabel = null, string parentFolderPrefix = null,
string loadingMessage = null, string errorMessage = null, string accessDeniedMessage = null, string emptyMessage = null,
string addFilesButtonLabel = null, string addFolderButtonLabel = null, string toolbarButtonLabel = null, string deleteButtonLabel = null,
BootstrapExtensions.BootstrapModalSize modalAddFilesSize = BootstrapExtensions.BootstrapModalSize.Default,
string modalAddFilesCssClass = null, string modalAddFilesTitle = null, string modalAddFilesDismissButtonSrText = null,
string modalAddFilesPrimaryButtonText = null, string modalAddFilesCancelButtonText = null, string modalAddFilesTitleCssClass = null,
string modalAddFilesPrimaryButtonCssClass = null, string modalAddFilesCancelButtonCssClass = null,
string modalAddFilesAttachFileLabel = null, string modalAddFilesAttachFileAccept = null,
bool modalAddFilesDisplayOverwriteField = true, string modalAddFilesOverwriteFieldLabel = null,
bool modalAddFilesOverwriteFieldDefaultValue = true, string modalAddFilesDestinationFolderLabel = null,
string modalAddFilesFormLeftColumnCssClass = null, string modalAddFilesFormRightColumnCssClass = null,
IDictionary<string, string> modalAddFilesHtmlAttributes = null,
BootstrapExtensions.BootstrapModalSize modalAddFolderSize = BootstrapExtensions.BootstrapModalSize.Default,
string modalAddFolderCssClass = null, string modalAddFolderTitle = null, string modalAddFolderDismissButtonSrText = null,
string modalAddFolderPrimaryButtonText = null, string modalAddFolderCancelButtonText = null, string modalAddFolderTitleCssClass = null,
string modalAddFolderPrimaryButtonCssClass = null, string modalAddFolderCancelButtonCssClass = null,
string modalAddFolderNameLabel = null, string modalAddFolderDestinationFolderLabel = null,
string modalAddFolderFormLeftColumnCssClass = null, string modalAddFolderFormRightColumnCssClass = null,
IDictionary<string, string> modalAddFolderHtmlAttributes = null,
BootstrapExtensions.BootstrapModalSize modalDeleteFileSize = BootstrapExtensions.BootstrapModalSize.Default,
string modalDeleteFileCssClass = null, string modalDeleteFileTitle = null, string modalDeleteFileConfirmation = null, string modalDeleteFileDismissButtonSrText = null,
string modalDeleteFilePrimaryButtonText = null, string modalDeleteFileCancelButtonText = null, string modalDeleteFileTitleCssClass = null,
string modalDeleteFilePrimaryButtonCssClass = null, string modalDeleteFileCancelButtonCssClass = null, IDictionary<string, string> modalDeleteFileHtmlAttributes = null,
BootstrapExtensions.BootstrapModalSize modalDeleteFolderSize = BootstrapExtensions.BootstrapModalSize.Default,
string modalDeleteFolderCssClass = null, string modalDeleteFolderTitle = null, string modalDeleteFolderConfirmation = null, string modalDeleteFolderDismissButtonSrText = null,
string modalDeleteFolderPrimaryButtonText = null, string modalDeleteFolderCancelButtonText = null, string modalDeleteFolderTitleCssClass = null,
string modalDeleteFolderPrimaryButtonCssClass = null, string modalDeleteFolderCancelButtonCssClass = null, IDictionary<string, string> modalDeleteFolderHtmlAttributes = null)
{
var container = new TagBuilder("div");
container.AddCssClass("sharepoint-grid");
container.AddCssClass("subgrid");
container.MergeAttribute("data-url-get", serviceUrlGet);
container.MergeAttribute("data-url-add-files", serviceUrlAddFiles);
container.MergeAttribute("data-url-add-folder", serviceUrlAddFolder);
container.MergeAttribute("data-url-delete", serviceUrlDelete);
container.MergeAttribute("data-add-enabled", createEnabled.ToString());
container.MergeAttribute("data-delete-enabled", deleteEnabled.ToString());
container.MergeAttribute("data-target", JsonConvert.SerializeObject(target));
container.MergeAttribute("data-pagesize", pageSize.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrWhiteSpace(title))
{
var header = new TagBuilder("div");
header.AddCssClass("page-header");
header.InnerHtml = (new TagBuilder("h3") { InnerHtml = title.GetValueOrDefault(DefaultSharePointGridTitle) }).ToString();
container.InnerHtml += header.ToString();
}
var template = new TagBuilder("script");
template.MergeAttribute("id", "sharepoint-template");
template.MergeAttribute("type", "text/x-handlebars-template");
var grid = new TagBuilder("div");
grid.AddCssClass("view-grid");
var table = new TagBuilder("table");
table.AddCssClass("table");
table.AddCssClass("table-striped");
table.MergeAttribute("aria-live", "polite");
table.MergeAttribute("aria-relevant", "additions");
var thead = new TagBuilder("thead");
var theadRow = new TagBuilder("tr");
var fileNameColumnHeader = new TagBuilder("th");
fileNameColumnHeader.MergeAttribute("data-sort-name", "FileLeafRef");
fileNameColumnHeader.AddCssClass("sort-enabled");
var fileNameColumnLink = new TagBuilder("a");
fileNameColumnLink.MergeAttribute("href", "#");
fileNameColumnLink.InnerHtml = fileNameColumnLabel.GetValueOrDefault(DefaultFileNameColumnTitle);
fileNameColumnHeader.InnerHtml = fileNameColumnLink.ToString();
theadRow.InnerHtml += fileNameColumnHeader.ToString();
var modifiedColumnHeader = new TagBuilder("th");
modifiedColumnHeader.MergeAttribute("data-sort-name", "Modified");
modifiedColumnHeader.AddCssClass("sort-enabled");
var modifiedColumnLink = new TagBuilder("a");
modifiedColumnLink.MergeAttribute("href", "#");
modifiedColumnLink.InnerHtml = modifiedColumnLabel.GetValueOrDefault(DefaultModifiedColumnTitle);
modifiedColumnHeader.InnerHtml = modifiedColumnLink.ToString();
theadRow.InnerHtml += modifiedColumnHeader.ToString();
if (deleteEnabled)
{
var actionsHeader = new TagBuilder("th");
actionsHeader.AddCssClass("sort-disabled");
actionsHeader.InnerHtml = "<span class='sr-only'>Actions</span>";
theadRow.InnerHtml += actionsHeader.ToString();
}
thead.InnerHtml = theadRow.ToString();
table.InnerHtml += thead.ToString();
table.InnerHtml += "{{#each SharePointItems}}";
table.InnerHtml += "{{#if IsFolder}}";
var folderRow = new TagBuilder("tr");
folderRow.AddCssClass("sp-item");
folderRow.MergeAttribute("data-id", "{{Id}}");
folderRow.MergeAttribute("data-foldername", "{{Name}}");
folderRow.MergeAttribute("data-folderpath", "{{FolderPath}}");
var folderNameCell = new TagBuilder("td");
folderNameCell.MergeAttribute("data-type", "System.String");
folderNameCell.MergeAttribute("data-value", "{{Name}}");
var folderLink = new TagBuilder("a");
folderLink.AddCssClass("folder-link");
folderLink.MergeAttribute("data-folderpath", "{{FolderPath}}");
folderLink.MergeAttribute("href", "#");
folderLink.InnerHtml += "{{#if IsParent}}";
folderLink.InnerHtml += "<span class='fa fa-level-up text-primary' aria-hidden='true'></span> ";
folderLink.InnerHtml += parentFolderPrefix.GetValueOrDefault(DefaultParentFolderPrefix);
folderLink.InnerHtml += "{{Name}}";
folderLink.InnerHtml += "{{else}}";
folderLink.InnerHtml += "<span class='fa fa-folder text-primary' aria-hidden='true'></span> {{Name}}";
folderLink.InnerHtml += "{{/if}}";
folderNameCell.InnerHtml += folderLink.ToString();
folderRow.InnerHtml += folderNameCell.ToString();
folderRow.InnerHtml += "{{#if IsParent}}";
folderRow.InnerHtml += new TagBuilder("td").ToString();
folderRow.InnerHtml += "{{else}}";
var folderModifiedCell = new TagBuilder("td");
folderModifiedCell.AddCssClass("postedon");
var folderModifiedAbbr = new TagBuilder("abbr");
folderModifiedAbbr.AddCssClass("timeago");
folderModifiedAbbr.MergeAttribute("title", "{{ModifiedOnDisplay}}");
folderModifiedAbbr.MergeAttribute("data-datetime", "{{ModifiedOnDisplay}}");
folderModifiedAbbr.InnerHtml = "{{ModifiedOnDisplay}}";
folderModifiedCell.InnerHtml = folderModifiedAbbr.ToString();
folderRow.InnerHtml += folderModifiedCell.ToString();
folderRow.InnerHtml += "{{/if}}";
if (deleteEnabled)
{
folderRow.InnerHtml += ActionCell(toolbarButtonLabel, deleteButtonLabel).ToString();
}
table.InnerHtml += folderRow.ToString();
table.InnerHtml += "{{else}}";
var fileRow = new TagBuilder("tr");
fileRow.AddCssClass("sp-item");
fileRow.MergeAttribute("data-id", "{{Id}}");
fileRow.MergeAttribute("data-filename", "{{Name}}");
fileRow.MergeAttribute("data-url", "{{Url}}");
var fileNameCell = new TagBuilder("td");
fileNameCell.MergeAttribute("data-type", "System.String");
fileNameCell.MergeAttribute("data-value", "{{Name}}");
var fileLink = new TagBuilder("a");
fileLink.MergeAttribute("target", "_blank");
fileLink.MergeAttribute("href", "{{Url}}");
fileLink.InnerHtml = "<span class='fa fa-file-o' aria-hidden='true'></span> {{Name}} <small>({{FileSizeDisplay}})</small>";
fileNameCell.InnerHtml += fileLink.ToString();
fileRow.InnerHtml += fileNameCell.ToString();
var fileModifiedCell = new TagBuilder("td");
fileModifiedCell.AddCssClass("postedon");
var fileModifiedAbbr = new TagBuilder("abbr");
fileModifiedAbbr.AddCssClass("timeago");
fileModifiedAbbr.MergeAttribute("title", "{{ModifiedOnDisplay}}");
fileModifiedAbbr.MergeAttribute("data-datetime", "{{ModifiedOnDisplay}}");
fileModifiedAbbr.InnerHtml = "{{ModifiedOnDisplay}}";
fileModifiedCell.InnerHtml = fileModifiedAbbr.ToString();
fileRow.InnerHtml += fileModifiedCell.ToString();
if (deleteEnabled)
{
fileRow.InnerHtml += ActionCell(toolbarButtonLabel, deleteButtonLabel).ToString();
}
table.InnerHtml += fileRow.ToString();
table.InnerHtml += "{{/if}}";
table.InnerHtml += "{{/each}}";
grid.InnerHtml += table.ToString();
template.InnerHtml = grid.GetHTML();
container.InnerHtml += template.ToString();
var actionRow = new TagBuilder("div");
actionRow.AddCssClass("view-toolbar grid-actions clearfix");
if (createEnabled)
{
if (!string.IsNullOrWhiteSpace(serviceUrlAddFolder))
{
var button = new TagBuilder("a");
button.AddCssClass("btn btn-info pull-right action");
button.AddCssClass("add-folder");
button.MergeAttribute("title", addFolderButtonLabel.GetValueOrDefault(DefaultAddFolderButtonLabel));
button.InnerHtml = addFolderButtonLabel.GetValueOrDefault(DefaultAddFolderButtonLabel);
actionRow.InnerHtml += button.ToString();
}
if (!string.IsNullOrWhiteSpace(serviceUrlAddFiles))
{
var button = new TagBuilder("a");
button.AddCssClass("btn btn-primary pull-right action");
button.AddCssClass("add-file");
button.MergeAttribute("title", addFilesButtonLabel.GetValueOrDefault(DefaultAddFilesButtonLabel));
button.InnerHtml = addFilesButtonLabel.GetValueOrDefault(DefaultAddFilesButtonLabel);
actionRow.InnerHtml += button.ToString();
}
}
container.InnerHtml += actionRow.ToString();
var sharePointBreadcrumbs = new TagBuilder("ol");
sharePointBreadcrumbs.AddCssClass("sharepoint-breadcrumbs");
sharePointBreadcrumbs.AddCssClass("breadcrumb");
sharePointBreadcrumbs.MergeAttribute("style", "display: none;");
container.InnerHtml += sharePointBreadcrumbs.ToString();
var sharePointData = new TagBuilder("div");
sharePointData.AddCssClass("sharepoint-data");
container.InnerHtml += sharePointData.ToString();
var messageEmpty = new TagBuilder("div");
messageEmpty.AddCssClass("sharepoint-empty message");
messageEmpty.MergeAttribute("style", "display: none;");
if (!string.IsNullOrWhiteSpace(emptyMessage))
{
messageEmpty.InnerHtml = emptyMessage;
}
else
{
var message = new TagBuilder("div");
message.AddCssClass("alert alert-block alert-warning");
message.InnerHtml = DefaultSharePointGridEmptyMessage;
messageEmpty.InnerHtml = message.ToString();
}
container.InnerHtml += messageEmpty.ToString();
var messageAccessDenied = new TagBuilder("div");
messageAccessDenied.AddCssClass("sharepoint-access-denied message");
messageAccessDenied.MergeAttribute("style", "display: none;");
if (!string.IsNullOrWhiteSpace(accessDeniedMessage))
{
messageAccessDenied.InnerHtml = accessDeniedMessage;
}
else
{
var message = new TagBuilder("div");
message.AddCssClass("alert alert-block alert-danger");
message.InnerHtml = DefaultSharePointGridAccessDeniedMessage;
messageAccessDenied.InnerHtml = message.ToString();
}
container.InnerHtml += messageAccessDenied.ToString();
var messageError = new TagBuilder("div");
messageError.AddCssClass("sharepoint-error message");
messageError.MergeAttribute("style", "display: none;");
if (!string.IsNullOrWhiteSpace(errorMessage))
{
messageError.InnerHtml = errorMessage;
}
else
{
var message = new TagBuilder("div");
message.AddCssClass("alert alert-block alert-danger");
message.InnerHtml = DefaultSharePointGridErrorMessage;
messageError.InnerHtml = message.ToString();
}
container.InnerHtml += messageError.ToString();
var messageLoading = new TagBuilder("div");
messageLoading.AddCssClass("sharepoint-loading message text-center");
messageLoading.InnerHtml = !string.IsNullOrWhiteSpace(loadingMessage)
? loadingMessage
: DefaultSharePointGridLoadingMessage;
container.InnerHtml += messageLoading.ToString();
var pagination = new TagBuilder("div");
pagination.AddCssClass("sharepoint-pagination");
pagination.MergeAttribute("data-pages", "1");
pagination.MergeAttribute("data-pagesize", pageSize.ToString(CultureInfo.InvariantCulture));
pagination.MergeAttribute("data-current-page", "1");
container.InnerHtml += pagination;
if (createEnabled)
{
if (!string.IsNullOrWhiteSpace(serviceUrlAddFiles))
{
var addFileModal = AddFilesModal(html, target, serviceUrlAddFiles, modalAddFilesSize, modalAddFilesCssClass, modalAddFilesTitle,
modalAddFilesDismissButtonSrText, modalAddFilesPrimaryButtonText, modalAddFilesCancelButtonText, modalAddFilesTitleCssClass,
modalAddFilesPrimaryButtonCssClass, modalAddFilesCancelButtonCssClass, modalAddFilesAttachFileLabel, modalAddFilesAttachFileAccept,
modalAddFilesDisplayOverwriteField, modalAddFilesOverwriteFieldLabel, modalAddFilesOverwriteFieldDefaultValue, modalAddFilesDestinationFolderLabel,
modalAddFilesFormLeftColumnCssClass, modalAddFilesFormRightColumnCssClass, modalAddFilesHtmlAttributes);
container.InnerHtml += addFileModal;
}
if (!string.IsNullOrWhiteSpace(serviceUrlAddFolder))
{
var addFolderModal = AddFolderModal(html, target, serviceUrlAddFolder, modalAddFolderSize, modalAddFolderCssClass, modalAddFolderTitle,
modalAddFolderDismissButtonSrText, modalAddFolderPrimaryButtonText, modalAddFolderCancelButtonText, modalAddFolderTitleCssClass,
modalAddFolderPrimaryButtonCssClass, modalAddFolderCancelButtonCssClass, modalAddFolderNameLabel, modalAddFolderDestinationFolderLabel,
modalAddFolderFormLeftColumnCssClass, modalAddFolderFormRightColumnCssClass, modalAddFolderHtmlAttributes);
container.InnerHtml += addFolderModal;
}
}
if (deleteEnabled && !string.IsNullOrWhiteSpace(serviceUrlDelete))
{
var deleteFileModal = html.DeleteModal(modalDeleteFileSize, string.Join(" ", new[] { "modal-delete-file", modalDeleteFileCssClass }).TrimEnd(' '),
modalDeleteFileTitle.GetValueOrDefault(DefaultDeleteFileModalTitle),
modalDeleteFileConfirmation.GetValueOrDefault(DefaultDeleteFileModalConfirmation),
modalDeleteFileDismissButtonSrText.GetValueOrDefault(DefaultModalDismissButtonSrText),
modalDeleteFilePrimaryButtonText.GetValueOrDefault(DefaultDeleteModalPrimaryButtonText),
modalDeleteFileCancelButtonText.GetValueOrDefault(DefaultDeleteModalCancelButtonText),
modalDeleteFileTitleCssClass, modalDeleteFilePrimaryButtonCssClass, modalDeleteFileCancelButtonCssClass,
modalDeleteFileHtmlAttributes);
container.InnerHtml += deleteFileModal;
var deleteFolderModal = html.DeleteModal(modalDeleteFolderSize, string.Join(" ", new[] { "modal-delete-folder", modalDeleteFolderCssClass }).TrimEnd(' '),
modalDeleteFolderTitle.GetValueOrDefault(DefaultDeleteFolderModalTitle),
modalDeleteFolderConfirmation.GetValueOrDefault(DefaultDeleteFolderModalConfirmation),
modalDeleteFolderDismissButtonSrText.GetValueOrDefault(DefaultModalDismissButtonSrText),
modalDeleteFolderPrimaryButtonText.GetValueOrDefault(DefaultDeleteModalPrimaryButtonText),
modalDeleteFolderCancelButtonText.GetValueOrDefault(DefaultDeleteModalCancelButtonText),
modalDeleteFolderTitleCssClass, modalDeleteFolderPrimaryButtonCssClass, modalDeleteFolderCancelButtonCssClass,
modalDeleteFolderHtmlAttributes);
container.InnerHtml += deleteFolderModal;
}
return new HtmlString(container.ToString());
}
/// <summary>
/// Render a bootstrap modal dialog for adding files.
/// </summary>
/// <param name="html">Extension method target, provides support for HTML rendering and access to view context/data.</param>
/// <param name="serviceUrl">URL to the service that handles the add file request.</param>
/// <param name="target">EntityReference of the target entity the file is regarding. <see cref="EntityReference"/></param>
/// <param name="size">Size of the modal. <see cref="BootstrapExtensions.BootstrapModalSize"/></param>
/// <param name="cssClass">CSS class assigned to the modal.</param>
/// <param name="title">Title assigned to the modal.</param>
/// <param name="dismissButtonSrText">The text to display for the dismiss button for screen readers only.</param>
/// <param name="primaryButtonText">Text displayed for the primary button.</param>
/// <param name="cancelButtonText">Text displayed for the cancel button.</param>
/// <param name="titleCssClass">CSS class assigned to the title element in the header.</param>
/// <param name="primaryButtonCssClass">CSS class assigned to the primary button.</param>
/// <param name="closeButtonCssClass">CSS class assigned to the close button.</param>
/// <param name="attachFileLabel">Text displayed for the attach file label.</param>
/// <param name="attachFileAccept">The accept attribute specifies the MIME types of files that the server accepts through file upload.
/// To specify more than one value, separate the values with a comma (e.g. audio/*,video/*,image/*).</param>
/// <param name="displayOverwriteField">Boolean value that indicates if the overwrite checkbox is displayed.</param>
/// <param name="overwriteFieldLabel">Text displayed for the label of the overwrite existing file checkbox.</param>
/// <param name="overwriteFieldDefaultValue">Default value assigned to the overwrite checkbox.</param>
/// <param name="destinationFolderLabel">Text displayed for the destination folder label.</param>
/// <param name="formLeftColumnCssClass">CSS class applied to the form's left column.</param>
/// <param name="formRightColumnCssClass">CSS class applied to the form's right column.</param>
/// <param name="htmlAttributes">HTML Attributes assigned to the modal.</param>
public static IHtmlString AddFilesModal(this HtmlHelper html, EntityReference target, string serviceUrl,
BootstrapExtensions.BootstrapModalSize size = BootstrapExtensions.BootstrapModalSize.Default, string cssClass = null,
string title = null, string dismissButtonSrText = null, string primaryButtonText = null,
string cancelButtonText = null, string titleCssClass = null, string primaryButtonCssClass = null,
string closeButtonCssClass = null, string attachFileLabel = null, string attachFileAccept = null,
bool displayOverwriteField = true, string overwriteFieldLabel = null, bool overwriteFieldDefaultValue = true, string destinationFolderLabel = null,
string formLeftColumnCssClass = null, string formRightColumnCssClass = null, IDictionary<string, string> htmlAttributes = null)
{
var body = new TagBuilder("div");
body.AddCssClass("add-file");
body.AddCssClass("form-horizontal");
body.MergeAttribute("data-url", serviceUrl);
var entityReference = new JObject(new JProperty("LogicalName", target.LogicalName),
new JProperty("Id", target.Id.ToString()));
body.MergeAttribute("data-target", entityReference.ToString());
var row1 = new TagBuilder("div");
row1.AddCssClass("form-group");
var fileInputLabel = new TagBuilder("label");
fileInputLabel.AddCssClass(formLeftColumnCssClass.GetValueOrDefault(DefaultAddModalFormLeftColumnCssClass));
fileInputLabel.AddCssClass("control-label");
fileInputLabel.InnerHtml = attachFileLabel.GetValueOrDefault(DefaultAddFilesModalAttachFileLabel);
var fileInputContainer = new TagBuilder("div");
fileInputContainer.AddCssClass(formRightColumnCssClass.GetValueOrDefault(DefaultAddModalFormRightColumnCssClass));
var fileInput = new TagBuilder("input");
fileInput.MergeAttribute("name", "file");
fileInput.MergeAttribute("type", "file");
fileInput.MergeAttribute("multiple", "multiple");
if (!string.IsNullOrWhiteSpace(attachFileAccept))
{
fileInput.MergeAttribute("accept", attachFileAccept);
}
fileInputContainer.InnerHtml = fileInput.ToString();
row1.InnerHtml = fileInputLabel.ToString();
row1.InnerHtml += fileInputContainer.ToString();
body.InnerHtml += row1.ToString();
if (displayOverwriteField)
{
var row2 = new TagBuilder("div");
row2.AddCssClass("form-group");
var emptyLeft = new TagBuilder("div");
emptyLeft.AddCssClass(formLeftColumnCssClass.GetValueOrDefault(DefaultAddModalFormLeftColumnCssClass));
row2.InnerHtml = emptyLeft.ToString();
var overwriteContainer = new TagBuilder("div");
overwriteContainer.AddCssClass("checkbox");
overwriteContainer.AddCssClass(formRightColumnCssClass.GetValueOrDefault(DefaultAddModalFormRightColumnCssClass));
var overwriteLabel = new TagBuilder("label");
var overwrite = new TagBuilder("input");
overwrite.MergeAttribute("name", "overwrite");
overwrite.MergeAttribute("type", "checkbox");
if (overwriteFieldDefaultValue)
{
overwrite.MergeAttribute("checked", "checked");
}
overwriteLabel.InnerHtml = overwrite.ToString();
overwriteLabel.InnerHtml += overwriteFieldLabel.GetValueOrDefault(DefaultAddFilesModalOverwriteFieldLabel);
overwriteContainer.InnerHtml = overwriteLabel.ToString();
row2.InnerHtml += overwriteContainer.ToString();
body.InnerHtml += row2.ToString();
}
var row3 = new TagBuilder("div");
row3.AddCssClass("form-group");
row3.AddCssClass("destination-group");
var destinationLabel = new TagBuilder("label");
destinationLabel.AddCssClass(formLeftColumnCssClass.GetValueOrDefault(DefaultAddModalFormLeftColumnCssClass));
destinationLabel.AddCssClass("control-label");
destinationLabel.InnerHtml = destinationFolderLabel.GetValueOrDefault(DefaultAddModalDestinationLabel);
var destinationContainer = new TagBuilder("div");
destinationContainer.AddCssClass(formRightColumnCssClass.GetValueOrDefault(DefaultAddModalFormRightColumnCssClass));
var destination = new TagBuilder("p");
destination.AddCssClass("destination-folder");
destination.AddCssClass("form-control-static");
destinationContainer.InnerHtml = destination.ToString();
row3.InnerHtml = destinationLabel.ToString();
row3.InnerHtml += destinationContainer.ToString();
body.InnerHtml += row3.ToString();
return html.BoostrapModal(BootstrapExtensions.BootstrapModalSize.Default,
title.GetValueOrDefault(DefaultAddFilesModalTitle), body.ToString(),
string.Join(" ", new[] { "modal-add-file", cssClass }).TrimEnd(' '), null, false,
dismissButtonSrText.GetValueOrDefault(DefaultModalDismissButtonSrText), false, false, false,
primaryButtonText.GetValueOrDefault(DefaultAddFilesModalPrimaryButtonText),
cancelButtonText.GetValueOrDefault(DefaultAddModalCancelButtonText), titleCssClass, primaryButtonCssClass,
closeButtonCssClass, htmlAttributes);
}
/// <summary>
/// Render a bootstrap modal dialog for adding a folder.
/// </summary>
/// <param name="html">Extension method target, provides support for HTML rendering and access to view context/data.</param>
/// <param name="serviceUrl">URL to the service that handles the add folder request.</param>
/// <param name="target">EntityReference of the target entity the folder is regarding. <see cref="EntityReference"/></param>
/// <param name="size">Size of the modal. <see cref="BootstrapExtensions.BootstrapModalSize"/></param>
/// <param name="cssClass">CSS class assigned to the modal.</param>
/// <param name="title">Title assigned to the modal.</param>
/// <param name="dismissButtonSrText">The text to display for the dismiss button for screen readers only.</param>
/// <param name="primaryButtonText">Text displayed for the primary button.</param>
/// <param name="cancelButtonText">Text displayed for the cancel button.</param>
/// <param name="titleCssClass">CSS class assigned to the title element in the header.</param>
/// <param name="primaryButtonCssClass">CSS class assigned to the primary button.</param>
/// <param name="closeButtonCssClass">CSS class assigned to the close button.</param>
/// <param name="nameLabel">Text displayed for the folder name label.</param>
/// <param name="destinationFolderLabel">Text displayed for the destination folder label.</param>
/// <param name="formLeftColumnCssClass">CSS class applied to the form's left column.</param>
/// <param name="formRightColumnCssClass">CSS class applied to the form's right column.</param>
/// <param name="htmlAttributes">HTML Attributes assigned to the modal.</param>
public static IHtmlString AddFolderModal(this HtmlHelper html, EntityReference target, string serviceUrl,
BootstrapExtensions.BootstrapModalSize size = BootstrapExtensions.BootstrapModalSize.Default, string cssClass = null,
string title = null, string dismissButtonSrText = null, string primaryButtonText = null,
string cancelButtonText = null, string titleCssClass = null, string primaryButtonCssClass = null,
string closeButtonCssClass = null, string nameLabel = null, string destinationFolderLabel = null,
string formLeftColumnCssClass = null, string formRightColumnCssClass = null, IDictionary<string, string> htmlAttributes = null)
{
var body = new TagBuilder("div");
body.AddCssClass("add-folder");
body.AddCssClass("form-horizontal");
body.MergeAttribute("data-url", serviceUrl);
var entityReference = new JObject(new JProperty("LogicalName", target.LogicalName),
new JProperty("Id", target.Id.ToString()));
body.MergeAttribute("data-target", entityReference.ToString());
var row1 = new TagBuilder("div");
row1.AddCssClass("form-group");
var nameFieldLabel = new TagBuilder("label");
nameFieldLabel.AddCssClass(formLeftColumnCssClass.GetValueOrDefault(DefaultAddModalFormLeftColumnCssClass));
nameFieldLabel.AddCssClass("control-label");
nameFieldLabel.MergeAttribute("for", "FolderName");
nameFieldLabel.InnerHtml = nameLabel.GetValueOrDefault(DefaultAddFolderModalNameLabel);
var nameInputContainer = new TagBuilder("div");
nameInputContainer.AddCssClass(formRightColumnCssClass.GetValueOrDefault(DefaultAddModalFormRightColumnCssClass));
var nameInput = new TagBuilder("input");
nameInput.AddCssClass("form-control");
nameInput.MergeAttribute("id", "FolderName");
nameInput.MergeAttribute("type", "text");
nameInput.MergeAttribute("placeholder", nameLabel.GetValueOrDefault(DefaultAddFolderModalNameLabel));
nameInputContainer.InnerHtml = nameInput.ToString();
row1.InnerHtml = nameFieldLabel.ToString();
row1.InnerHtml += nameInputContainer.ToString();
body.InnerHtml += row1.ToString();
var row2 = new TagBuilder("div");
row2.AddCssClass("form-group");
row2.AddCssClass("destination-group");
var destinationLabel = new TagBuilder("label");
destinationLabel.AddCssClass(formLeftColumnCssClass.GetValueOrDefault(DefaultAddModalFormLeftColumnCssClass));
destinationLabel.AddCssClass("control-label");
destinationLabel.InnerHtml = destinationFolderLabel.GetValueOrDefault(DefaultAddModalDestinationLabel);
var destinationContainer = new TagBuilder("div");
destinationContainer.AddCssClass(formRightColumnCssClass.GetValueOrDefault(DefaultAddModalFormRightColumnCssClass));
var destination = new TagBuilder("p");
destination.AddCssClass("destination-folder");
destination.AddCssClass("form-control-static");
destinationContainer.InnerHtml = destination.ToString();
row2.InnerHtml = destinationLabel.ToString();
row2.InnerHtml += destinationContainer.ToString();
body.InnerHtml += row2.ToString();
return html.BoostrapModal(BootstrapExtensions.BootstrapModalSize.Default,
title.GetValueOrDefault(DefaultAddFolderModalTitle), body.ToString(),
string.Join(" ", new[] { "modal-add-folder", cssClass }).TrimEnd(' '), null, false,
dismissButtonSrText.GetValueOrDefault(DefaultModalDismissButtonSrText), false, false, false,
primaryButtonText.GetValueOrDefault(DefaultAddFolderModalPrimaryButtonText),
cancelButtonText.GetValueOrDefault(DefaultAddModalCancelButtonText), titleCssClass, primaryButtonCssClass,
closeButtonCssClass, htmlAttributes);
}
private static TagBuilder ActionCell(string toolbarButtonLabel, string deleteButtonLabel)
{
var actionCell = new TagBuilder("td");
actionCell.InnerHtml += "{{#unless IsParent}}";
var dropdown = new TagBuilder("div");
dropdown.AddCssClass("toolbar {{#if @last}} dropup {{else}} dropdown {{/if}} pull-right");
var dropdownLink = new TagBuilder("a");
dropdownLink.AddCssClass("btn btn-default btn-xs");
dropdownLink.MergeAttribute("href", "#");
dropdownLink.MergeAttribute("data-toggle", "dropdown");
dropdownLink.InnerHtml += toolbarButtonLabel.GetValueOrDefault(DefaultToolbarButtonLabel);
dropdown.InnerHtml += dropdownLink.ToString();
var dropdownMenu = new TagBuilder("ul");
dropdownMenu.AddCssClass("dropdown-menu");
dropdownMenu.MergeAttribute("role", "menu");
var deleteItem = new TagBuilder("li");
deleteItem.MergeAttribute("role", "presentation");
var deleteLink = new TagBuilder("a");
deleteLink.AddCssClass("delete-link");
deleteLink.MergeAttribute("role", "menuitem");
deleteLink.MergeAttribute("tabindex", "-1");
deleteLink.MergeAttribute("href", "#");
deleteLink.InnerHtml = deleteButtonLabel.GetValueOrDefault(DefaultDeleteButtonLabel);
deleteItem.InnerHtml = deleteLink.ToString();
dropdownMenu.InnerHtml += deleteItem.ToString();
dropdown.InnerHtml += dropdownMenu.ToString();
actionCell.InnerHtml += dropdown.ToString();
actionCell.InnerHtml += "{{/unless}}";
return actionCell;
}
}
public static class TagBuilderExtensions
{
public static string GetHTML(this TagBuilder tb)
{
return tb.ToString().Replace(" ", " "); // Fix error in handlebars template
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedServiceAttachmentsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
ServiceAttachment = "service_attachment592c837a",
};
ServiceAttachment expectedResponse = new ServiceAttachment
{
Id = 11672635353343658936UL,
TargetService = "target_service3f6f9a5a",
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DomainNames =
{
"domain_names58aa2a78",
},
CreationTimestamp = "creation_timestamp235e59a1",
ConnectedEndpoints =
{
new ServiceAttachmentConnectedEndpoint(),
},
Region = "regionedb20d96",
ConsumerRejectLists =
{
"consumer_reject_lists640993ba",
},
Fingerprint = "fingerprint009e6052",
ProducerForwardingRule = "producer_forwarding_rule8732a25d",
ConnectionPreference = "connection_preference328ae231",
EnableProxyProtocol = true,
NatSubnets =
{
"nat_subnets59063249",
},
ConsumerAcceptLists =
{
new ServiceAttachmentConsumerProjectLimit(),
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
PscServiceAttachmentId = new Uint128(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
ServiceAttachment response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
ServiceAttachment = "service_attachment592c837a",
};
ServiceAttachment expectedResponse = new ServiceAttachment
{
Id = 11672635353343658936UL,
TargetService = "target_service3f6f9a5a",
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DomainNames =
{
"domain_names58aa2a78",
},
CreationTimestamp = "creation_timestamp235e59a1",
ConnectedEndpoints =
{
new ServiceAttachmentConnectedEndpoint(),
},
Region = "regionedb20d96",
ConsumerRejectLists =
{
"consumer_reject_lists640993ba",
},
Fingerprint = "fingerprint009e6052",
ProducerForwardingRule = "producer_forwarding_rule8732a25d",
ConnectionPreference = "connection_preference328ae231",
EnableProxyProtocol = true,
NatSubnets =
{
"nat_subnets59063249",
},
ConsumerAcceptLists =
{
new ServiceAttachmentConsumerProjectLimit(),
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
PscServiceAttachmentId = new Uint128(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
ServiceAttachment responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServiceAttachment responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
ServiceAttachment = "service_attachment592c837a",
};
ServiceAttachment expectedResponse = new ServiceAttachment
{
Id = 11672635353343658936UL,
TargetService = "target_service3f6f9a5a",
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DomainNames =
{
"domain_names58aa2a78",
},
CreationTimestamp = "creation_timestamp235e59a1",
ConnectedEndpoints =
{
new ServiceAttachmentConnectedEndpoint(),
},
Region = "regionedb20d96",
ConsumerRejectLists =
{
"consumer_reject_lists640993ba",
},
Fingerprint = "fingerprint009e6052",
ProducerForwardingRule = "producer_forwarding_rule8732a25d",
ConnectionPreference = "connection_preference328ae231",
EnableProxyProtocol = true,
NatSubnets =
{
"nat_subnets59063249",
},
ConsumerAcceptLists =
{
new ServiceAttachmentConsumerProjectLimit(),
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
PscServiceAttachmentId = new Uint128(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
ServiceAttachment response = client.Get(request.Project, request.Region, request.ServiceAttachment);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
ServiceAttachment = "service_attachment592c837a",
};
ServiceAttachment expectedResponse = new ServiceAttachment
{
Id = 11672635353343658936UL,
TargetService = "target_service3f6f9a5a",
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DomainNames =
{
"domain_names58aa2a78",
},
CreationTimestamp = "creation_timestamp235e59a1",
ConnectedEndpoints =
{
new ServiceAttachmentConnectedEndpoint(),
},
Region = "regionedb20d96",
ConsumerRejectLists =
{
"consumer_reject_lists640993ba",
},
Fingerprint = "fingerprint009e6052",
ProducerForwardingRule = "producer_forwarding_rule8732a25d",
ConnectionPreference = "connection_preference328ae231",
EnableProxyProtocol = true,
NatSubnets =
{
"nat_subnets59063249",
},
ConsumerAcceptLists =
{
new ServiceAttachmentConsumerProjectLimit(),
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
PscServiceAttachmentId = new Uint128(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
ServiceAttachment responseCallSettings = await client.GetAsync(request.Project, request.Region, request.ServiceAttachment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServiceAttachment responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.ServiceAttachment, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Project, request.Region, request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace EasyNetQ
{
/// <summary>
/// Collection of precondition methods for qualifying method arguments.
/// </summary>
internal static class Preconditions
{
/// <summary>
/// Ensures that <paramref name="value"/> is not null.
/// </summary>
/// <param name="value">
/// The value to check, must not be null.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="name"/> is blank.
/// </exception>
public static void CheckNotNull<T>(T value, string name) where T : class
{
CheckNotNull(value, name, string.Format("{0} must not be null", name));
}
/// <summary>
/// Ensures that <paramref name="value"/> is not null.
/// </summary>
/// <param name="value">
/// The value to check, must not be null.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="value"/>
/// is null, must not be blank.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="name"/> or <paramref name="message"/> are
/// blank.
/// </exception>
public static void CheckNotNull<T>(T value, string name, string message) where T : class
{
if (value == null)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentNullException(name, message);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is not blank.
/// </summary>
/// <param name="value">
/// The value to check, must not be blank.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="value"/>
/// is blank, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/>, <paramref name="name"/>, or
/// <paramref name="message"/> are blank.
/// </exception>
public static void CheckNotBlank(string value, string name, string message)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("name must not be blank", "name");
}
if (string.IsNullOrWhiteSpace(message))
{
throw new ArgumentException("message must not be blank", "message");
}
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is not blank.
/// </summary>
/// <param name="value">
/// The value to check, must not be blank.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> or <paramref name="name"/> are
/// blank.
/// </exception>
public static void CheckNotBlank(string value, string name)
{
CheckNotBlank(value, name, string.Format("{0} must not be blank", name));
}
/// <summary>
/// Ensures that <paramref name="collection"/> contains at least one
/// item.
/// </summary>
/// <param name="collection">
/// The collection to check, must not be null or empty.
/// </param>
/// <param name="name">
/// The name of the parameter the collection is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is empty, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="collection"/> is empty, or if
/// <paramref name="value"/> or <paramref name="name"/> are blank.
/// </exception>
public static void CheckAny<T>(IEnumerable<T> collection, string name, string message)
{
if (collection == null || !collection.Any())
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is true.
/// </summary>
/// <param name="value">
/// The value to check, must be true.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is false, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> is false, or if <paramref name="name"/>
/// or <paramref name="message"/> are blank.
/// </exception>
public static void CheckTrue(bool value, string name, string message)
{
if (!value)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is false.
/// </summary>
/// <param name="value">
/// The value to check, must be false.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is true, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> is true, or if <paramref name="name"/>
/// or <paramref name="message"/> are blank.
/// </exception>
public static void CheckFalse(bool value, string name, string message)
{
if (value)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
public static void CheckShortString(string value, string name)
{
CheckNotNull(value, name);
if (value.Length > 255)
{
throw new ArgumentException(string.Format("Argument '{0}' must be less than or equal to 255 characters.", name));
}
}
public static void CheckTypeMatches(Type expectedType, object value, string name, string message)
{
if (!expectedType.IsAssignableFrom(value.GetType()))
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
public static void CheckLess(TimeSpan value, TimeSpan maxValue, string name)
{
if (value < maxValue)
return;
throw new ArgumentOutOfRangeException(name, string.Format("Arguments {0} must be less than maxValue", name));
}
}
}
| |
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 StarterKit.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;
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using Microsoft.Build.Framework;
namespace GitVersionTask.Tests.Helpers
{
/// <summary>
/// Offers a default string format for Error and Warning events
/// </summary>
internal static class EventArgsFormatting
{
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e)
{
// "error" should not be localized
return FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile)
{
// "error" should not be localized
return FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e)
{
// "warning" should not be localized
return FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile)
{
// "warning" should not be localized
return FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildMessageEventArgs e)
{
return FormatEventMessage(e, false);
}
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <param name="showProjectFile">Show project file or not</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile)
{
// "message" should not be localized
return FormatEventMessage("message", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage
(
string category,
string subcategory,
string message,
string code,
string file,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
)
{
return FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId);
}
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="projectFile">the project file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage
(
string category,
string subcategory,
string message,
string code,
string file,
string projectFile,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
)
{
var format = new StringBuilder();
// Uncomment these lines to show show the processor, if present.
/*
if (threadId != 0)
{
format.Append("{0}>");
}
*/
if ((file == null) || (file.Length == 0))
{
format.Append("MSBUILD : "); // Should not be localized.
}
else
{
format.Append("{1}");
if (lineNumber == 0)
{
format.Append(" : ");
}
else
{
if (columnNumber == 0)
{
if (endLineNumber == 0)
{
format.Append("({2}): ");
}
else
{
format.Append("({2}-{7}): ");
}
}
else
{
if (endLineNumber == 0)
{
if (endColumnNumber == 0)
{
format.Append("({2},{3}): ");
}
else
{
format.Append("({2},{3}-{8}): ");
}
}
else
{
if (endColumnNumber == 0)
{
format.Append("({2}-{7},{3}): ");
}
else
{
format.Append("({2},{3},{7},{8}): ");
}
}
}
}
}
if ((subcategory != null) && (subcategory.Length != 0))
{
format.Append("{9} ");
}
// The category as a string (should not be localized)
format.Append("{4} ");
// Put a code in, if available and necessary.
if (code == null)
{
format.Append(": ");
}
else
{
format.Append("{5}: ");
}
// Put the message in, if available.
if (message != null)
{
format.Append("{6}");
}
// If the project file was specified, tack that onto the very end.
if (projectFile != null && !string.Equals(projectFile, file))
{
format.Append(" [{10}]");
}
// A null message is allowed and is to be treated as a blank line.
if (null == message)
{
message = string.Empty;
}
var finalFormat = format.ToString();
// If there are multiple lines, show each line as a separate message.
var lines = SplitStringOnNewLines(message);
var formattedMessage = new StringBuilder();
for (var i = 0; i < lines.Length; i++)
{
formattedMessage.Append(string.Format(
CultureInfo.CurrentCulture, finalFormat,
threadId, file,
lineNumber, columnNumber, category, code,
lines[i], endLineNumber, endColumnNumber,
subcategory, projectFile));
if (i < (lines.Length - 1))
{
formattedMessage.AppendLine();
}
}
return formattedMessage.ToString();
}
/// <summary>
/// Splits strings on 'newLines' with tolerance for Everett and Dogfood builds.
/// </summary>
/// <param name="s">String to split.</param>
private static string[] SplitStringOnNewLines(string s)
{
var subStrings = s.Split(s_newLines, StringSplitOptions.None);
return subStrings;
}
/// <summary>
/// The kinds of newline breaks we expect.
/// </summary>
/// <remarks>Currently we're not supporting "\r".</remarks>
private static readonly string[] s_newLines = { "\r\n", "\n" };
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.Intrinsics
{
// We mark certain methods with AggressiveInlining to ensure that the JIT will
// inline them. The JIT would otherwise not inline the method since it, at the
// point it tries to determine inline profability, currently cannot determine
// that most of the code-paths will be optimized away as "dead code".
//
// We then manually inline cases (such as certain intrinsic code-paths) that
// will generate code small enough to make the AgressiveInlining profitable. The
// other cases (such as the software fallback) are placed in their own method.
// This ensures we get good codegen for the "fast-path" and allows the JIT to
// determine inline profitability of the other paths as it would normally.
[Intrinsic]
[DebuggerDisplay("{DisplayString,nq}")]
[DebuggerTypeProxy(typeof(Vector128DebugView<>))]
[StructLayout(LayoutKind.Sequential, Size = Vector128.Size)]
public readonly struct Vector128<T> : IEquatable<Vector128<T>>, IFormattable
where T : struct
{
// These fields exist to ensure the alignment is 8, rather than 1.
// This also allows the debug view to work https://github.com/dotnet/coreclr/issues/15694)
private readonly ulong _00;
private readonly ulong _01;
/// <summary>Gets the number of <typeparamref name="T" /> that are in a <see cref="Vector128{T}" />.</summary>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public static int Count
{
get
{
ThrowHelper.ThrowForUnsupportedVectorBaseType<T>();
return Vector128.Size / Unsafe.SizeOf<T>();
}
}
/// <summary>Gets a new <see cref="Vector128{T}" /> with all elements initialized to zero.</summary>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public static Vector128<T> Zero
{
[Intrinsic]
get
{
ThrowHelper.ThrowForUnsupportedVectorBaseType<T>();
return default;
}
}
internal unsafe string DisplayString
{
get
{
if (IsSupported)
{
return ToString();
}
else
{
return SR.NotSupported_Type;
}
}
}
internal static bool IsSupported
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return (typeof(T) == typeof(byte)) ||
(typeof(T) == typeof(sbyte)) ||
(typeof(T) == typeof(short)) ||
(typeof(T) == typeof(ushort)) ||
(typeof(T) == typeof(int)) ||
(typeof(T) == typeof(uint)) ||
(typeof(T) == typeof(long)) ||
(typeof(T) == typeof(ulong)) ||
(typeof(T) == typeof(float)) ||
(typeof(T) == typeof(double));
}
}
/// <summary>Determines whether the specified <see cref="Vector128{T}" /> is equal to the current instance.</summary>
/// <param name="other">The <see cref="Vector128{T}" /> to compare with the current instance.</param>
/// <returns><c>true</c> if <paramref name="other" /> is equal to the current instance; otherwise, <c>false</c>.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(Vector128<T> other)
{
ThrowHelper.ThrowForUnsupportedVectorBaseType<T>();
if (Sse.IsSupported && (typeof(T) == typeof(float)))
{
Vector128<float> result = Sse.CompareEqual(this.AsSingle(), other.AsSingle());
return Sse.MoveMask(result) == 0b1111; // We have one bit per element
}
if (Sse2.IsSupported)
{
if (typeof(T) == typeof(double))
{
Vector128<double> result = Sse2.CompareEqual(this.AsDouble(), other.AsDouble());
return Sse2.MoveMask(result) == 0b11; // We have one bit per element
}
else
{
// Unlike float/double, there are no special values to consider
// for integral types and we can just do a comparison that all
// bytes are exactly the same.
Debug.Assert((typeof(T) != typeof(float)) && (typeof(T) != typeof(double)));
Vector128<byte> result = Sse2.CompareEqual(this.AsByte(), other.AsByte());
return Sse2.MoveMask(result) == 0b1111_1111_1111_1111; // We have one bit per element
}
}
return SoftwareFallback(in this, other);
static bool SoftwareFallback(in Vector128<T> vector, Vector128<T> other)
{
for (int i = 0; i < Count; i++)
{
if (!((IEquatable<T>)(vector.GetElement(i))).Equals(other.GetElement(i)))
{
return false;
}
}
return true;
}
}
/// <summary>Determines whether the specified object is equal to the current instance.</summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Vector128{T}" /> and is equal to the current instance; otherwise, <c>false</c>.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public override bool Equals(object obj)
{
return (obj is Vector128<T>) && Equals((Vector128<T>)(obj));
}
/// <summary>Gets the hash code for the instance.</summary>
/// <returns>The hash code for the instance.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public override int GetHashCode()
{
ThrowHelper.ThrowForUnsupportedVectorBaseType<T>();
int hashCode = 0;
for (int i = 0; i < Count; i++)
{
hashCode = HashCode.Combine(hashCode, this.GetElement(i).GetHashCode());
}
return hashCode;
}
/// <summary>Converts the current instance to an equivalent string representation.</summary>
/// <returns>An equivalent string representation of the current instance.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public override string ToString()
{
return ToString("G");
}
/// <summary>Converts the current instance to an equivalent string representation using the specified format.</summary>
/// <param name="format">The format specifier used to format the individual elements of the current instance.</param>
/// <returns>An equivalent string representation of the current instance.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public string ToString(string format)
{
return ToString(format, formatProvider: null);
}
/// <summary>Converts the current instance to an equivalent string representation using the specified format.</summary>
/// <param name="format">The format specifier used to format the individual elements of the current instance.</param>
/// <param name="formatProvider">The format provider used to format the individual elements of the current instance.</param>
/// <returns>An equivalent string representation of the current instance.</returns>
/// <exception cref="NotSupportedException">The type of the current instance (<typeparamref name="T" />) is not supported.</exception>
public string ToString(string format, IFormatProvider formatProvider)
{
ThrowHelper.ThrowForUnsupportedVectorBaseType<T>();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
int lastElement = Count - 1;
var sb = StringBuilderCache.Acquire();
sb.Append('<');
for (int i = 0; i < lastElement; i++)
{
sb.Append(((IFormattable)(this.GetElement(i))).ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
}
sb.Append(((IFormattable)(this.GetElement(lastElement))).ToString(format, formatProvider));
sb.Append('>');
return StringBuilderCache.GetStringAndRelease(sb);
}
}
}
| |
// 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.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const string AnonymousPipeName = "anonymous";
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
protected void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(new Span<byte>(buffer, offset, count));
}
public override int Read(Span<byte> destination)
{
if (_isAsync)
{
return base.Read(destination);
}
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(destination);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(new Memory<byte>(buffer, offset, count), cancellationToken);
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_isAsync)
{
return base.ReadAsync(destination, cancellationToken);
}
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
CheckReadOperations();
if (destination.Length == 0)
{
UpdateMessageCompletion(false);
return new ValueTask<int>(0);
}
return new ValueTask<int>(ReadAsyncCore(destination, cancellationToken));
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (_isAsync)
return TaskToApm.End<int>(asyncResult);
else
return base.EndRead(asyncResult);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
}
public override void Write(ReadOnlySpan<byte> source)
{
if (_isAsync)
{
base.Write(source);
return;
}
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(source);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_isAsync)
{
return base.WriteAsync(source, cancellationToken);
}
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (source.Length == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(source, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (_isAsync)
TaskToApm.End(asyncResult);
else
base.EndWrite(asyncResult);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertHandleValid(SafePipeHandle handle)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
[Conditional("DEBUG")]
private static void DebugAssertReadWriteArgs(byte[] buffer, int offset, int count, SafePipeHandle handle)
{
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(offset <= buffer.Length - count, "offset + count is too big");
DebugAssertHandleValid(handle);
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
public override unsafe int ReadByte()
{
byte b;
return Read(new Span<byte>(&b, 1)) > 0 ? b : -1;
}
public override unsafe void WriteByte(byte value)
{
Write(new ReadOnlySpan<byte>(&value, 1));
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
DisposeCore(disposing);
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
get
{
return _handle;
}
}
protected bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
get
{
return _canRead;
}
}
public override bool CanWrite
{
get
{
return _canWrite;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
protected internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
protected internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
protected internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
// <copyright file="MlkBiCgStab.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers
{
/// <summary>
/// A Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver is an 'improvement'
/// of the standard BiCgStab solver.
/// </para>
/// <para>
/// The algorithm was taken from: <br/>
/// ML(k)BiCGSTAB: A BiCGSTAB variant based on multiple Lanczos starting vectors
/// <br/>
/// Man-chung Yeung and Tony F. Chan
/// <br/>
/// SIAM Journal of Scientific Computing
/// <br/>
/// Volume 21, Number 4, pp. 1263 - 1290
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class MlkBiCgStab : IIterativeSolver<Numerics.Complex32>
{
/// <summary>
/// The default number of starting vectors.
/// </summary>
const int DefaultNumberOfStartingVectors = 50;
/// <summary>
/// The collection of starting vectors which are used as the basis for the Krylov sub-space.
/// </summary>
IList<Vector<Numerics.Complex32>> _startingVectors;
/// <summary>
/// The number of starting vectors used by the algorithm
/// </summary>
int _numberOfStartingVectors = DefaultNumberOfStartingVectors;
/// <summary>
/// Gets or sets the number of starting vectors.
/// </summary>
/// <remarks>
/// Must be larger than 1 and smaller than the number of variables in the matrix that
/// for which this solver will be used.
/// </remarks>
public int NumberOfStartingVectors
{
[DebuggerStepThrough]
get { return _numberOfStartingVectors; }
[DebuggerStepThrough]
set
{
if (value <= 1)
{
throw new ArgumentOutOfRangeException("value");
}
_numberOfStartingVectors = value;
}
}
/// <summary>
/// Resets the number of starting vectors to the default value.
/// </summary>
public void ResetNumberOfStartingVectors()
{
_numberOfStartingVectors = DefaultNumberOfStartingVectors;
}
/// <summary>
/// Gets or sets a series of orthonormal vectors which will be used as basis for the
/// Krylov sub-space.
/// </summary>
public IList<Vector<Numerics.Complex32>> StartingVectors
{
[DebuggerStepThrough]
get { return _startingVectors; }
[DebuggerStepThrough]
set
{
if ((value == null) || (value.Count == 0))
{
_startingVectors = null;
}
else
{
_startingVectors = value;
}
}
}
/// <summary>
/// Gets the number of starting vectors to create
/// </summary>
/// <param name="maximumNumberOfStartingVectors">Maximum number</param>
/// <param name="numberOfVariables">Number of variables</param>
/// <returns>Number of starting vectors to create</returns>
static int NumberOfStartingVectorsToCreate(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
return Math.Min(maximumNumberOfStartingVectors, (numberOfVariables - 1));
}
/// <summary>
/// Returns an array of starting vectors.
/// </summary>
/// <param name="maximumNumberOfStartingVectors">The maximum number of starting vectors that should be created.</param>
/// <param name="numberOfVariables">The number of variables.</param>
/// <returns>
/// An array with starting vectors. The array will never be larger than the
/// <paramref name="maximumNumberOfStartingVectors"/> but it may be smaller if
/// the <paramref name="numberOfVariables"/> is smaller than
/// the <paramref name="maximumNumberOfStartingVectors"/>.
/// </returns>
static IList<Vector<Numerics.Complex32>> CreateStartingVectors(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
// Get random values and then orthogonalize them with
// modified Gramm - Schmidt
var count = NumberOfStartingVectorsToCreate(maximumNumberOfStartingVectors, numberOfVariables);
// Get a random set of samples based on the standard normal distribution with
// mean = 0 and sd = 1
var distribution = new Normal();
var matrix = new DenseMatrix(numberOfVariables, count);
for (var i = 0; i < matrix.ColumnCount; i++)
{
var samples = new Numerics.Complex32[matrix.RowCount];
var samplesRe = distribution.Samples().Take(matrix.RowCount).ToArray();
var samplesIm = distribution.Samples().Take(matrix.RowCount).ToArray();
for (int j = 0; j < matrix.RowCount; j++)
{
samples[j] = new Numerics.Complex32((float)samplesRe[j], (float)samplesIm[j]);
}
// Set the column
matrix.SetColumn(i, samples);
}
// Compute the orthogonalization.
var gs = matrix.GramSchmidt();
var orthogonalMatrix = gs.Q;
// Now transfer this to vectors
var result = new List<Vector<Numerics.Complex32>>();
for (var i = 0; i < orthogonalMatrix.ColumnCount; i++)
{
result.Add(orthogonalMatrix.Column(i));
// Normalize the result vector
result[i].Multiply(1/(float) result[i].L2Norm(), result[i]);
}
return result;
}
/// <summary>
/// Create random vectors array
/// </summary>
/// <param name="arraySize">Number of vectors</param>
/// <param name="vectorSize">Size of each vector</param>
/// <returns>Array of random vectors</returns>
static Vector<Numerics.Complex32>[] CreateVectorArray(int arraySize, int vectorSize)
{
var result = new Vector<Numerics.Complex32>[arraySize];
for (var i = 0; i < result.Length; i++)
{
result[i] = new DenseVector(vectorSize);
}
return result;
}
/// <summary>
/// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Source <see cref="Matrix"/>A.</param>
/// <param name="residual">Residual <see cref="Vector"/> data.</param>
/// <param name="x">x <see cref="Vector"/> data.</param>
/// <param name="b">b <see cref="Vector"/> data.</param>
static void CalculateTrueResidual(Matrix<Numerics.Complex32> matrix, Vector<Numerics.Complex32> residual, Vector<Numerics.Complex32> x, Vector<Numerics.Complex32> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<Numerics.Complex32> matrix, Vector<Numerics.Complex32> input, Vector<Numerics.Complex32> result, Iterator<Numerics.Complex32> iterator, IPreconditioner<Numerics.Complex32> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (result.Count != input.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (input.Count != matrix.RowCount)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix);
}
if (iterator == null)
{
iterator = new Iterator<Numerics.Complex32>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<Numerics.Complex32>();
}
preconditioner.Initialize(matrix);
// Choose an initial guess x_0
// Take x_0 = 0
var xtemp = new DenseVector(input.Count);
// Choose k vectors q_1, q_2, ..., q_k
// Build a new set if:
// a) the stored set doesn't exist (i.e. == null)
// b) Is of an incorrect length (i.e. too long)
// c) The vectors are of an incorrect length (i.e. too long or too short)
var useOld = false;
if (_startingVectors != null)
{
// We don't accept collections with zero starting vectors so ...
if (_startingVectors.Count <= NumberOfStartingVectorsToCreate(_numberOfStartingVectors, input.Count))
{
// Only check the first vector for sizing. If that matches we assume the
// other vectors match too. If they don't the process will crash
if (_startingVectors[0].Count == input.Count)
{
useOld = true;
}
}
}
_startingVectors = useOld ? _startingVectors : CreateStartingVectors(_numberOfStartingVectors, input.Count);
// Store the number of starting vectors. Not really necessary but easier to type :)
var k = _startingVectors.Count;
// r_0 = b - Ax_0
// This is basically a SAXPY so it could be made a lot faster
var residuals = new DenseVector(matrix.RowCount);
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Define the temporary values
var c = new Numerics.Complex32[k];
// Define the temporary vectors
var gtemp = new DenseVector(residuals.Count);
var u = new DenseVector(residuals.Count);
var utemp = new DenseVector(residuals.Count);
var temp = new DenseVector(residuals.Count);
var temp1 = new DenseVector(residuals.Count);
var temp2 = new DenseVector(residuals.Count);
var zd = new DenseVector(residuals.Count);
var zg = new DenseVector(residuals.Count);
var zw = new DenseVector(residuals.Count);
var d = CreateVectorArray(_startingVectors.Count, residuals.Count);
// g_0 = r_0
var g = CreateVectorArray(_startingVectors.Count, residuals.Count);
residuals.CopyTo(g[k - 1]);
var w = CreateVectorArray(_startingVectors.Count, residuals.Count);
// FOR (j = 0, 1, 2 ....)
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue)
{
// SOLVE M g~_((j-1)k+k) = g_((j-1)k+k)
preconditioner.Approximate(g[k - 1], gtemp);
// w_((j-1)k+k) = A g~_((j-1)k+k)
matrix.Multiply(gtemp, w[k - 1]);
// c_((j-1)k+k) = q^T_1 w_((j-1)k+k)
c[k - 1] = _startingVectors[0].ConjugateDotProduct(w[k - 1]);
if (c[k - 1].Real.AlmostEqualNumbersBetween(0, 1) && c[k - 1].Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+1) = q^T_1 r_((j-1)k+k) / c_((j-1)k+k)
var alpha = _startingVectors[0].ConjugateDotProduct(residuals)/c[k - 1];
// u_(jk+1) = r_((j-1)k+k) - alpha_(jk+1) w_((j-1)k+k)
w[k - 1].Multiply(-alpha, temp);
residuals.Add(temp, u);
// SOLVE M u~_(jk+1) = u_(jk+1)
preconditioner.Approximate(u, temp1);
temp1.CopyTo(utemp);
// rho_(j+1) = -u^t_(jk+1) A u~_(jk+1) / ||A u~_(jk+1)||^2
matrix.Multiply(temp1, temp);
var rho = temp.ConjugateDotProduct(temp);
// If rho is zero then temp is a zero vector and we're probably
// about to have zero residuals (i.e. an exact solution).
// So set rho to 1.0 because in the next step it will turn to zero.
if (rho.Real.AlmostEqualNumbersBetween(0, 1) && rho.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
rho = 1.0f;
}
rho = -u.ConjugateDotProduct(temp)/rho;
// r_(jk+1) = rho_(j+1) A u~_(jk+1) + u_(jk+1)
u.CopyTo(residuals);
// Reuse temp
temp.Multiply(rho, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// x_(jk+1) = x_((j-1)k_k) - rho_(j+1) u~_(jk+1) + alpha_(jk+1) g~_((j-1)k+k)
utemp.Multiply(-rho, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
gtemp.Multiply(alpha, gtemp);
xtemp.Add(gtemp, temp2);
temp2.CopyTo(xtemp);
// Check convergence and stop if we are converged.
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Calculate the true residual
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// We're all good now.
// Exit from the while loop.
break;
}
}
// FOR (i = 1,2, ...., k)
for (var i = 0; i < k; i++)
{
// z_d = u_(jk+1)
u.CopyTo(zd);
// z_g = r_(jk+i)
residuals.CopyTo(zg);
// z_w = 0
zw.Clear();
// FOR (s = i, ...., k-1) AND j >= 1
Numerics.Complex32 beta;
if (iterationNumber >= 1)
{
for (var s = i; s < k - 1; s++)
{
// beta^(jk+i)_((j-1)k+s) = -q^t_(s+1) z_d / c_((j-1)k+s)
beta = -_startingVectors[s + 1].ConjugateDotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_((j-1)k+s) d_((j-1)k+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_((j-1)k+s) g_((j-1)k+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = z_w + beta^(jk+i)_((j-1)k+s) w_((j-1)k+s)
w[s].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
}
}
beta = rho*c[k - 1];
if (beta.Real.AlmostEqualNumbersBetween(0, 1) && beta.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// beta^(jk+i)_((j-1)k+k) = -(q^T_1 (r_(jk+1) + rho_(j+1) z_w)) / (rho_(j+1) c_((j-1)k+k))
zw.Multiply(rho, temp2);
residuals.Add(temp2, temp);
beta = -_startingVectors[0].ConjugateDotProduct(temp)/beta;
// z_g = z_g + beta^(jk+i)_((j-1)k+k) g_((j-1)k+k)
g[k - 1].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = rho_(j+1) (z_w + beta^(jk+i)_((j-1)k+k) w_((j-1)k+k))
w[k - 1].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
zw.Multiply(rho, zw);
// z_d = r_(jk+i) + z_w
residuals.Add(zw, zd);
// FOR (s = 1, ... i - 1)
for (var s = 0; s < i - 1; s++)
{
// beta^(jk+i)_(jk+s) = -q^T_s+1 z_d / c_(jk+s)
beta = -_startingVectors[s + 1].ConjugateDotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_(jk+s) * d_(jk+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_(jk+s) * g_(jk+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
}
// d_(jk+i) = z_d - u_(jk+i)
zd.Subtract(u, d[i]);
// g_(jk+i) = z_g + z_w
zg.Add(zw, g[i]);
// IF (i < k - 1)
if (i < k - 1)
{
// c_(jk+1) = q^T_i+1 d_(jk+i)
c[i] = _startingVectors[i + 1].ConjugateDotProduct(d[i]);
if (c[i].Real.AlmostEqualNumbersBetween(0, 1) && c[i].Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+i+1) = q^T_(i+1) u_(jk+i) / c_(jk+i)
alpha = _startingVectors[i + 1].ConjugateDotProduct(u)/c[i];
// u_(jk+i+1) = u_(jk+i) - alpha_(jk+i+1) d_(jk+i)
d[i].Multiply(-alpha, temp);
u.Add(temp, temp2);
temp2.CopyTo(u);
// SOLVE M g~_(jk+i) = g_(jk+i)
preconditioner.Approximate(g[i], gtemp);
// x_(jk+i+1) = x_(jk+i) + rho_(j+1) alpha_(jk+i+1) g~_(jk+i)
gtemp.Multiply(rho*alpha, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
// w_(jk+i) = A g~_(jk+i)
matrix.Multiply(gtemp, w[i]);
// r_(jk+i+1) = r_(jk+i) - rho_(j+1) alpha_(jk+i+1) w_(jk+i)
w[i].Multiply(-rho*alpha, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// We can check the residuals here if they're close
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Recalculate the residuals and go round again. This is done to ensure that
// we have the proper residuals.
CalculateTrueResidual(matrix, residuals, xtemp, input);
}
}
} // END ITERATION OVER i
iterationNumber++;
}
// copy the temporary result to the real result vector
xtemp.CopyTo(result);
}
}
}
| |
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 TAWG_API.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 J2N.Threading;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Search;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValuesField = BinaryDocValuesField;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValuesField = NumericDocValuesField;
using SortedDocValuesField = SortedDocValuesField;
using TestUtil = Lucene.Net.Util.TestUtil;
[SuppressCodecs("Lucene3x")]
[TestFixture]
public class TestDocValuesWithThreads : LuceneTestCase
{
[Test]
public virtual void Test()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
IList<long?> numbers = new List<long?>();
IList<BytesRef> binary = new List<BytesRef>();
IList<BytesRef> sorted = new List<BytesRef>();
int numDocs = AtLeast(100);
for (int i = 0; i < numDocs; i++)
{
Document d = new Document();
long number = Random.NextInt64();
d.Add(new NumericDocValuesField("number", number));
BytesRef bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random));
d.Add(new BinaryDocValuesField("bytes", bytes));
binary.Add(bytes);
bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random));
d.Add(new SortedDocValuesField("sorted", bytes));
sorted.Add(bytes);
w.AddDocument(d);
numbers.Add(number);
}
w.ForceMerge(1);
IndexReader r = w.GetReader();
w.Dispose();
Assert.AreEqual(1, r.Leaves.Count);
AtomicReader ar = (AtomicReader)r.Leaves[0].Reader;
int numThreads = TestUtil.NextInt32(Random, 2, 5);
IList<ThreadJob> threads = new List<ThreadJob>();
CountdownEvent startingGun = new CountdownEvent(1);
for (int t = 0; t < numThreads; t++)
{
Random threadRandom = new Random(Random.Next());
ThreadJob thread = new ThreadAnonymousInnerClassHelper(this, numbers, binary, sorted, numDocs, ar, startingGun, threadRandom);
thread.Start();
threads.Add(thread);
}
startingGun.Signal();
foreach (ThreadJob thread in threads)
{
thread.Join();
}
r.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadJob
{
private readonly TestDocValuesWithThreads outerInstance;
private readonly IList<long?> numbers;
private readonly IList<BytesRef> binary;
private readonly IList<BytesRef> sorted;
private readonly int numDocs;
private readonly AtomicReader ar;
private readonly CountdownEvent startingGun;
private readonly Random threadRandom;
public ThreadAnonymousInnerClassHelper(TestDocValuesWithThreads outerInstance, IList<long?> numbers, IList<BytesRef> binary, IList<BytesRef> sorted, int numDocs, AtomicReader ar, CountdownEvent startingGun, Random threadRandom)
{
this.outerInstance = outerInstance;
this.numbers = numbers;
this.binary = binary;
this.sorted = sorted;
this.numDocs = numDocs;
this.ar = ar;
this.startingGun = startingGun;
this.threadRandom = threadRandom;
}
public override void Run()
{
try
{
//NumericDocValues ndv = ar.GetNumericDocValues("number");
FieldCache.Int64s ndv = FieldCache.DEFAULT.GetInt64s(ar, "number", false);
//BinaryDocValues bdv = ar.GetBinaryDocValues("bytes");
BinaryDocValues bdv = FieldCache.DEFAULT.GetTerms(ar, "bytes", false);
SortedDocValues sdv = FieldCache.DEFAULT.GetTermsIndex(ar, "sorted");
startingGun.Wait();
int iters = AtLeast(1000);
BytesRef scratch = new BytesRef();
BytesRef scratch2 = new BytesRef();
for (int iter = 0; iter < iters; iter++)
{
int docID = threadRandom.Next(numDocs);
switch (threadRandom.Next(6))
{
#pragma warning disable 612, 618
case 0:
Assert.AreEqual((long)(sbyte)numbers[docID], (sbyte)FieldCache.DEFAULT.GetBytes(ar, "number", false).Get(docID));
break;
case 1:
Assert.AreEqual((long)(short)numbers[docID], FieldCache.DEFAULT.GetInt16s(ar, "number", false).Get(docID));
break;
#pragma warning restore 612, 618
case 2:
Assert.AreEqual((long)(int)numbers[docID], FieldCache.DEFAULT.GetInt32s(ar, "number", false).Get(docID));
break;
case 3:
Assert.AreEqual((long)numbers[docID], FieldCache.DEFAULT.GetInt64s(ar, "number", false).Get(docID));
break;
case 4:
Assert.AreEqual(J2N.BitConversion.Int32BitsToSingle((int)numbers[docID]), FieldCache.DEFAULT.GetSingles(ar, "number", false).Get(docID), 0.0f);
break;
case 5:
Assert.AreEqual(J2N.BitConversion.Int64BitsToDouble((long)numbers[docID]), FieldCache.DEFAULT.GetDoubles(ar, "number", false).Get(docID), 0.0);
break;
}
bdv.Get(docID, scratch);
Assert.AreEqual(binary[docID], scratch);
// Cannot share a single scratch against two "sources":
sdv.Get(docID, scratch2);
Assert.AreEqual(sorted[docID], scratch2);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
}
[Test]
public virtual void Test2()
{
Random random = Random;
int NUM_DOCS = AtLeast(100);
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
random, dir);
bool allowDups = random.NextBoolean();
ISet<string> seen = new JCG.HashSet<string>();
if (Verbose)
{
Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS + " allowDups=" + allowDups);
}
int numDocs = 0;
IList<BytesRef> docValues = new List<BytesRef>();
// TODO: deletions
while (numDocs < NUM_DOCS)
{
string s;
if (random.NextBoolean())
{
s = TestUtil.RandomSimpleString(random);
}
else
{
s = TestUtil.RandomUnicodeString(random);
}
BytesRef br = new BytesRef(s);
if (!allowDups)
{
if (seen.Contains(s))
{
continue;
}
seen.Add(s);
}
if (Verbose)
{
Console.WriteLine(" " + numDocs + ": s=" + s);
}
Document doc = new Document();
doc.Add(new SortedDocValuesField("stringdv", br));
doc.Add(new NumericDocValuesField("id", numDocs));
docValues.Add(br);
writer.AddDocument(doc);
numDocs++;
if (random.Next(40) == 17)
{
// force flush
writer.GetReader().Dispose();
}
}
writer.ForceMerge(1);
DirectoryReader r = writer.GetReader();
writer.Dispose();
AtomicReader sr = GetOnlySegmentReader(r);
long END_TIME = Environment.TickCount + (TestNightly ? 30 : 1);
int NUM_THREADS = TestUtil.NextInt32(LuceneTestCase.Random, 1, 10);
ThreadJob[] threads = new ThreadJob[NUM_THREADS];
for (int thread = 0; thread < NUM_THREADS; thread++)
{
threads[thread] = new ThreadAnonymousInnerClassHelper2(random, docValues, sr, END_TIME);
threads[thread].Start();
}
foreach (ThreadJob thread in threads)
{
thread.Join();
}
r.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper2 : ThreadJob
{
private readonly Random random;
private readonly IList<BytesRef> docValues;
private readonly AtomicReader sr;
private readonly long endTime;
public ThreadAnonymousInnerClassHelper2(Random random, IList<BytesRef> docValues, AtomicReader sr, long endTime)
{
this.random = random;
this.docValues = docValues;
this.sr = sr;
this.endTime = endTime;
}
public override void Run()
{
SortedDocValues stringDVDirect;
NumericDocValues docIDToID;
try
{
stringDVDirect = sr.GetSortedDocValues("stringdv");
docIDToID = sr.GetNumericDocValues("id");
Assert.IsNotNull(stringDVDirect);
}
catch (IOException ioe)
{
throw new Exception(ioe.ToString(), ioe);
}
while (Environment.TickCount < endTime)
{
SortedDocValues source;
source = stringDVDirect;
BytesRef scratch = new BytesRef();
for (int iter = 0; iter < 100; iter++)
{
int docID = random.Next(sr.MaxDoc);
source.Get(docID, scratch);
Assert.AreEqual(docValues[(int)docIDToID.Get(docID)], scratch);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Linq;
namespace HTLib2
{
public static partial class LinAlgSparse
{
public static MatrixSparse<T> ToColMatrix<T>(VectorSparse<T> vec)
{
MatrixSparse<T> mat = new MatrixSparse<T>(vec.Size, 1, GetDefault: vec.GetDefault);
foreach(var i_val in vec.EnumElements())
{
int i = i_val.Item1;
var val = i_val.Item2;
mat[i, 0] = val;
}
return mat;
}
public static double[,] ToArray(MatrixSparse<MatrixByArr> mat)
{
return MatrixByArr.FromMatrixArray(mat.ToArray());
}
public static double[,] ToArray(VectorSparse<MatrixByArr> vec)
{
return MatrixByArr.FromMatrixArray(ToColMatrix(vec).ToArray());
}
public static MatrixByArr VtV(VectorSparse<MatrixByArr> l, VectorSparse<MatrixByArr> r)
{
HDebug.Assert(l.Size == r.Size);
IList<int> l_idx = new List<int>(l.EnumIndex());
IList<int> r_idx = new List<int>(r.EnumIndex());
IList<int> idxs = l_idx.HListCommonT(r_idx);
MatrixByArr val = l.GetDefault();
foreach(var idx in idxs)
{
val += l[idx].Tr() * r[idx];
}
if(HDebug.IsDebuggerAttached)
{
MatrixByArr tl = ToArray(l);
MatrixByArr tr = ToArray(r);
MatrixByArr tval = tl.Tr() * tr;
HDebug.AssertTolerance(0.00000001, val-tval);
}
return val;
}
public static MatrixSparse<MatrixByArr> VVt(VectorSparse<MatrixByArr> v0, VectorSparse<MatrixByArr> v1)
{
MatrixSparse<MatrixByArr> mat = new MatrixSparse<MatrixByArr>(v0.Size, v1.Size, GetDefault: v0.GetDefault);
foreach(var i1_val1 in v1.EnumElements())
{
int i1 = i1_val1.Item1;
MatrixByArr val1t = i1_val1.Item2.Tr();
foreach(var i0_val0 in v0.EnumElements())
{
int i0 = i0_val0.Item1;
MatrixByArr val0 = i0_val0.Item2;
mat[i0, i1] = val0 * val1t;
}
}
if(HDebug.IsDebuggerAttached)
{
MatrixByArr tv0 = ToArray(v0);
MatrixByArr tv1 = ToArray(v1);
MatrixByArr tmat = tv0 * tv1.Tr();
HDebug.AssertTolerance(0.00000001, ToArray(mat)-tmat);
}
return mat;
}
public static MatrixSparse<MatrixByArr> Sum_M_Mt(MatrixSparse<MatrixByArr> mat)
{
HDebug.Assert(mat.ColSize == mat.RowSize);
MatrixSparse<MatrixByArr> result = new MatrixSparse<MatrixByArr>(mat.ColSize, mat.RowSize, GetDefault:mat.GetDefault);
foreach(var c_r_val in mat.EnumElements())
{
int c = c_r_val.Item1;
int r = c_r_val.Item2;
var val = c_r_val.Item3;
result[c, r] += val;
result[r, c] += val.Tr();
}
return result;
}
public static VectorSparse<MatrixByArr> MV(MatrixSparse<MatrixByArr> lmat, VectorSparse<MatrixByArr> rvec)
{
HDebug.Assert(lmat.RowSize == rvec.Size);
VectorSparse<MatrixByArr> result = new VectorSparse<MatrixByArr>(lmat.ColSize, lmat.GetDefault);
foreach(var c_r_val in lmat.EnumElements())
{
int c = c_r_val.Item1;
int r = c_r_val.Item2;
MatrixByArr mat_cr = c_r_val.Item3;
if(rvec.HasElement(r) == false)
continue;
MatrixByArr vec_r = rvec[r];
result[c] += mat_cr * vec_r;
}
if(HDebug.IsDebuggerAttached)
{
MatrixByArr tlmat = ToArray(lmat);
MatrixByArr trvec = ToArray(rvec);
MatrixByArr tmat = tlmat * trvec;
HDebug.AssertTolerance(0.00000001, ToArray(result)-tmat);
}
return result;
}
public static VectorSparse<MatrixByArr> Mul(VectorSparse<MatrixByArr> lvec, MatrixByArr rval)
{
VectorSparse<MatrixByArr> mul = new VectorSparse<MatrixByArr>(lvec.Size, lvec.GetDefault);
foreach(var i_val in lvec.EnumElements())
{
int i = i_val.Item1;
MatrixByArr val = i_val.Item2;
mul[i] = val*rval;
}
if(HDebug.IsDebuggerAttached)
{
MatrixByArr tlvec = ToArray(lvec);
MatrixByArr tmat = tlvec * rval;
HDebug.AssertTolerance(0.00000001, ToArray(mul)-tmat);
}
return mul;
}
public static VectorSparse<MatrixByArr> Mul(MatrixByArr lval, VectorSparse<MatrixByArr> rvec)
{
VectorSparse<MatrixByArr> mul = new VectorSparse<MatrixByArr>(rvec.Size, rvec.GetDefault);
foreach(var i_val in rvec.EnumElements())
{
int i = i_val.Item1;
MatrixByArr val = i_val.Item2;
mul[i] = val*lval;
}
if(HDebug.IsDebuggerAttached)
{
MatrixByArr trvec = ToArray(rvec);
MatrixByArr tmat = lval * trvec;
HDebug.AssertTolerance(0.00000001, ToArray(mul)-tmat);
}
return mul;
}
public static VectorSparse<MatrixByArr> Sum(double s1, VectorSparse<MatrixByArr> m1, double s2, VectorSparse<MatrixByArr> m2)
{
return Sum(new Tuple<double, VectorSparse<MatrixByArr>>[]{
new Tuple<double,VectorSparse<MatrixByArr>>(s1, m1),
new Tuple<double,VectorSparse<MatrixByArr>>(s2, m2),
});
}
public static VectorSparse<MatrixByArr> Sum(double s1, VectorSparse<MatrixByArr> m1, double s2, VectorSparse<MatrixByArr> m2, double s3, VectorSparse<MatrixByArr> m3)
{
return Sum(new Tuple<double, VectorSparse<MatrixByArr>>[]{
new Tuple<double,VectorSparse<MatrixByArr>>(s1, m1),
new Tuple<double,VectorSparse<MatrixByArr>>(s2, m2),
new Tuple<double,VectorSparse<MatrixByArr>>(s3, m3),
});
}
public static VectorSparse<MatrixByArr> Sum(params Tuple<double, VectorSparse<MatrixByArr>>[] lst_mat_scale)
{
int size = lst_mat_scale[0].Item2.Size;
var GetDefault = lst_mat_scale[0].Item2.GetDefault;
VectorSparse<MatrixByArr> sum = new VectorSparse<MatrixByArr>(size, GetDefault);
foreach(var mat_scale in lst_mat_scale)
{
HDebug.Assert(size == mat_scale.Item2.Size);
double scale = mat_scale.Item1;
foreach(var i_val in mat_scale.Item2.EnumElements())
{
int i = i_val.Item1;
var val = i_val.Item2;
sum[i] += val * scale;
}
}
return sum;
}
public static MatrixSparse<MatrixByArr> Sum(double s1, MatrixSparse<MatrixByArr> m1, double s2, MatrixSparse<MatrixByArr> m2)
{
return Sum(new Tuple<double, MatrixSparse<MatrixByArr>>[]{
new Tuple<double,MatrixSparse<MatrixByArr>>(s1, m1),
new Tuple<double,MatrixSparse<MatrixByArr>>(s2, m2),
});
}
public static MatrixSparse<MatrixByArr> Sum(double s1, MatrixSparse<MatrixByArr> m1, double s2, MatrixSparse<MatrixByArr> m2, double s3, MatrixSparse<MatrixByArr> m3)
{
return Sum(new Tuple<double,MatrixSparse<MatrixByArr>>[]{
new Tuple<double,MatrixSparse<MatrixByArr>>(s1, m1),
new Tuple<double,MatrixSparse<MatrixByArr>>(s2, m2),
new Tuple<double,MatrixSparse<MatrixByArr>>(s3, m3),
});
}
public static MatrixSparse<MatrixByArr> Sum(params Tuple<double,MatrixSparse<MatrixByArr>>[] lst_mat_scale)
{
int colsize = lst_mat_scale[0].Item2.ColSize;
int rowsize = lst_mat_scale[0].Item2.RowSize;
var GetDefault = lst_mat_scale[0].Item2.GetDefault;
MatrixSparse<MatrixByArr> sum = new MatrixSparse<MatrixByArr>(colsize, rowsize, GetDefault);
foreach(var mat_scale in lst_mat_scale)
{
HDebug.Assert(colsize == mat_scale.Item2.ColSize);
HDebug.Assert(rowsize == mat_scale.Item2.RowSize);
double scale = mat_scale.Item1;
foreach(var c_r_val in mat_scale.Item2.EnumElements())
{
int c = c_r_val.Item1;
int r = c_r_val.Item2;
var val = c_r_val.Item3;
sum[c, r] += val * scale;
}
}
return sum;
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
// David Stephensen (mailto:David.Stephensen@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.DocumentObjectModel.Fields;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.DocumentObjectModel.IO;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// Represents the format of a text.
/// </summary>
public class FormattedText : DocumentObject, IVisitable
{
/// <summary>
/// Initializes a new instance of the FormattedText class.
/// </summary>
public FormattedText()
{
}
/// <summary>
/// Initializes a new instance of the FormattedText class with the specified parent.
/// </summary>
internal FormattedText(DocumentObject parent) : base(parent) { }
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new FormattedText Clone()
{
return (FormattedText)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
FormattedText formattedText = (FormattedText)base.DeepCopy();
if (formattedText.font != null)
{
formattedText.font = formattedText.font.Clone();
formattedText.font.parent = formattedText;
}
if (formattedText.elements != null)
{
formattedText.elements = formattedText.elements.Clone();
formattedText.elements.parent = formattedText;
}
return formattedText;
}
/// <summary>
/// Adds a new Bookmark.
/// </summary>
public BookmarkField AddBookmark(string name)
{
return this.Elements.AddBookmark(name);
}
/// <summary>
/// Adds a single character repeated the specified number of times to the formatted text.
/// </summary>
public Text AddChar(char ch, int count)
{
return this.Elements.AddChar(ch, count);
}
/// <summary>
/// Adds a single character to the formatted text.
/// </summary>
public Text AddChar(char ch)
{
return this.Elements.AddChar(ch);
}
/// <summary>
/// Adds a new PageField.
/// </summary>
public PageField AddPageField()
{
return this.Elements.AddPageField();
}
/// <summary>
/// Adds a new PageRefField.
/// </summary>
public PageRefField AddPageRefField(string name)
{
return this.Elements.AddPageRefField(name);
}
/// <summary>
/// Adds a new NumPagesField.
/// </summary>
public NumPagesField AddNumPagesField()
{
return this.Elements.AddNumPagesField();
}
/// <summary>
/// Adds a new SectionField.
/// </summary>
public SectionField AddSectionField()
{
return this.Elements.AddSectionField();
}
/// <summary>
/// Adds a new SectionPagesField.
/// </summary>
public SectionPagesField AddSectionPagesField()
{
return this.Elements.AddSectionPagesField();
}
/// <summary>
/// Adds a new DateField.
/// </summary>
public DateField AddDateField()
{
return this.Elements.AddDateField();
}
/// <summary>
/// Adds a new DateField.
/// </summary>
public DateField AddDateField(string format)
{
return this.Elements.AddDateField(format);
}
/// <summary>
/// Adds a new InfoField.
/// </summary>
public InfoField AddInfoField(InfoFieldType iType)
{
return this.Elements.AddInfoField(iType);
}
/// <summary>
/// Adds a new Footnote with the specified text.
/// </summary>
public Footnote AddFootnote(string text)
{
return this.Elements.AddFootnote(text);
}
/// <summary>
/// Adds a new Footnote.
/// </summary>
public Footnote AddFootnote()
{
return this.Elements.AddFootnote();
}
/// <summary>
/// Adds a text phrase to the formatted text.
/// </summary>
/// <param name="text">Content of the new text object.</param>
/// <returns>Returns a new Text object.</returns>
public Text AddText(string text)
{
return this.Elements.AddText(text);
}
/// <summary>
/// Adds a new FormattedText.
/// </summary>
public FormattedText AddFormattedText()
{
return this.Elements.AddFormattedText();
}
/// <summary>
/// Adds a new FormattedText object with the given format.
/// </summary>
public FormattedText AddFormattedText(TextFormat textFormat)
{
return this.Elements.AddFormattedText(textFormat);
}
/// <summary>
/// Adds a new FormattedText with the given Font.
/// </summary>
public FormattedText AddFormattedText(Font font)
{
return this.Elements.AddFormattedText(font);
}
/// <summary>
/// Adds a new FormattedText with the given text.
/// </summary>
public FormattedText AddFormattedText(string text)
{
return this.Elements.AddFormattedText(text);
}
/// <summary>
/// Adds a new FormattedText object with the given text and format.
/// </summary>
public FormattedText AddFormattedText(string text, TextFormat textFormat)
{
return this.Elements.AddFormattedText(text, textFormat);
}
/// <summary>
/// Adds a new FormattedText object with the given text and font.
/// </summary>
public FormattedText AddFormattedText(string text, Font font)
{
return this.Elements.AddFormattedText(text, font);
}
/// <summary>
/// Adds a new FormattedText object with the given text and style.
/// </summary>
public FormattedText AddFormattedText(string text, string style)
{
return this.Elements.AddFormattedText(text, style);
}
/// <summary>
/// Adds a new Hyperlink of Type "Local",
/// i.e. the target is a Bookmark within the Document
/// </summary>
public Hyperlink AddHyperlink(string name)
{
return this.Elements.AddHyperlink(name);
}
/// <summary>
/// Adds a new Hyperlink
/// </summary>
public Hyperlink AddHyperlink(string name, HyperlinkType type)
{
return this.Elements.AddHyperlink(name, type);
}
/// <summary>
/// Adds a new Image object
/// </summary>
public Image AddImage(string fileName)
{
return this.Elements.AddImage(fileName);
}
/// <summary>
/// Adds a new Image to the paragraph from a MemoryStream.
/// </summary>
/// <returns></returns>
public Image AddImage(MemoryStream stream)
{
return this.Elements.AddImage(stream);
}
/// <summary>
/// Adds a Symbol object.
/// </summary>
public Character AddCharacter(SymbolName symbolType)
{
return this.Elements.AddCharacter(symbolType);
}
/// <summary>
/// Adds one or more Symbol objects.
/// </summary>
public Character AddCharacter(SymbolName symbolType, int count)
{
return this.Elements.AddCharacter(symbolType, count);
}
/// <summary>
/// Adds a Symbol object defined by a character.
/// </summary>
public Character AddCharacter(char ch)
{
return this.Elements.AddCharacter(ch);
}
/// <summary>
/// Adds one or more Symbol objects defined by a character.
/// </summary>
public Character AddCharacter(char ch, int count)
{
return this.Elements.AddCharacter(ch, count);
}
/// <summary>
/// Adds one or more Symbol objects defined by a character.
/// </summary>
public Character AddSpace(int count)
{
return this.Elements.AddSpace(count);
}
/// <summary>
/// Adds a horizontal tab.
/// </summary>
public void AddTab()
{
this.Elements.AddTab();
}
/// <summary>
/// Adds a line break.
/// </summary>
public void AddLineBreak()
{
this.Elements.AddLineBreak();
}
/// <summary>
/// Adds a new Bookmark
/// </summary>
public void Add(BookmarkField bookmark)
{
this.Elements.Add(bookmark);
}
/// <summary>
/// Adds a new PageField
/// </summary>
public void Add(PageField pageField)
{
this.Elements.Add(pageField);
}
/// <summary>
/// Adds a new PageRefField
/// </summary>
public void Add(PageRefField pageRefField)
{
this.Elements.Add(pageRefField);
}
/// <summary>
/// Adds a new NumPagesField
/// </summary>
public void Add(NumPagesField numPagesField)
{
this.Elements.Add(numPagesField);
}
/// <summary>
/// Adds a new SectionField
/// </summary>
public void Add(SectionField sectionField)
{
this.Elements.Add(sectionField);
}
/// <summary>
/// Adds a new SectionPagesField
/// </summary>
public void Add(SectionPagesField sectionPagesField)
{
this.Elements.Add(sectionPagesField);
}
/// <summary>
/// Adds a new DateField
/// </summary>
public void Add(DateField dateField)
{
this.Elements.Add(dateField);
}
/// <summary>
/// Adds a new InfoField
/// </summary>
public void Add(InfoField infoField)
{
this.Elements.Add(infoField);
}
/// <summary>
/// Adds a new Footnote
/// </summary>
public void Add(Footnote footnote)
{
this.Elements.Add(footnote);
}
/// <summary>
/// Adds a new Text
/// </summary>
public void Add(Text text)
{
this.Elements.Add(text);
}
/// <summary>
/// Adds a new FormattedText
/// </summary>
public void Add(FormattedText formattedText)
{
this.Elements.Add(formattedText);
}
/// <summary>
/// Adds a new Hyperlink
/// </summary>
public void Add(Hyperlink hyperlink)
{
this.Elements.Add(hyperlink);
}
/// <summary>
/// Adds a new Image
/// </summary>
public void Add(Image image)
{
this.Elements.Add(image);
}
/// <summary>
/// Adds a new Character
/// </summary>
public void Add(Character character)
{
this.Elements.Add(character);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the font object.
/// </summary>
public Font Font
{
get
{
if (this.font == null)
this.font = new Font(this);
return this.font;
}
set
{
SetParent(value);
this.font = value;
}
}
[DV]
internal Font font;
/// <summary>
/// Gets or sets the style name.
/// </summary>
public string Style
{
get { return this.style.Value; }
set { this.style.Value = value; }
}
[DV]
internal NString style = NString.NullValue;
/// <summary>
/// Gets or sets the name of the font.
/// </summary>
[DV]
public string FontName
{
get { return Font.Name; }
set { Font.Name = value; }
}
/// <summary>
/// Gets or sets the name of the font.
/// For internal use only.
/// </summary>
[DV]
internal string Name
{
get { return Font.Name; }
set { Font.Name = value; }
}
/// <summary>
/// Gets or sets the size in point.
/// </summary>
[DV]
public Unit Size
{
get { return Font.Size; }
set { Font.Size = value; }
}
/// <summary>
/// Gets or sets the bold property.
/// </summary>
[DV]
public bool Bold
{
get { return Font.Bold; }
set { Font.Bold = value; }
}
/// <summary>
/// Gets or sets the italic property.
/// </summary>
[DV]
public bool Italic
{
get { return Font.Italic; }
set { Font.Italic = value; }
}
/// <summary>
/// Gets or sets the underline property.
/// </summary>
[DV]
public Underline Underline
{
get { return Font.Underline; }
set { Font.Underline = value; }
}
/// <summary>
/// Gets or sets the color property.
/// </summary>
[DV]
public Color Color
{
get { return Font.Color; }
set { Font.Color = value; }
}
/// <summary>
/// Gets or sets the superscript property.
/// </summary>
[DV]
public bool Superscript
{
get { return Font.Superscript; }
set { Font.Superscript = value; }
}
/// <summary>
/// Gets or sets the subscript property.
/// </summary>
[DV]
public bool Subscript
{
get { return Font.Subscript; }
set { Font.Subscript = value; }
}
/// <summary>
/// Gets the collection of paragraph elements that defines the FormattedText.
/// </summary>
public ParagraphElements Elements
{
get
{
if (this.elements == null)
this.elements = new ParagraphElements(this);
return this.elements;
}
set
{
SetParent(value);
this.elements = value;
}
}
[DV(ItemType = typeof(DocumentObject))]
internal ParagraphElements elements;
#endregion
#region Internal
/// <summary>
/// Converts FormattedText into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
bool isFormatted = false;
if (!this.IsNull("Font"))
{
this.Font.Serialize(serializer);
isFormatted = true;
}
else
{
if (!this.style.IsNull)
{
serializer.Write("\\font(\"" + this.Style + "\")");
isFormatted = true;
}
}
if (isFormatted)
serializer.Write("{");
if (!this.IsNull("Elements"))
this.Elements.Serialize(serializer);
if (isFormatted)
serializer.Write("}");
}
/// <summary>
/// Allows the visitor object to visit the document object and it's child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitFormattedText(this);
if (visitChildren && this.elements != null)
((IVisitable)this.elements).AcceptVisitor(visitor, visitChildren);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(FormattedText));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
//#define ASTARDEBUG //Some debugging
//#define ASTAR_NO_JSON
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
using Pathfinding;
namespace Pathfinding {
public interface INavmesh {
//TriangleMeshNode[] TriNodes {get;}
void GetNodes(GraphNodeDelegateCancelable del);
//Int3[] originalVertices {
// get;
// set;
//}
}
[System.Serializable]
[JsonOptIn]
/** Generates graphs based on navmeshes.
\ingroup graphs
Navmeshes are meshes where each polygon define a walkable area.
These are great because the AI can get so much more information on how it can walk.
Polygons instead of points mean that the funnel smoother can produce really nice looking paths and the graphs are also really fast to search
and have a low memory footprint because of their smaller size to describe the same area (compared to grid graphs).
\see Pathfinding.RecastGraph
\shadowimage{navmeshgraph_graph.png}
\shadowimage{navmeshgraph_inspector.png}
*/
public class NavMeshGraph : NavGraph, INavmesh, IUpdatableGraph, IFunnelGraph, INavmeshHolder
,IRaycastableGraph
{
public override void CreateNodes (int number) {
TriangleMeshNode[] tmp = new TriangleMeshNode[number];
for (int i=0;i<number;i++) {
tmp[i] = new TriangleMeshNode (active);
tmp[i].Penalty = initialPenalty;
}
}
[JsonMember]
public Mesh sourceMesh; /**< Mesh to construct navmesh from */
[JsonMember]
public Vector3 offset; /**< Offset in world space */
[JsonMember]
public Vector3 rotation; /**< Rotation in degrees */
[JsonMember]
public float scale = 1; /**< Scale of the graph */
[JsonMember]
/** More accurate nearest node queries.
* When on, looks for the closest point on every triangle instead of if point is inside the node triangle in XZ space.
* This is slower, but a lot better if your mesh contains overlaps (e.g bridges over other areas of the mesh).
* Note that for maximum effect the Full Get Nearest Node Search setting should be toggled in A* Inspector Settings.
*/
public bool accurateNearestNode = true;
public TriangleMeshNode[] nodes;
public TriangleMeshNode[] TriNodes {
get { return nodes; }
}
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i=0;i<nodes.Length && del (nodes[i]);i++) {}
}
public override void OnDestroy () {
base.OnDestroy ();
// Cleanup
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this), null);
}
public Int3 GetVertex (int index) {
return vertices[index];
}
public int GetVertexArrayIndex (int index) {
return index;
}
public void GetTileCoordinates (int tileIndex, out int x, out int z) {
//Tiles not supported
x = z = 0;
}
/** Bounding Box Tree. Enables really fast lookups of nodes. \astarpro */
BBTree _bbTree;
public BBTree bbTree {
get { return _bbTree; }
set { _bbTree = value;}
}
[System.NonSerialized]
Int3[] _vertices;
public Int3[] vertices {
get {
return _vertices;
}
set {
_vertices = value;
}
}
[System.NonSerialized]
Vector3[] originalVertices;
/*public Int3[] originalVertices {
get { return _originalVertices; }
set { _originalVertices = value; }
}*/
[System.NonSerialized]
public int[] triangles;
public void GenerateMatrix () {
#if !PhotonImplementation
SetMatrix (Matrix4x4.TRS (offset,Quaternion.Euler (rotation),new Vector3 (scale,scale,scale)));
#else
SetMatrix (Matrix4x4.TRS (offset,rotation,new Vector3 (scale,scale,scale)));
#endif
}
/** Relocates the nodes to match the newMatrix.
* The "oldMatrix" variable can be left out in this function call (only for this graph generator) since it is not used */
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
//base.RelocateNodes (oldMatrix,newMatrix);
if (vertices == null || vertices.Length == 0 || originalVertices == null || originalVertices.Length != vertices.Length) {
return;
}
for (int i=0;i<_vertices.Length;i++) {
//Vector3 tmp = inv.MultiplyPoint3x4 (vertices[i]);
//vertices[i] = (Int3)newMatrix.MultiplyPoint3x4 (tmp);
_vertices[i] = (Int3)newMatrix.MultiplyPoint3x4 ((Vector3)originalVertices[i]);
}
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = (TriangleMeshNode)nodes[i];
node.UpdatePositionFromVertices();
if (node.connections != null) {
for (int q=0;q<node.connections.Length;q++) {
node.connectionCosts[q] = (uint)(node.position-node.connections[q].position).costMagnitude;
}
}
}
SetMatrix (newMatrix);
// Make a new BBTree
bbTree = new BBTree(this);
for (int i=0;i<nodes.Length;i++) {
bbTree.Insert (nodes[i]);
}
}
public static NNInfo GetNearest (NavMeshGraph graph, GraphNode[] nodes, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
if (nodes == null || nodes.Length == 0) {
Debug.LogError ("NavGraph hasn't been generated yet or does not contain any nodes");
return new NNInfo ();
}
if (constraint == null) constraint = NNConstraint.None;
Int3[] vertices = graph.vertices;
//Query BBTree
if (graph.bbTree == null) {
/** \todo Change method to require a navgraph */
return GetNearestForce (graph as NavGraph, graph as INavmeshHolder, position, constraint, accurateNearestNode);
//Debug.LogError ("No Bounding Box Tree has been assigned");
//return new NNInfo ();
}
//Searches in radiuses of 0.05 - 0.2 - 0.45 ... 1.28 times the average of the width and depth of the bbTree
float w = (graph.bbTree.Size.width + graph.bbTree.Size.height)*0.5F*0.02F;
NNInfo query = graph.bbTree.QueryCircle (position,w,constraint);//graph.bbTree.Query (position,constraint);
if (query.node == null) {
for (int i=1;i<=8;i++) {
query = graph.bbTree.QueryCircle (position, i*i*w, constraint);
if (query.node != null || (i-1)*(i-1)*w > AstarPath.active.maxNearestNodeDistance*2) { // *2 for a margin
break;
}
}
}
if (query.node != null) {
query.clampedPosition = ClosestPointOnNode (query.node as TriangleMeshNode,vertices,position);
}
if (query.constrainedNode != null) {
if (constraint.constrainDistance && ((Vector3)query.constrainedNode.position - position).sqrMagnitude > AstarPath.active.maxNearestNodeDistanceSqr) {
query.constrainedNode = null;
} else {
query.constClampedPosition = ClosestPointOnNode (query.constrainedNode as TriangleMeshNode, vertices, position);
}
}
return query;
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearest (this, nodes,position, constraint, accurateNearestNode);
}
/** This performs a linear search through all polygons returning the closest one.
* This is usually only called in the Free version of the A* Pathfinding Project since the Pro one supports BBTrees and will do another query
*/
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearestForce (this, this,position,constraint, accurateNearestNode);
//Debug.LogWarning ("This function shouldn't be called since constrained nodes are sent back in the GetNearest call");
//return new NNInfo ();
}
/** This performs a linear search through all polygons returning the closest one */
public static NNInfo GetNearestForce (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
NNInfo nn = GetNearestForceBoth (graph, navmesh,position,constraint,accurateNearestNode);
nn.node = nn.constrainedNode;
nn.clampedPosition = nn.constClampedPosition;
return nn;
}
/** This performs a linear search through all polygons returning the closest one.
* This will fill the NNInfo with .node for the closest node not necessarily complying with the NNConstraint, and .constrainedNode with the closest node
* complying with the NNConstraint.
* \see GetNearestForce(Node[],Int3[],Vector3,NNConstraint,bool)
*/
public static NNInfo GetNearestForceBoth (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
Int3 pos = (Int3)position;
float minDist = -1;
GraphNode minNode = null;
float minConstDist = -1;
GraphNode minConstNode = null;
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
GraphNodeDelegateCancelable del = delegate (GraphNode _node) {
TriangleMeshNode node = _node as TriangleMeshNode;
if (accurateNearestNode) {
Vector3 closest = node.ClosestPointOnNode (position);
float dist = ((Vector3)pos-closest).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
if (!node.ContainsPoint ((Int3)position)) {
float dist = (node.position-pos).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
#if ASTARDEBUG
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.blue);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.blue);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.blue);
#endif
int dist = AstarMath.Abs (node.position.y-pos.y);
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
}
}
return true;
};
graph.GetNodes (del);
NNInfo nninfo = new NNInfo (minNode);
//Find the point closest to the nearest triangle
if (nninfo.node != null) {
TriangleMeshNode node = nninfo.node as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.clampedPosition = clP;
}
nninfo.constrainedNode = minConstNode;
if (nninfo.constrainedNode != null) {
TriangleMeshNode node = nninfo.constrainedNode as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.constClampedPosition = clP;
}
return nninfo;
}
public void BuildFunnelCorridor (List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
BuildFunnelCorridor (this,path,startIndex,endIndex,left,right);
}
public static void BuildFunnelCorridor (INavmesh graph, List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
if (graph == null) {
Debug.LogError ("Couldn't cast graph to the appropriate type (graph isn't a Navmesh type graph, it doesn't implement the INavmesh interface)");
return;
}
for (int i=startIndex;i<endIndex;i++) {
//Find the connection between the nodes
TriangleMeshNode n1 = path[i] as TriangleMeshNode;
TriangleMeshNode n2 = path[i+1] as TriangleMeshNode;
int a;
bool search = true;
for (a=0;a<3;a++) {
for (int b=0;b<3;b++) {
if (n1.GetVertexIndex(a) == n2.GetVertexIndex((b+1)%3) && n1.GetVertexIndex((a+1)%3) == n2.GetVertexIndex(b)) {
search = false;
break;
}
}
if (!search) break;
}
if (a == 3) {
left.Add ((Vector3)n1.position);
right.Add ((Vector3)n1.position);
left.Add ((Vector3)n2.position);
right.Add ((Vector3)n2.position);
} else {
left.Add ((Vector3)n1.GetVertex(a));
right.Add ((Vector3)n1.GetVertex((a+1)%3));
}
}
}
public void AddPortal (GraphNode n1, GraphNode n2, List<Vector3> left, List<Vector3> right) {
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public bool Linecast (Vector3 origin, Vector3 end) {
return Linecast (origin, end, GetNearest (origin, NNConstraint.None).node);
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* \param [in] origin Point to linecast from
* \param [in] end Point to linecast to
* \param [out] hit Contains info on what was hit, see GraphHitInfo
* \param [in] hint You need to pass the node closest to the start point
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit) {
return Linecast (this as INavmesh, origin,end,hint, out hit, null);
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* \param [in] origin Point to linecast from
* \param [in] end Point to linecast to
* \param [in] hint You need to pass the node closest to the start point
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint) {
GraphHitInfo hit;
return Linecast (this as INavmesh, origin,end,hint, out hit, null);
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* \param [in] origin Point to linecast from
* \param [in] end Point to linecast to
* \param [out] hit Contains info on what was hit, see GraphHitInfo
* \param [in] hint You need to pass the node closest to the start point
* \param trace If a list is passed, then it will be filled with all nodes the linecast traverses
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace) {
return Linecast (this as INavmesh, origin,end,hint, out hit, trace);
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* \param [in] graph The graph to perform the search on
* \param [in] tmp_origin Point to start from
* \param [in] tmp_end Point to linecast to
* \param [out] hit Contains info on what was hit, see GraphHitInfo
* \param [in] hint You need to pass the node closest to the start point, if null, a search for the closest node will be done
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public static bool Linecast (INavmesh graph, Vector3 tmp_origin, Vector3 tmp_end, GraphNode hint, out GraphHitInfo hit) {
return Linecast (graph, tmp_origin, tmp_end, hint, out hit, null);
}
/** Returns if there is an obstacle between \a origin and \a end on the graph.
* \param [in] graph The graph to perform the search on
* \param [in] tmp_origin Point to start from
* \param [in] tmp_end Point to linecast to
* \param [out] hit Contains info on what was hit, see GraphHitInfo
* \param [in] hint You need to pass the node closest to the start point, if null, a search for the closest node will be done
* \param trace If a list is passed, then it will be filled with all nodes the linecast traverses
* This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
* \astarpro */
public static bool Linecast (INavmesh graph, Vector3 tmp_origin, Vector3 tmp_end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace) {
Int3 end = (Int3)tmp_end;
Int3 origin = (Int3)tmp_origin;
hit = new GraphHitInfo ();
if (float.IsNaN (tmp_origin.x + tmp_origin.y + tmp_origin.z)) throw new System.ArgumentException ("origin is NaN");
if (float.IsNaN (tmp_end.x + tmp_end.y + tmp_end.z)) throw new System.ArgumentException ("end is NaN");
TriangleMeshNode node = hint as TriangleMeshNode;
if (node == null) {
node = (graph as NavGraph).GetNearest (tmp_origin, NNConstraint.None).node as TriangleMeshNode;
if (node == null) {
Debug.LogError ("Could not find a valid node to start from");
hit.point = tmp_origin;
return true;
}
}
if (origin == end) {
hit.node = node;
return false;
}
origin = (Int3)node.ClosestPointOnNode ((Vector3)origin);
hit.origin = (Vector3)origin;
if (!node.Walkable) {
hit.point = (Vector3)origin;
hit.tangentOrigin = (Vector3)origin;
return true;
}
List<Vector3> left = Pathfinding.Util.ListPool<Vector3>.Claim();//new List<Vector3>(1);
List<Vector3> right = Pathfinding.Util.ListPool<Vector3>.Claim();//new List<Vector3>(1);
while (true) {
TriangleMeshNode newNode = null;
if (trace != null) trace.Add (node);
if (node.ContainsPoint (end)) {
Pathfinding.Util.ListPool<Vector3>.Release(left);
Pathfinding.Util.ListPool<Vector3>.Release(right);
return false;
}
for (int i=0;i<node.connections.Length;i++) {
//Nodes on other graphs should not be considered
//They might even be of other types (not MeshNode)
if (node.connections[i].GraphIndex != node.GraphIndex) continue;
left.Clear();
right.Clear();
if (!node.GetPortal (node.connections[i],left,right,false)) continue;
Vector3 a = left[0];
Vector3 b = right[0];
//i.e Right or colinear
if (!Polygon.LeftNotColinear (a,b,hit.origin)) {
if (Polygon.LeftNotColinear (a, b, tmp_end)) {
//Since polygons are laid out in clockwise order, the ray would intersect (if intersecting) this edge going in to the node, not going out from it
continue;
}
}
float factor1, factor2;
if (Polygon.IntersectionFactor (a,b,hit.origin,tmp_end, out factor1, out factor2)) {
//Intersection behind the start
if (factor2 < 0) continue;
if (factor1 >= 0 && factor1 <= 1) {
newNode = node.connections[i] as TriangleMeshNode;
break;
}
}
}
if (newNode == null) {
//Possible edge hit
int vs = node.GetVertexCount();
for (int i=0;i<vs;i++) {
Vector3 a = (Vector3)node.GetVertex(i);
Vector3 b = (Vector3)node.GetVertex((i + 1) % vs);
//i.e right or colinear
if (!Polygon.LeftNotColinear (a,b,hit.origin)) {
//Since polygons are laid out in clockwise order, the ray would intersect (if intersecting) this edge going in to the node, not going out from it
if (Polygon.LeftNotColinear (a, b, tmp_end)) {
//Since polygons are laid out in clockwise order, the ray would intersect (if intersecting) this edge going in to the node, not going out from it
continue;
}
}
float factor1, factor2;
if (Polygon.IntersectionFactor (a,b,hit.origin,tmp_end, out factor1, out factor2)) {
if (factor2 < 0) continue;
if (factor1 >= 0 && factor1 <= 1) {
Vector3 intersectionPoint = a + (b-a)*factor1;
hit.point = intersectionPoint;
hit.node = node;
hit.tangent = b-a;
hit.tangentOrigin = a;
Pathfinding.Util.ListPool<Vector3>.Release(left);
Pathfinding.Util.ListPool<Vector3>.Release(right);
return true;
}
}
}
//Ok, this is wrong...
Debug.LogWarning ("Linecast failing because point not inside node, and line does not hit any edges of it");
Pathfinding.Util.ListPool<Vector3>.Release(left);
Pathfinding.Util.ListPool<Vector3>.Release(right);
return false;
}
node = newNode;
}
}
public GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o) {
return GraphUpdateThreading.UnityThread;
}
public void UpdateAreaInit (GraphUpdateObject o) {}
public void UpdateArea (GraphUpdateObject o) {
}
public static void UpdateArea (GraphUpdateObject o, INavmesh graph) {
//System.DateTime startTime = System.DateTime.UtcNow;
Bounds bounds = o.bounds;
Rect r = Rect.MinMaxRect (bounds.min.x,bounds.min.z,bounds.max.x,bounds.max.z);
IntRect r2 = new IntRect(
Mathf.FloorToInt(bounds.min.x*Int3.Precision),
Mathf.FloorToInt(bounds.min.z*Int3.Precision),
Mathf.FloorToInt(bounds.max.x*Int3.Precision),
Mathf.FloorToInt(bounds.max.z*Int3.Precision)
);
/*Vector3 a = new Vector3 (r.xMin,0,r.yMin);// -1 -1
Vector3 b = new Vector3 (r.xMin,0,r.yMax);// -1 1
Vector3 c = new Vector3 (r.xMax,0,r.yMin);// 1 -1
Vector3 d = new Vector3 (r.xMax,0,r.yMax);// 1 1
*/
Int3 a = new Int3(r2.xmin,0,r2.ymin);
Int3 b = new Int3(r2.xmin,0,r2.ymax);
Int3 c = new Int3(r2.xmax,0,r2.ymin);
Int3 d = new Int3(r2.xmax,0,r2.ymax);
Int3 ia = (Int3)a;
Int3 ib = (Int3)b;
Int3 ic = (Int3)c;
Int3 id = (Int3)d;
#if ASTARDEBUG
Debug.DrawLine (a,b,Color.white);
Debug.DrawLine (a,c,Color.white);
Debug.DrawLine (c,d,Color.white);
Debug.DrawLine (d,b,Color.white);
#endif
//for (int i=0;i<nodes.Length;i++) {
graph.GetNodes (delegate (GraphNode _node) {
TriangleMeshNode node = _node as TriangleMeshNode;
bool inside = false;
int allLeft = 0;
int allRight = 0;
int allTop = 0;
int allBottom = 0;
for (int v=0;v<3;v++) {
Int3 p = node.GetVertex(v);
Vector3 vert = (Vector3)p;
//Vector2 vert2D = new Vector2 (vert.x,vert.z);
if (r2.Contains (p.x,p.z)) {
//Debug.DrawRay (vert,Vector3.up*10,Color.yellow);
inside = true;
break;
}
if (vert.x < r.xMin) allLeft++;
if (vert.x > r.xMax) allRight++;
if (vert.z < r.yMin) allTop++;
if (vert.z > r.yMax) allBottom++;
//if (!bounds.Contains (node[v]) {
// inside = false;
// break;
//}
}
if (!inside) {
if (allLeft == 3 || allRight == 3 || allTop == 3 || allBottom == 3) {
return true;
}
}
//Debug.DrawLine ((Vector3)node.GetVertex(0),(Vector3)node.GetVertex(1),Color.yellow);
//Debug.DrawLine ((Vector3)node.GetVertex(1),(Vector3)node.GetVertex(2),Color.yellow);
//Debug.DrawLine ((Vector3)node.GetVertex(2),(Vector3)node.GetVertex(0),Color.yellow);
for (int v=0;v<3;v++) {
int v2 = v > 1 ? 0 : v+1;
Int3 vert1 = node.GetVertex(v);
Int3 vert2 = node.GetVertex(v2);
if (Polygon.Intersects (a,b,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (a,c,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (c,d,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (d,b,vert1,vert2)) { inside = true; break; }
}
if (node.ContainsPoint (ia) || node.ContainsPoint (ib) || node.ContainsPoint (ic) || node.ContainsPoint (id)) {
inside = true;
}
if (!inside) {
return true;
}
o.WillUpdateNode(node);
o.Apply (node);
/*Debug.DrawLine ((Vector3)node.GetVertex(0),(Vector3)node.GetVertex(1),Color.blue);
Debug.DrawLine ((Vector3)node.GetVertex(1),(Vector3)node.GetVertex(2),Color.blue);
Debug.DrawLine ((Vector3)node.GetVertex(2),(Vector3)node.GetVertex(0),Color.blue);
Debug.Break ();*/
return true;
});
//System.DateTime endTime = System.DateTime.UtcNow;
//float theTime = (endTime-startTime).Ticks*0.0001F;
//Debug.Log ("Intersecting bounds with navmesh took "+theTime.ToString ("0.000")+" ms");
}
/** Returns the closest point of the node */
public static Vector3 ClosestPointOnNode (TriangleMeshNode node, Int3[] vertices, Vector3 pos) {
return Polygon.ClosestPointOnTriangle ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],(Vector3)vertices[node.v2],pos);
}
/** Returns if the point is inside the node in XZ space */
public bool ContainsPoint (TriangleMeshNode node, Vector3 pos) {
if ( Polygon.IsClockwise ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Returns if the point is inside the node in XZ space */
public static bool ContainsPoint (TriangleMeshNode node, Vector3 pos, Int3[] vertices) {
if (!Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], (Vector3)vertices[node.v2])) {
Debug.LogError ("Noes!");
}
if ( Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Scans the graph using the path to an .obj mesh */
public void ScanInternal (string objMeshPath) {
Mesh mesh = ObjImporter.ImportFile (objMeshPath);
if (mesh == null) {
Debug.LogError ("Couldn't read .obj file at '"+objMeshPath+"'");
return;
}
sourceMesh = mesh;
ScanInternal ();
}
public override void ScanInternal (OnScanStatus statusCallback) {
if (sourceMesh == null) {
return;
}
GenerateMatrix ();
//float startTime = 0;//Time.realtimeSinceStartup;
Vector3[] vectorVertices = sourceMesh.vertices;
triangles = sourceMesh.triangles;
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this),this);
GenerateNodes (vectorVertices,triangles, out originalVertices, out _vertices);
}
/** Generates a navmesh. Based on the supplied vertices and triangles. Memory usage is about O(n) */
public void GenerateNodes (Vector3[] vectorVertices, int[] triangles, out Vector3[] originalVertices, out Int3[] vertices) {
Profiler.BeginSample ("Init");
if (vectorVertices.Length == 0 || triangles.Length == 0) {
originalVertices = vectorVertices;
vertices = new Int3[0];
//graph.CreateNodes (0);
nodes = new TriangleMeshNode[0];
return;
}
vertices = new Int3[vectorVertices.Length];
//Backup the original vertices
//for (int i=0;i<vectorVertices.Length;i++) {
// vectorVertices[i] = graph.matrix.MultiplyPoint (vectorVertices[i]);
//}
int c = 0;
for (int i=0;i<vertices.Length;i++) {
vertices[i] = (Int3)matrix.MultiplyPoint3x4 (vectorVertices[i]);
}
Dictionary<Int3,int> hashedVerts = new Dictionary<Int3,int> ();
int[] newVertices = new int[vertices.Length];
Profiler.EndSample ();
Profiler.BeginSample ("Hashing");
for (int i=0;i<vertices.Length;i++) {
if (!hashedVerts.ContainsKey (vertices[i])) {
newVertices[c] = i;
hashedVerts.Add (vertices[i], c);
c++;
}// else {
//Debug.Log ("Hash Duplicate "+hash+" "+vertices[i].ToString ());
//}
}
/*newVertices[c] = vertices.Length-1;
if (!hashedVerts.ContainsKey (vertices[newVertices[c]])) {
hashedVerts.Add (vertices[newVertices[c]], c);
c++;
}*/
for (int x=0;x<triangles.Length;x++) {
Int3 vertex = vertices[triangles[x]];
triangles[x] = hashedVerts[vertex];
}
/*for (int i=0;i<triangles.Length;i += 3) {
Vector3 offset = Vector3.forward*i*0.01F;
Debug.DrawLine (newVertices[triangles[i]]+offset,newVertices[triangles[i+1]]+offset,Color.blue);
Debug.DrawLine (newVertices[triangles[i+1]]+offset,newVertices[triangles[i+2]]+offset,Color.blue);
Debug.DrawLine (newVertices[triangles[i+2]]+offset,newVertices[triangles[i]]+offset,Color.blue);
}*/
Int3[] totalIntVertices = vertices;
vertices = new Int3[c];
originalVertices = new Vector3[c];
for (int i=0;i<c;i++) {
vertices[i] = totalIntVertices[newVertices[i]];//(Int3)graph.matrix.MultiplyPoint (vectorVertices[i]);
originalVertices[i] = (Vector3)vectorVertices[newVertices[i]];//vectorVertices[newVertices[i]];
}
Profiler.EndSample ();
Profiler.BeginSample ("Constructing Nodes");
//graph.CreateNodes (triangles.Length/3);//new Node[triangles.Length/3];
nodes = new TriangleMeshNode[triangles.Length/3];
for (int i=0;i<nodes.Length;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];//new MeshNode ();
node.Penalty = initialPenalty;
node.Walkable = true;
node.v0 = triangles[i*3];
node.v1 = triangles[i*3+1];
node.v2 = triangles[i*3+2];
if (!Polygon.IsClockwise (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
//Debug.DrawLine (vertices[node.v0],vertices[node.v1],Color.red);
//Debug.DrawLine (vertices[node.v1],vertices[node.v2],Color.red);
//Debug.DrawLine (vertices[node.v2],vertices[node.v0],Color.red);
int tmp = node.v0;
node.v0 = node.v2;
node.v2 = tmp;
}
if (Polygon.IsColinear (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.red);
}
// Make sure position is correctly set
node.UpdatePositionFromVertices();
}
Profiler.EndSample ();
Dictionary<Int2,TriangleMeshNode> sides = new Dictionary<Int2, TriangleMeshNode>();
for (int i=0, j=0;i<triangles.Length; j+=1, i+=3) {
sides[new Int2(triangles[i+0],triangles[i+1])] = nodes[j];
sides[new Int2(triangles[i+1],triangles[i+2])] = nodes[j];
sides[new Int2(triangles[i+2],triangles[i+0])] = nodes[j];
}
Profiler.BeginSample ("Connecting Nodes");
List<MeshNode> connections = new List<MeshNode> ();
List<uint> connectionCosts = new List<uint> ();
int identicalError = 0;
for (int i=0, j=0;i<triangles.Length; j+=1, i+=3) {
connections.Clear ();
connectionCosts.Clear ();
//Int3 indices = new Int3(triangles[i],triangles[i+1],triangles[i+2]);
TriangleMeshNode node = nodes[j];
for ( int q = 0; q < 3; q++ ) {
TriangleMeshNode other;
if (sides.TryGetValue ( new Int2 (triangles[i+((q+1)%3)], triangles[i+q]), out other ) ) {
connections.Add (other);
connectionCosts.Add ((uint)(node.position-other.position).costMagnitude);
}
}
node.connections = connections.ToArray ();
node.connectionCosts = connectionCosts.ToArray ();
}
if (identicalError > 0) {
Debug.LogError ("One or more triangles are identical to other triangles, this is not a good thing to have in a navmesh\nIncreasing the scale of the mesh might help\nNumber of triangles with error: "+identicalError+"\n");
}
Profiler.EndSample ();
Profiler.BeginSample ("Rebuilding BBTree");
RebuildBBTree (this);
Profiler.EndSample ();
#if ASTARDEBUG
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = nodes[i] as TriangleMeshNode;
float a1 = Polygon.TriangleArea2 ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],(Vector3)vertices[node.v2]);
long a2 = Polygon.TriangleArea2 (vertices[node.v0],vertices[node.v1],vertices[node.v2]);
if (a1 * a2 < 0) Debug.LogError (a1+ " " + a2);
if (Polygon.IsClockwise (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.green);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.green);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.green);
} else {
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.red);
}
}
#endif
//Debug.Log ("Graph Generation - NavMesh - Time to compute graph "+((Time.realtimeSinceStartup-startTime)*1000F).ToString ("0")+"ms");
}
/** Rebuilds the BBTree on a NavGraph.
* \astarpro
* \see NavMeshGraph.bbTree */
public static void RebuildBBTree (NavMeshGraph graph) {
//Build Axis Aligned Bounding Box Tree
NavMeshGraph meshGraph = graph as NavMeshGraph;
BBTree bbTree = meshGraph.bbTree;
if ( bbTree == null ) {
bbTree = new BBTree (graph as INavmeshHolder);
}
bbTree.Clear ();
TriangleMeshNode[] nodes = meshGraph.TriNodes;
for (int i=nodes.Length-1;i>=0;i--) {
bbTree.Insert (nodes[i]);
}
meshGraph.bbTree = bbTree;
}
public void PostProcess () {
#if FALSE
int rnd = Random.Range (0,nodes.Length);
GraphNode nodex = nodes[rnd];
NavGraph gr = null;
if (AstarPath.active.astarData.GetGraphIndex(this) == 0) {
gr = AstarPath.active.graphs[1];
} else {
gr = AstarPath.active.graphs[0];
}
rnd = Random.Range (0,gr.nodes.Length);
List<GraphNode> connections = new List<GraphNode> ();
List<int> connectionCosts = new List<int> ();
connections.AddRange (nodex.connections);
connectionCosts.AddRange (nodex.connectionCosts);
GraphNode otherNode = gr.nodes[rnd];
connections.Add (otherNode);
connectionCosts.Add ((nodex.position-otherNode.position).costMagnitude);
nodex.connections = connections.ToArray ();
nodex.connectionCosts = connectionCosts.ToArray ();
#endif
}
public void Sort (Vector3[] a) {
bool changed = true;
while (changed) {
changed = false;
for (int i=0;i<a.Length-1;i++) {
if (a[i].x > a[i+1].x || (a[i].x == a[i+1].x && (a[i].y > a[i+1].y || (a[i].y == a[i+1].y && a[i].z > a[i+1].z)))) {
Vector3 tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
changed = true;
}
}
}
}
public override void OnDrawGizmos (bool drawNodes) {
if (!drawNodes) {
return;
}
Matrix4x4 preMatrix = matrix;
GenerateMatrix ();
if (nodes == null) {
//Scan ();
}
if (nodes == null) {
return;
}
if ( bbTree != null ) {
bbTree.OnDrawGizmos ();
}
if (preMatrix != matrix) {
//Debug.Log ("Relocating Nodes");
RelocateNodes (preMatrix, matrix);
}
PathHandler debugData = AstarPath.active.debugPathData;
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = (TriangleMeshNode)nodes[i];
Gizmos.color = NodeColor (node,AstarPath.active.debugPathData);
if (node.Walkable ) {
if (AstarPath.active.showSearchTree && debugData != null && debugData.GetPathNode(node).parent != null) {
Gizmos.DrawLine ((Vector3)node.position,(Vector3)debugData.GetPathNode(node).parent.node.position);
} else {
for (int q=0;q<node.connections.Length;q++) {
Gizmos.DrawLine ((Vector3)node.position,Vector3.Lerp ((Vector3)node.position, (Vector3)node.connections[q].position, 0.45f));
}
}
Gizmos.color = AstarColor.MeshEdgeColor;
} else {
Gizmos.color = Color.red;
}
Gizmos.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1]);
Gizmos.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2]);
Gizmos.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0]);
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx)
{
uint graphIndex = (uint)active.astarData.GetGraphIndex(this);
TriangleMeshNode.SetNavmeshHolder ((int)graphIndex,this);
int c1 = ctx.reader.ReadInt32();
int c2 = ctx.reader.ReadInt32();
if (c1 == -1) {
nodes = new TriangleMeshNode[0];
_vertices = new Int3[0];
originalVertices = new Vector3[0];
}
nodes = new TriangleMeshNode[c1];
_vertices = new Int3[c2];
originalVertices = new Vector3[c2];
for (int i=0;i<c2;i++) {
_vertices[i] = new Int3(ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
originalVertices[i] = new Vector3(ctx.reader.ReadSingle(), ctx.reader.ReadSingle(), ctx.reader.ReadSingle());
}
bbTree = new BBTree(this);
for (int i=0;i<c1;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];
node.DeserializeNode(ctx);
node.GraphIndex = graphIndex;
node.UpdatePositionFromVertices();
bbTree.Insert (node);
}
}
public override void SerializeExtraInfo (GraphSerializationContext ctx)
{
if (nodes == null || originalVertices == null || _vertices == null || originalVertices.Length != _vertices.Length) {
ctx.writer.Write (-1);
ctx.writer.Write (-1);
return;
}
ctx.writer.Write(nodes.Length);
ctx.writer.Write(_vertices.Length);
for (int i=0;i<_vertices.Length;i++) {
ctx.writer.Write (_vertices[i].x);
ctx.writer.Write (_vertices[i].y);
ctx.writer.Write (_vertices[i].z);
ctx.writer.Write (originalVertices[i].x);
ctx.writer.Write (originalVertices[i].y);
ctx.writer.Write (originalVertices[i].z);
}
for (int i=0;i<nodes.Length;i++) {
nodes[i].SerializeNode (ctx);
}
}
public static void DeserializeMeshNodes (NavMeshGraph graph, GraphNode[] nodes, byte[] bytes) {
System.IO.MemoryStream mem = new System.IO.MemoryStream(bytes);
System.IO.BinaryReader stream = new System.IO.BinaryReader(mem);
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = nodes[i] as TriangleMeshNode;
if (node == null) {
Debug.LogError ("Serialization Error : Couldn't cast the node to the appropriate type - NavMeshGenerator");
return;
}
node.v0 = stream.ReadInt32 ();
node.v1 = stream.ReadInt32 ();
node.v2 = stream.ReadInt32 ();
}
int numVertices = stream.ReadInt32 ();
graph.vertices = new Int3[numVertices];
for (int i=0;i<numVertices;i++) {
int x = stream.ReadInt32 ();
int y = stream.ReadInt32 ();
int z = stream.ReadInt32 ();
graph.vertices[i] = new Int3 (x,y,z);
}
RebuildBBTree (graph);
}
#if ASTAR_NO_JSON
void SerializeUnityObject ( UnityEngine.Object ob, GraphSerializationContext ctx ) {
if ( ob == null ) {
ctx.writer.Write (int.MaxValue);
return;
}
int inst = ob.GetInstanceID();
string name = ob.name;
string type = ob.GetType().AssemblyQualifiedName;
string guid = "";
//Write scene path if the object is a Component or GameObject
Component component = ob as Component;
GameObject go = ob as GameObject;
if (component != null || go != null) {
if (component != null && go == null) {
go = component.gameObject;
}
UnityReferenceHelper helper = go.GetComponent<UnityReferenceHelper>();
if (helper == null) {
Debug.Log ("Adding UnityReferenceHelper to Unity Reference '"+ob.name+"'");
helper = go.AddComponent<UnityReferenceHelper>();
}
//Make sure it has a unique GUID
helper.Reset ();
guid = helper.GetGUID ();
}
ctx.writer.Write(inst);
ctx.writer.Write(name);
ctx.writer.Write(type);
ctx.writer.Write(guid);
}
UnityEngine.Object DeserializeUnityObject ( GraphSerializationContext ctx ) {
int inst = ctx.reader.ReadInt32();
if ( inst == int.MaxValue ) {
return null;
}
string name = ctx.reader.ReadString();
string typename = ctx.reader.ReadString();
string guid = ctx.reader.ReadString();
System.Type type = System.Type.GetType (typename);
if (type == null) {
Debug.LogError ("Could not find type '"+typename+"'. Cannot deserialize Unity reference");
return null;
}
if (!string.IsNullOrEmpty(guid)) {
UnityReferenceHelper[] helpers = UnityEngine.Object.FindObjectsOfType(typeof(UnityReferenceHelper)) as UnityReferenceHelper[];
for (int i=0;i<helpers.Length;i++) {
if (helpers[i].GetGUID () == guid) {
if (System.Type.Equals ( type, typeof(GameObject) )) {
return helpers[i].gameObject;
} else {
return helpers[i].GetComponent (type);
}
}
}
}
//Try to load from resources
UnityEngine.Object[] objs = Resources.LoadAll (name,type);
for (int i=0;i<objs.Length;i++) {
if (objs[i].name == name || objs.Length == 1) {
return objs[i];
}
}
return null;
}
public override void SerializeSettings ( GraphSerializationContext ctx ) {
base.SerializeSettings (ctx);
SerializeUnityObject ( sourceMesh, ctx );
ctx.writer.Write(offset.x);
ctx.writer.Write(offset.y);
ctx.writer.Write(offset.z);
ctx.writer.Write(rotation.x);
ctx.writer.Write(rotation.y);
ctx.writer.Write(rotation.z);
ctx.writer.Write(scale);
ctx.writer.Write(accurateNearestNode);
}
public override void DeserializeSettings ( GraphSerializationContext ctx ) {
base.DeserializeSettings (ctx);
sourceMesh = DeserializeUnityObject (ctx) as Mesh;
offset = new Vector3 (ctx.reader.ReadSingle(),ctx.reader.ReadSingle(),ctx.reader.ReadSingle());
rotation = new Vector3 (ctx.reader.ReadSingle(),ctx.reader.ReadSingle(),ctx.reader.ReadSingle());
scale = ctx.reader.ReadSingle();
accurateNearestNode = ctx.reader.ReadBoolean();
}
#endif
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Archiver;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
public class InventoryArchiveWriteRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Used to select all inventory nodes in a folder but not the folder itself
/// </value>
private const string STAR_WILDCARD = "*";
private InventoryArchiverModule m_module;
private UserAccount m_userInfo;
private string m_invPath;
protected TarArchiveWriter m_archiveWriter;
protected UuidGatherer m_assetGatherer;
/// <value>
/// We only use this to request modules
/// </value>
protected Scene m_scene;
/// <value>
/// ID of this request
/// </value>
protected Guid m_id;
/// <value>
/// Used to collect the uuids of the assets that we need to save into the archive
/// </value>
protected Dictionary<UUID, AssetType> m_assetUuids = new Dictionary<UUID, AssetType>();
/// <value>
/// Used to collect the uuids of the users that we need to save into the archive
/// </value>
protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>();
/// <value>
/// The stream to which the inventory archive will be saved.
/// </value>
private Stream m_saveStream;
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
Guid id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, string savePath)
: this(
id,
module,
scene,
userInfo,
invPath,
new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress))
{
}
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
Guid id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, Stream saveStream)
{
m_id = id;
m_module = module;
m_scene = scene;
m_userInfo = userInfo;
m_invPath = invPath;
m_saveStream = saveStream;
m_assetGatherer = new UuidGatherer(m_scene.AssetService);
}
protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids)
{
Exception reportedException = null;
bool succeeded = true;
try
{
m_archiveWriter.Close();
}
catch (Exception e)
{
reportedException = e;
succeeded = false;
}
finally
{
m_saveStream.Close();
}
m_module.TriggerInventoryArchiveSaved(
m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException);
}
protected void SaveInvItem(InventoryItemBase inventoryItem, string path, Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("verbose"))
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving item {0} with asset {1}", inventoryItem.ID, inventoryItem.AssetID);
string filename = path + CreateArchiveItemName(inventoryItem);
// Record the creator of this item for user record purposes (which might go away soon)
m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;
string serialization = UserInventoryItemSerializer.Serialize(inventoryItem, options, userAccountService);
m_archiveWriter.WriteFile(filename, serialization);
m_assetGatherer.GatherAssetUuids(inventoryItem.AssetID, (AssetType)inventoryItem.AssetType, m_assetUuids);
}
/// <summary>
/// Save an inventory folder
/// </summary>
/// <param name="inventoryFolder">The inventory folder to save</param>
/// <param name="path">The path to which the folder should be saved</param>
/// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param>
/// <param name="options"></param>
/// <param name="userAccountService"></param>
protected void SaveInvFolder(
InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself,
Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("verbose"))
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving folder {0}", inventoryFolder.Name);
if (saveThisFolderItself)
{
path += CreateArchiveFolderName(inventoryFolder);
// We need to make sure that we record empty folders
m_archiveWriter.WriteDir(path);
}
InventoryCollection contents
= m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID);
foreach (InventoryFolderBase childFolder in contents.Folders)
{
SaveInvFolder(childFolder, path, true, options, userAccountService);
}
foreach (InventoryItemBase item in contents.Items)
{
SaveInvItem(item, path, options, userAccountService);
}
}
/// <summary>
/// Execute the inventory write request
/// </summary>
public void Execute(Dictionary<string, object> options, IUserAccountService userAccountService)
{
try
{
InventoryFolderBase inventoryFolder = null;
InventoryItemBase inventoryItem = null;
InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID);
bool saveFolderContentsOnly = false;
// Eliminate double slashes and any leading / on the path.
string[] components
= m_invPath.Split(
new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
int maxComponentIndex = components.Length - 1;
// If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the
// folder itself. This may get more sophisicated later on
if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD)
{
saveFolderContentsOnly = true;
maxComponentIndex--;
}
m_invPath = String.Empty;
for (int i = 0; i <= maxComponentIndex; i++)
{
m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER;
}
// Annoyingly Split actually returns the original string if the input string consists only of delimiters
// Therefore if we still start with a / after the split, then we need the root folder
if (m_invPath.Length == 0)
{
inventoryFolder = rootFolder;
}
else
{
m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER));
List<InventoryFolderBase> candidateFolders
= InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, rootFolder, m_invPath);
if (candidateFolders.Count > 0)
inventoryFolder = candidateFolders[0];
}
// The path may point to an item instead
if (inventoryFolder == null)
{
inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath);
//inventoryItem = m_userInfo.RootFolder.FindItemByPath(m_invPath);
}
if (null == inventoryFolder && null == inventoryItem)
{
// We couldn't find the path indicated
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
Exception e = new InventoryArchiverException(errorMessage);
m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e);
throw e;
}
m_archiveWriter = new TarArchiveWriter(m_saveStream);
// Write out control file. This has to be done first so that subsequent loaders will see this file first
// XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this
// not sure how to fix this though, short of going with a completely different file format.
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options));
m_log.InfoFormat("[INVENTORY ARCHIVER]: Added control file to archive.");
if (inventoryFolder != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}",
inventoryFolder.Name,
inventoryFolder.ID,
m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath);
//recurse through all dirs getting dirs and files
SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly, options, userAccountService);
}
else if (inventoryItem != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, m_invPath);
SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH, options, userAccountService);
}
// Don't put all this profile information into the archive right now.
//SaveUsers();
new AssetsRequest(
new AssetsArchiver(m_archiveWriter),
m_assetUuids, m_scene.AssetService,
m_scene.UserAccountService, m_scene.RegionInfo.ScopeID,
options, ReceivedAllAssets).Execute();
}
catch (Exception)
{
m_saveStream.Close();
throw;
}
}
/// <summary>
/// Save information for the users that we've collected.
/// </summary>
protected void SaveUsers()
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count);
foreach (UUID creatorId in m_userUuids.Keys)
{
// Record the creator of this item
UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId);
if (creator != null)
{
m_archiveWriter.WriteFile(
ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml",
UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName));
}
else
{
m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId);
}
}
}
/// <summary>
/// Create the archive name for a particular folder.
/// </summary>
///
/// These names are prepended with an inventory folder's UUID so that more than one folder can have the
/// same name
///
/// <param name="folder"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(InventoryFolderBase folder)
{
return CreateArchiveFolderName(folder.Name, folder.ID);
}
/// <summary>
/// Create the archive name for a particular item.
/// </summary>
///
/// These names are prepended with an inventory item's UUID so that more than one item can have the
/// same name
///
/// <param name="item"></param>
/// <returns></returns>
public static string CreateArchiveItemName(InventoryItemBase item)
{
return CreateArchiveItemName(item.Name, item.ID);
}
/// <summary>
/// Create an archive folder name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}/",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create an archive item name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveItemName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}.xml",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create the control file for the archive
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public static string CreateControlFile(Dictionary<string, object> options)
{
int majorVersion, minorVersion;
if (options.ContainsKey("profile"))
{
majorVersion = 1;
minorVersion = 1;
}
else
{
majorVersion = 0;
minorVersion = 2;
}
m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion);
StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("archive");
xtw.WriteAttributeString("major_version", majorVersion.ToString());
xtw.WriteAttributeString("minor_version", minorVersion.ToString());
xtw.WriteEndElement();
xtw.Flush();
xtw.Close();
String s = sw.ToString();
sw.Close();
return s;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Buffers.Text
{
public static partial class Utf8Formatter
{
/// <summary>
/// Formats a TimeSpan as a UTF8 string.
/// </summary>
/// <param name="value">Value to format</param>
/// <param name="destination">Buffer to write the UTF8-formatted value to</param>
/// <param name="bytesWritten">Receives the length of the formatted text in bytes</param>
/// <param name="format">The standard format to use</param>
/// <returns>
/// true for success. "bytesWritten" contains the length of the formatted text in bytes.
/// false if buffer was too short. Iteratively increase the size of the buffer and retry until it succeeds.
/// </returns>
/// <remarks>
/// Formats supported:
/// c/t/T (default) [-][d.]hh:mm:ss[.fffffff] (constant format)
/// G [-]d:hh:mm:ss.fffffff (general long)
/// g [-][d:][h]h:mm:ss[.f[f[f[f[f[f[f]]]]]] (general short)
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryFormat(TimeSpan value, Span<byte> destination, out int bytesWritten, StandardFormat format = default)
{
char symbol = FormattingHelpers.GetSymbolOrDefault(format, 'c');
switch (symbol)
{
case 'c':
case 'G':
case 'g':
break;
case 't':
case 'T':
symbol = 'c';
break;
default:
return ThrowHelper.TryFormatThrowFormatException(out bytesWritten);
}
// First, calculate how large an output buffer is needed to hold the entire output.
int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary
uint fraction;
ulong totalSecondsRemaining;
{
// Turn this into a non-negative TimeSpan if possible.
var ticks = value.Ticks;
if (ticks < 0)
{
ticks = -ticks;
if (ticks < 0)
{
Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */);
// We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue.
fraction = 4775808;
totalSecondsRemaining = 922337203685;
goto AfterComputeFraction;
}
}
totalSecondsRemaining = FormattingHelpers.DivMod((ulong)Math.Abs(value.Ticks), TimeSpan.TicksPerSecond, out ulong fraction64);
fraction = (uint)fraction64;
}
AfterComputeFraction:
int fractionDigits = 0;
if (symbol == 'c')
{
// Only write out the fraction if it's non-zero, and in that
// case write out the entire fraction (all digits).
if (fraction != 0)
{
fractionDigits = Utf8Constants.DateTimeNumFractionDigits;
}
}
else if (symbol == 'G')
{
// Always write out the fraction, even if it's zero.
fractionDigits = Utf8Constants.DateTimeNumFractionDigits;
}
else
{
// Only write out the fraction if it's non-zero, and in that
// case write out only the most significant digits.
if (fraction != 0)
{
fractionDigits = Utf8Constants.DateTimeNumFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction);
}
}
Debug.Assert(fraction < 10_000_000);
// If we're going to write out a fraction, also need to write the leading decimal.
if (fractionDigits != 0)
{
requiredOutputLength += fractionDigits + 1;
}
ulong totalMinutesRemaining = 0;
ulong seconds = 0;
if (totalSecondsRemaining > 0)
{
// Only compute minutes if the TimeSpan has an absolute value of >= 1 minute.
totalMinutesRemaining = FormattingHelpers.DivMod(totalSecondsRemaining, 60 /* seconds per minute */, out seconds);
}
Debug.Assert(seconds < 60);
ulong totalHoursRemaining = 0;
ulong minutes = 0;
if (totalMinutesRemaining > 0)
{
// Only compute hours if the TimeSpan has an absolute value of >= 1 hour.
totalHoursRemaining = FormattingHelpers.DivMod(totalMinutesRemaining, 60 /* minutes per hour */, out minutes);
}
Debug.Assert(minutes < 60);
// At this point, we can switch over to 32-bit divmod since the data has shrunk far enough.
Debug.Assert(totalHoursRemaining <= uint.MaxValue);
uint days = 0;
uint hours = 0;
if (totalHoursRemaining > 0)
{
// Only compute days if the TimeSpan has an absolute value of >= 1 day.
days = FormattingHelpers.DivMod((uint)totalHoursRemaining, 24 /* hours per day */, out hours);
}
Debug.Assert(hours < 24);
int hourDigits = 2;
if (hours < 10 && symbol == 'g')
{
// Only writing a one-digit hour, not a two-digit hour
hourDigits--;
requiredOutputLength--;
}
int dayDigits = 0;
if (days == 0)
{
if (symbol == 'G')
{
requiredOutputLength += 2; // for the leading "0:"
dayDigits = 1;
}
}
else
{
dayDigits = FormattingHelpers.CountDigits(days);
requiredOutputLength += dayDigits + 1; // for the leading "d:" (or "d.")
}
if (value.Ticks < 0)
{
requiredOutputLength++; // for the leading '-' sign
}
if (destination.Length < requiredOutputLength)
{
bytesWritten = 0;
return false;
}
bytesWritten = requiredOutputLength;
int idx = 0;
// Write leading '-' if necessary
if (value.Ticks < 0)
{
destination[idx++] = Utf8Constants.Minus;
}
// Write day (and separator) if necessary
if (dayDigits > 0)
{
FormattingHelpers.WriteDigits(days, destination.Slice(idx, dayDigits));
idx += dayDigits;
destination[idx++] = (symbol == 'c') ? Utf8Constants.Period : Utf8Constants.Colon;
}
// Write "[h]h:mm:ss"
FormattingHelpers.WriteDigits(hours, destination.Slice(idx, hourDigits));
idx += hourDigits;
destination[idx++] = Utf8Constants.Colon;
FormattingHelpers.WriteDigits((uint)minutes, destination.Slice(idx, 2));
idx += 2;
destination[idx++] = Utf8Constants.Colon;
FormattingHelpers.WriteDigits((uint)seconds, destination.Slice(idx, 2));
idx += 2;
// Write fraction (and separator) if necessary
if (fractionDigits > 0)
{
destination[idx++] = Utf8Constants.Period;
FormattingHelpers.WriteDigits(fraction, destination.Slice(idx, fractionDigits));
idx += fractionDigits;
}
// And we're done!
Debug.Assert(idx == requiredOutputLength);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
namespace Frapid.Configuration.Tests.TenantServices.Fakes
{
public sealed class FakeLogger : ILogger
{
public ILogger ForContext(ILogEventEnricher enricher)
{
return this;
}
public ILogger ForContext(IEnumerable<ILogEventEnricher> enrichers)
{
return this;
}
public ILogger ForContext(string propertyName, object value, bool destructureObjects = false)
{
return this;
}
public ILogger ForContext<TSource>()
{
return this;
}
public ILogger ForContext(Type source)
{
return this;
}
public void Write(LogEvent logEvent)
{
}
public void Write(LogEventLevel level, string messageTemplate)
{
}
public void Write<T>(LogEventLevel level, string messageTemplate, T propertyValue)
{
}
public void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues)
{
}
public void Write(LogEventLevel level, Exception exception, string messageTemplate)
{
}
public void Write<T>(LogEventLevel level, Exception exception, string messageTemplate, T propertyValue)
{
}
public void Write<T0, T1>(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Write<T0, T1, T2>(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Write(LogEventLevel level, Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public bool IsEnabled(LogEventLevel level)
{
return true;
}
public void Verbose(string messageTemplate)
{
}
public void Verbose<T>(string messageTemplate, T propertyValue)
{
}
public void Verbose<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Verbose<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Verbose(string messageTemplate, params object[] propertyValues)
{
}
public void Verbose(Exception exception, string messageTemplate)
{
}
public void Verbose<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Verbose<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Verbose<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Verbose(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Debug(string messageTemplate)
{
}
public void Debug<T>(string messageTemplate, T propertyValue)
{
}
public void Debug<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Debug<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Debug(string messageTemplate, params object[] propertyValues)
{
}
public void Debug(Exception exception, string messageTemplate)
{
}
public void Debug<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Debug<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Debug<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Debug(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Information(string messageTemplate)
{
}
public void Information<T>(string messageTemplate, T propertyValue)
{
}
public void Information<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Information<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Information(string messageTemplate, params object[] propertyValues)
{
}
public void Information(Exception exception, string messageTemplate)
{
}
public void Information<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Information<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Information<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Information(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Warning(string messageTemplate)
{
}
public void Warning<T>(string messageTemplate, T propertyValue)
{
}
public void Warning<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Warning<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Warning(string messageTemplate, params object[] propertyValues)
{
}
public void Warning(Exception exception, string messageTemplate)
{
}
public void Warning<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Warning<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Warning<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Warning(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Error(string messageTemplate)
{
}
public void Error<T>(string messageTemplate, T propertyValue)
{
}
public void Error<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Error<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Error(string messageTemplate, params object[] propertyValues)
{
}
public void Error(Exception exception, string messageTemplate)
{
}
public void Error<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Error<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Error<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Error(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Fatal(string messageTemplate)
{
}
public void Fatal<T>(string messageTemplate, T propertyValue)
{
}
public void Fatal<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Fatal<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Fatal(string messageTemplate, params object[] propertyValues)
{
}
public void Fatal(Exception exception, string messageTemplate)
{
}
public void Fatal<T>(Exception exception, string messageTemplate, T propertyValue)
{
}
public void Fatal<T0, T1>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Fatal<T0, T1, T2>(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Fatal(Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, out IEnumerable<LogEventProperty> boundProperties)
{
parsedTemplate = new MessageTemplate(string.Empty, new List<MessageTemplateToken>());
boundProperties = new List<LogEventProperty>();
return false;
}
public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
{
property = new LogEventProperty(string.Empty, new ScalarValue(string.Empty));
return false;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.
//
using System.Linq;
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Calls the specified web service on each log message.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// The web service must implement a method that accepts a number of string parameters.
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" />
/// <p>The example web service that works with this example is shown below</p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" />
/// </example>
[Target("WebService")]
public sealed class WebServiceTarget : MethodCallTargetBase
{
private const string SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
private const string Soap12EnvelopeNamespace = "http://www.w3.org/2003/05/soap-envelope";
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
/// </summary>
public WebServiceTarget()
{
this.Protocol = WebServiceProtocol.Soap11;
//default NO utf-8 bom
const bool writeBOM = false;
this.Encoding = new UTF8Encoding(writeBOM);
this.IncludeBOM = writeBOM;
}
/// <summary>
/// Gets or sets the web service URL.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the Web service method name. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string MethodName { get; set; }
/// <summary>
/// Gets or sets the Web service namespace. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the protocol to be used when calling web service.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
[DefaultValue("Soap11")]
public WebServiceProtocol Protocol { get; set; }
/// <summary>
/// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property.
///
/// This will only work for UTF-8.
/// </summary>
public bool? IncludeBOM { get; set; }
/// <summary>
/// Gets or sets the encoding.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Calls the target method. Must be implemented in concrete classes.
/// </summary>
/// <param name="parameters">Method call parameters.</param>
protected override void DoInvoke(object[] parameters)
{
// method is not used, instead asynchronous overload will be used
throw new NotImplementedException();
}
/// <summary>
/// Invokes the web service method.
/// </summary>
/// <param name="parameters">Parameters to be passed.</param>
/// <param name="continuation">The continuation.</param>
protected override void DoInvoke(object[] parameters, AsyncContinuation continuation)
{
var request = (HttpWebRequest)WebRequest.Create(this.Url);
Func<AsyncCallback, IAsyncResult> begin = (r) => request.BeginGetRequestStream(r, null);
Func<IAsyncResult, Stream> getStream = request.EndGetRequestStream;
DoInvoke(parameters, continuation, request, begin, getStream);
}
internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc,
Func<IAsyncResult, Stream> getStreamFunc)
{
Stream postPayload = null;
switch (this.Protocol)
{
case WebServiceProtocol.Soap11:
postPayload = this.PrepareSoap11Request(request, parameters);
break;
case WebServiceProtocol.Soap12:
postPayload = this.PrepareSoap12Request(request, parameters);
break;
case WebServiceProtocol.HttpGet:
postPayload = this.PrepareGetRequest(request, parameters);
break;
case WebServiceProtocol.HttpPost:
postPayload = this.PreparePostRequest(request, parameters);
break;
}
AsyncContinuation sendContinuation =
ex =>
{
if (ex != null)
{
continuation(ex);
return;
}
request.BeginGetResponse(
r =>
{
try
{
using (var response = request.EndGetResponse(r))
{
}
continuation(null);
}
catch (Exception ex2)
{
InternalLogger.Error(ex2.ToString());
if (ex2.MustBeRethrown())
{
throw;
}
continuation(ex2);
}
},
null);
};
if (postPayload != null && postPayload.Length > 0)
{
postPayload.Position = 0;
beginFunc(
result =>
{
try
{
using (Stream stream = getStreamFunc(result))
{
WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding);
postPayload.Dispose();
}
sendContinuation(null);
}
catch (Exception ex)
{
postPayload.Dispose();
InternalLogger.Error(ex.ToString());
if (ex.MustBeRethrown())
{
throw;
}
continuation(ex);
}
});
}
else
{
sendContinuation(null);
}
}
private MemoryStream PrepareSoap11Request(HttpWebRequest request, object[] parameterValues)
{
string soapAction;
if (this.Namespace.EndsWith("/", StringComparison.Ordinal))
{
soapAction = this.Namespace + this.MethodName;
}
else
{
soapAction = this.Namespace + "/" + this.MethodName;
}
request.Headers["SOAPAction"] = soapAction;
return PrepareSoapRequestPost(request, parameterValues, SoapEnvelopeNamespace, "soap");
}
private MemoryStream PrepareSoap12Request(HttpWebRequest request, object[] parameterValues)
{
return PrepareSoapRequestPost(request, parameterValues, Soap12EnvelopeNamespace, "soap12");
}
/// <summary>
/// Helper for creating soap POST-XML request
/// </summary>
/// <param name="request"></param>
/// <param name="parameterValues"></param>
/// <param name="soapEnvelopeNamespace"></param>
/// <param name="soapname"></param>
/// <returns></returns>
private MemoryStream PrepareSoapRequestPost(WebRequest request, object[] parameterValues, string soapEnvelopeNamespace, string soapname)
{
request.Method = "POST";
request.ContentType = "text/xml; charset=" + this.Encoding.WebName;
var ms = new MemoryStream();
XmlWriter xtw = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = this.Encoding });
xtw.WriteStartElement(soapname, "Envelope", soapEnvelopeNamespace);
xtw.WriteStartElement("Body", soapEnvelopeNamespace);
xtw.WriteStartElement(this.MethodName, this.Namespace);
int i = 0;
foreach (MethodCallParameter par in this.Parameters)
{
xtw.WriteElementString(par.Name, Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture));
i++;
}
xtw.WriteEndElement(); // methodname
xtw.WriteEndElement(); // Body
xtw.WriteEndElement(); // soap:Envelope
xtw.Flush();
return ms;
}
private MemoryStream PreparePostRequest(HttpWebRequest request, object[] parameterValues)
{
request.Method = "POST";
return PrepareHttpRequest(request, parameterValues);
}
private MemoryStream PrepareGetRequest(HttpWebRequest request, object[] parameterValues)
{
request.Method = "GET";
return PrepareHttpRequest(request, parameterValues);
}
private MemoryStream PrepareHttpRequest(HttpWebRequest request, object[] parameterValues)
{
request.ContentType = "application/x-www-form-urlencoded; charset=" + this.Encoding.WebName;
var ms = new MemoryStream();
string separator = string.Empty;
var sw = new StreamWriter(ms, this.Encoding);
sw.Write(string.Empty);
int i = 0;
foreach (MethodCallParameter parameter in this.Parameters)
{
sw.Write(separator);
sw.Write(parameter.Name);
sw.Write("=");
sw.Write(UrlHelper.UrlEncode(Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture), true));
separator = "&";
i++;
}
sw.Flush();
return ms;
}
/// <summary>
/// Write from input to output. Fix the UTF-8 bom
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="writeUtf8BOM"></param>
/// <param name="encoding"></param>
private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding)
{
//only when utf-8 encoding is used, the Encoding preamble is optional
var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding);
const int preambleSize = 3;
if (!nothingToDo)
{
//it's UTF-8
var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize;
//BOM already in Encoding.
nothingToDo = writeUtf8BOM.Value && hasBomInEncoding;
//Bom already not in Encoding
nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding;
}
var offset = nothingToDo ? 0 : preambleSize;
input.CopyWithOffset(output, offset);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
internal Object _target;
// MethodBase, either cached after first request or assigned from a DynamicMethod
// For open delegates to collectible types, this may be a LoaderAllocator object
internal Object _methodBase;
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
internal IntPtr _methodPtr;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
internal IntPtr _methodPtrAux;
// This constructor is called from the class generated by the
// compiler generated code
protected Delegate(Object target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
// the choice of target method ambiguous) for backwards
// compatibility. The name matching was case sensitive and we
// preserve that as well.
if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected unsafe Delegate(Type target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// The name matching was case insensitive (no idea why this is
// different from the constructor above) and we preserve that as
// well.
BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
DelegateBindingFlags.CaselessMatching);
}
// Protect the default constructor so you can't build a delegate
private Delegate()
{
}
public Object DynamicInvoke(params Object[] args)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload of DynamicInvokeImpl that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return DynamicInvokeImpl(args);
}
protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null);
}
public override bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
return false;
Delegate d = (Delegate)obj;
// do an optimistic check first. This is hopefully cheap enough to be worth
if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
return true;
// even though the fields were not all equals the delegates may still match
// When target carries the delegate itself the 2 targets (delegates) may be different instances
// but the delegates are logically the same
// It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other
// if that's the case the delegates may still be equals but we need to make a more complicated check
if (_methodPtrAux.IsNull())
{
if (!d._methodPtrAux.IsNull())
return false; // different delegate kind
// they are both closed over the first arg
if (_target != d._target)
return false;
// fall through method handle check
}
else
{
if (d._methodPtrAux.IsNull())
return false; // different delegate kind
// Ignore the target as it will be the delegate instance, though it may be a different one
/*
if (_methodPtr != d._methodPtr)
return false;
*/
if (_methodPtrAux == d._methodPtrAux)
return true;
// fall through method handle check
}
// method ptrs don't match, go down long path
//
if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
return Delegate.InternalEqualMethodHandles(this, d);
else
return _methodBase.Equals(d._methodBase);
}
public override int GetHashCode()
{
//
// this is not right in the face of a method being jitted in one delegate and not in another
// in that case the delegate is the same and Equals will return true but GetHashCode returns a
// different hashcode which is not true.
/*
if (_methodPtrAux.IsNull())
return unchecked((int)((long)this._methodPtr));
else
return unchecked((int)((long)this._methodPtrAux));
*/
if (_methodPtrAux.IsNull())
return ( _target != null ? RuntimeHelpers.GetHashCode(_target) * 33 : 0) + GetType().GetHashCode();
else
return GetType().GetHashCode();
}
public static Delegate Combine(Delegate a, Delegate b)
{
if ((Object)a == null) // cast to object for a more efficient test
return b;
return a.CombineImpl(b);
}
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d, delegates[i]);
return d;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
// This routine will return the method
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
if (!isStatic)
{
if (_methodPtrAux == (IntPtr)0)
{
// The target may be of a derived type that doesn't have visibility onto the
// target method. We don't want to call RuntimeType.GetMethodBase below with that
// or reflection can end up generating a MethodInfo where the ReflectedType cannot
// see the MethodInfo itself and that breaks an important invariant. But the
// target type could include important generic type information we need in order
// to work out what the exact instantiation of the method's declaring type is. So
// we'll walk up the inheritance chain (which will yield exactly instantiated
// types at each step) until we find the declaring type. Since the declaring type
// we get from the method is probably shared and those in the hierarchy we're
// walking won't be we compare using the generic type definition forms instead.
Type currentType = _target.GetType();
Type targetType = declaringType.GetGenericTypeDefinition();
while (currentType != null)
{
if (currentType.IsGenericType &&
currentType.GetGenericTypeDefinition() == targetType)
{
declaringType = currentType as RuntimeType;
break;
}
currentType = currentType.BaseType;
}
// RCWs don't need to be "strongly-typed" in which case we don't find a base type
// that matches the declaring type of the method. This is fine because interop needs
// to work with exact methods anyway so declaringType is never shared at this point.
BCLDebug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method");
}
else
{
// it's an open one, need to fetch the first arg of the instantiation
MethodInfo invoke = this.GetType().GetMethod("Invoke");
declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
}
}
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
public Object Target
{
get
{
return GetTarget();
}
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
protected virtual Delegate CombineImpl(Delegate d)
{
throw new MulticastNotSupportedException(SR.Multicast_Combine);
}
protected virtual Delegate RemoveImpl(Delegate d)
{
return (d.Equals(this)) ? null : this;
}
public virtual Object Clone()
{
return MemberwiseClone();
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// We never generate a closed over null delegate and this is
// actually enforced via the check on target above, but we pass
// NeverCloseOverNull anyway just for clarity.
if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly |
DelegateBindingFlags.NeverCloseOverNull |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
if (!d.BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
return CreateDelegate(type, firstArgument, method, true);
}
// V2 API.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking. The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
firstArgument,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
//
// Implementation of ISerializable
//
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
}
//
// internal implementation details (FCALLS and utilities)
//
// V2 internal API.
// This is Critical because it skips the security check when creating the delegate.
internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
// used by the dynamic method code to generate a wrapper delegate.
// Allow flexible binding options since the target method is
// unambiguously provided to us.
if (!d.BindToMethodInfo(target,
method.GetMethodInfo(),
RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// Caution: this method is intended for deserialization only, no security checks are performed.
internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!type.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
// target in a valid delegate) so we should bind with the most
// relaxed rules available (the result will never be ambiguous, it
// just increases the chance of success with minor (compatible)
// signature changes). We explicitly skip security checks here --
// we're not really constructing a delegate, we're cloning an
// existing instance which already passed its checks.
Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument,
DelegateBindingFlags.SkipSecurityChecks |
DelegateBindingFlags.RelaxedSignature);
if (d == null)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, MethodInfo method)
{
return CreateDelegate(type, method, true);
}
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
{
Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
}
internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
{
Delegate d = InternalAlloc(rtType);
if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags))
return d;
else
return null;
}
//
// internal implementation details (FCALLS and utilities)
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualTypes(object a, object b);
// Used by the ctor. Do not call directly.
// The name of this function will appear in managed stacktraces as delegate constructor.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DelegateConstruct(Object target, IntPtr slot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetMulticastInvoke();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetInvokeMethod();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IRuntimeMethodInfo FindMethodHandle();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetCallStub(IntPtr methodPtr);
internal virtual Object GetTarget()
{
return (_methodPtrAux.IsNull()) ? _target : null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2);
}
// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in vm\comdelegate.h.
internal enum DelegateBindingFlags
{
StaticMethodOnly = 0x00000001, // Can only bind to static target methods
InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/test.proto
// Original file comments:
// Copyright 2015-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
//
// An integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Grpc.Testing {
/// <summary>
/// A simple service to test the various types of RPCs and experiment with
/// performance with various types of payload.
/// </summary>
public static partial class TestService
{
static readonly string __ServiceName = "grpc.testing.TestService";
static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"EmptyCall",
__Marshaller_Empty,
__Marshaller_Empty);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_CacheableUnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CacheableUnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
grpc::MethodType.ServerStreaming,
__ServiceName,
"StreamingOutputCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly grpc::Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new grpc::Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>(
grpc::MethodType.ClientStreaming,
__ServiceName,
"StreamingInputCall",
__Marshaller_StreamingInputCallRequest,
__Marshaller_StreamingInputCallResponse);
static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"FullDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"HalfDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"UnimplementedCall",
__Marshaller_Empty,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of TestService</summary>
public abstract partial class TestServiceBase
{
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by one response.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by one response. Response has cache control
/// headers set such that a caching HTTP proxy (such as GFE) can
/// satisfy subsequent requests.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task FullDuplexCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task HalfDuplexCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// The test server will not implement this method. It will be used
/// to test the behavior when clients call unimplemented methods.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for TestService</summary>
public partial class TestServiceClient : grpc::ClientBase<TestServiceClient>
{
/// <summary>Creates a new client for TestService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public TestServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for TestService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public TestServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected TestServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected TestServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_EmptyCall, null, options, request);
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_EmptyCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response. Response has cache control
/// headers set such that a caching HTTP proxy (such as GFE) can
/// satisfy subsequent requests.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CacheableUnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response. Response has cache control
/// headers set such that a caching HTTP proxy (such as GFE) can
/// satisfy subsequent requests.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CacheableUnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response. Response has cache control
/// headers set such that a caching HTTP proxy (such as GFE) can
/// satisfy subsequent requests.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> CacheableUnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CacheableUnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response. Response has cache control
/// headers set such that a caching HTTP proxy (such as GFE) can
/// satisfy subsequent requests.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> CacheableUnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CacheableUnaryCall, null, options, request);
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingOutputCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncServerStreamingCall(__Method_StreamingOutputCall, null, options, request);
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingInputCall(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::CallOptions options)
{
return CallInvoker.AsyncClientStreamingCall(__Method_StreamingInputCall, null, options);
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return FullDuplexCall(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_FullDuplexCall, null, options);
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return HalfDuplexCall(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_HalfDuplexCall, null, options);
}
/// <summary>
/// The test server will not implement this method. It will be used
/// to test the behavior when clients call unimplemented methods.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// The test server will not implement this method. It will be used
/// to test the behavior when clients call unimplemented methods.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request);
}
/// <summary>
/// The test server will not implement this method. It will be used
/// to test the behavior when clients call unimplemented methods.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// The test server will not implement this method. It will be used
/// to test the behavior when clients call unimplemented methods.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override TestServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new TestServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(TestServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall)
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_CacheableUnaryCall, serviceImpl.CacheableUnaryCall)
.AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall)
.AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall)
.AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall)
.AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall)
.AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build();
}
}
/// <summary>
/// A simple service NOT implemented at servers so clients can test for
/// that case.
/// </summary>
public static partial class UnimplementedService
{
static readonly string __ServiceName = "grpc.testing.UnimplementedService";
static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"UnimplementedCall",
__Marshaller_Empty,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[1]; }
}
/// <summary>Base class for server-side implementations of UnimplementedService</summary>
public abstract partial class UnimplementedServiceBase
{
/// <summary>
/// A call that no server should implement
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for UnimplementedService</summary>
public partial class UnimplementedServiceClient : grpc::ClientBase<UnimplementedServiceClient>
{
/// <summary>Creates a new client for UnimplementedService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public UnimplementedServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for UnimplementedService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public UnimplementedServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UnimplementedServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected UnimplementedServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// A call that no server should implement
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A call that no server should implement
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request);
}
/// <summary>
/// A call that no server should implement
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A call that no server should implement
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override UnimplementedServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new UnimplementedServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(UnimplementedServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build();
}
}
/// <summary>
/// A service used to control reconnect server.
/// </summary>
public static partial class ReconnectService
{
static readonly string __ServiceName = "grpc.testing.ReconnectService";
static readonly grpc::Marshaller<global::Grpc.Testing.ReconnectParams> __Marshaller_ReconnectParams = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectParams.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ReconnectInfo> __Marshaller_ReconnectInfo = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectInfo.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty> __Method_Start = new grpc::Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"Start",
__Marshaller_ReconnectParams,
__Marshaller_Empty);
static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo> __Method_Stop = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo>(
grpc::MethodType.Unary,
__ServiceName,
"Stop",
__Marshaller_Empty,
__Marshaller_ReconnectInfo);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[2]; }
}
/// <summary>Base class for server-side implementations of ReconnectService</summary>
public abstract partial class ReconnectServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.ReconnectParams request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ReconnectService</summary>
public partial class ReconnectServiceClient : grpc::ClientBase<ReconnectServiceClient>
{
/// <summary>Creates a new client for ReconnectService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ReconnectServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ReconnectService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ReconnectServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ReconnectServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ReconnectServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Start(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Start, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StartAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Start, null, options, request);
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Stop(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Stop, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StopAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Stop, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ReconnectServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ReconnectServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ReconnectServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Start, serviceImpl.Start)
.AddMethod(__Method_Stop, serviceImpl.Stop).Build();
}
}
}
#endregion
| |
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using Moritz.Globals;
namespace Moritz.Palettes
{
public partial class OrnamentsForm : Form
{
public OrnamentsForm(PaletteForm paletteForm, IPaletteFormsHostForm acForm, FormStateFunctions fsf)
{
InitializeOrnamentSettingsForm(null, paletteForm, acForm, fsf);
_fsf.SetFormState(this, SavedState.unconfirmed);
ConfirmButton.Enabled = false;
RevertToSavedButton.Enabled = false;
RevertToSavedButton.Hide();
}
public OrnamentsForm(XmlReader r, PaletteForm paletteForm, IPaletteFormsHostForm acForm, FormStateFunctions fsf)
{
_isLoading = true;
InitializeOrnamentSettingsForm(r, paletteForm, acForm, fsf);
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
_isLoading = false;
}
private void InitializeOrnamentSettingsForm(XmlReader r, PaletteForm paletteForm, IPaletteFormsHostForm acForm, FormStateFunctions fsf)
{
InitializeComponent();
_paletteForm = paletteForm;
_fsf = fsf;
_assistantComposerForm = acForm;
ConnectBasicChordControl();
Text = paletteForm.PaletteName + " : ornaments";
if(r != null)
{
_numberOfBasicChordDefs = ReadOrnamentSettingsForm(r);
}
_allNonOrnamentTextBoxes = GetNonOrnamentTextBoxes();
_12OrnamentTextBoxes = Get12OrnamentTextBoxes();
_allTextBoxes = new List<TextBox>();
_allTextBoxes.AddRange(_allNonOrnamentTextBoxes);
_allTextBoxes.AddRange(_12OrnamentTextBoxes);
NumBasicChordDefsTextBox_Leave(NumBasicChordDefsTextBox, null);
TouchAllTextBoxes();
}
private void ConnectBasicChordControl()
{
_bcc = new BasicChordControl(SetDialogState)
{
Location = new Point(0, 25),
BorderStyle = BorderStyle.None
};
this.TopPanel.Controls.Add(_bcc);
TopPanel.TabIndex = 0;
_bcc.TabIndex = 1;
int rightMargin = _bcc.DurationsLabel.Location.X + _bcc.DurationsLabel.Size.Width;
ReplaceLabel(_bcc.DurationsLabel, "relative durations", rightMargin);
ReplaceLabel(_bcc.VelocitiesLabel, "velocity increments", rightMargin);
ReplaceLabel(_bcc.MidiPitchesLabel, "transpositions", rightMargin);
ReplaceLabel(_bcc.ChordDensitiesLabel, "note density factors", rightMargin);
}
private void ReplaceLabel(Label label, string newText, int rightMargin)
{
label.Text = newText;
label.Location = new Point(rightMargin - label.Size.Width, label.Location.Y);
}
/************/
private int ReadOrnamentSettingsForm(XmlReader r)
{
#region default values
NumBasicChordDefsTextBox.Text = "";
BankIndicesTextBox.Text = "";
PatchIndicesTextBox.Text = "";
NumberOfOrnamentsTextBox.Text = "";
#endregion
Debug.Assert(r.Name == "ornamentSettings");
M.ReadToXmlElementTag(r, "numBasicChordDefs", "basicChord", "bankIndices", "patchIndices", "ornaments");
while(r.Name == "numBasicChordDefs" || r.Name == "basicChord" || r.Name == "bankIndices" || r.Name == "patchIndices"
|| r.Name == "numOrnaments" || r.Name == "ornaments")
{
if(r.NodeType != XmlNodeType.EndElement)
{
switch(r.Name)
{
case "numBasicChordDefs":
NumBasicChordDefsTextBox.Text = r.ReadElementContentAsString();
SavedNumBasicChordDefsTextBoxText = NumBasicChordDefsTextBox.Text;
break;
case "basicChord":
_bcc.ReadBasicChordControl(r);
break;
case "bankIndices":
BankIndicesTextBox.Text = r.ReadElementContentAsString();
SavedBankIndicesTextBoxText = BankIndicesTextBox.Text;
break;
case "patchIndices":
PatchIndicesTextBox.Text = r.ReadElementContentAsString();
SavedPatchIndicesTextBoxText = PatchIndicesTextBox.Text;
break;
case "numOrnaments":
NumberOfOrnamentsTextBox.Text = r.ReadElementContentAsString();
SavedNumberOfOrnamentsTextBoxText = NumberOfOrnamentsTextBox.Text;
break;
case "ornaments":
GetOrnaments(r);
break;
}
}
M.ReadToXmlElementTag(r, "ornamentSettings",
"numBasicChordDefs", "basicChord", "bankIndices", "patchIndices",
"numOrnaments", "ornaments");
}
Debug.Assert(r.Name == "ornamentSettings");
_fsf.SetSettingsAreSaved(this, false, ConfirmButton, RevertToSavedButton);
return int.Parse(NumBasicChordDefsTextBox.Text);
}
private int GetOrnaments(XmlReader r)
{
int numberOfOrnaments = 0;
Debug.Assert(r.Name == "ornaments");
M.ReadToXmlElementTag(r, "ornament");
while(r.Name == "ornament")
{
++numberOfOrnaments;
#region read each ornament
switch(numberOfOrnaments)
{
case 1:
Ornament1TextBox.Text = r.ReadElementContentAsString();
SavedOrnament1TextBoxText = Ornament1TextBox.Text;
break;
case 2:
Ornament2TextBox.Text = r.ReadElementContentAsString();
SavedOrnament2TextBoxText = Ornament2TextBox.Text;
break;
case 3:
Ornament3TextBox.Text = r.ReadElementContentAsString();
SavedOrnament3TextBoxText = Ornament3TextBox.Text;
break;
case 4:
Ornament4TextBox.Text = r.ReadElementContentAsString();
SavedOrnament4TextBoxText = Ornament4TextBox.Text;
break;
case 5:
Ornament5TextBox.Text = r.ReadElementContentAsString();
SavedOrnament5TextBoxText = Ornament5TextBox.Text;
break;
case 6:
Ornament6TextBox.Text = r.ReadElementContentAsString();
SavedOrnament6TextBoxText = Ornament6TextBox.Text;
break;
case 7:
Ornament7TextBox.Text = r.ReadElementContentAsString();
SavedOrnament7TextBoxText = Ornament7TextBox.Text;
break;
case 8:
Ornament8TextBox.Text = r.ReadElementContentAsString();
SavedOrnament8TextBoxText = Ornament8TextBox.Text;
break;
case 9:
Ornament9TextBox.Text = r.ReadElementContentAsString();
SavedOrnament9TextBoxText = Ornament9TextBox.Text;
break;
case 10:
Ornament10TextBox.Text = r.ReadElementContentAsString();
SavedOrnament10TextBoxText = Ornament10TextBox.Text;
break;
case 11:
Ornament11TextBox.Text = r.ReadElementContentAsString();
SavedOrnament11TextBoxText = Ornament11TextBox.Text;
break;
case 12:
Ornament12TextBox.Text = r.ReadElementContentAsString();
SavedOrnament12TextBoxText = Ornament12TextBox.Text;
break;
}
#endregion read each ornament
M.ReadToXmlElementTag(r, "ornaments", "ornament");
}
Debug.Assert(r.Name == "ornaments");
return numberOfOrnaments;
}
#region revertToSaved strings
private string SavedNumBasicChordDefsTextBoxText;
private string SavedBankIndicesTextBoxText;
private string SavedPatchIndicesTextBoxText;
private string SavedNumberOfOrnamentsTextBoxText;
private string SavedOrnament1TextBoxText;
private string SavedOrnament2TextBoxText;
private string SavedOrnament3TextBoxText;
private string SavedOrnament4TextBoxText;
private string SavedOrnament5TextBoxText;
private string SavedOrnament6TextBoxText;
private string SavedOrnament7TextBoxText;
private string SavedOrnament8TextBoxText;
private string SavedOrnament9TextBoxText;
private string SavedOrnament10TextBoxText;
private string SavedOrnament11TextBoxText;
private string SavedOrnament12TextBoxText;
#endregion revertToSaved strings
/************/
private List<TextBox> GetNonOrnamentTextBoxes()
{
List<TextBox> textBoxes = new List<TextBox>
{
NumBasicChordDefsTextBox,
_bcc.DurationsTextBox,
_bcc.VelocitiesTextBox,
_bcc.MidiPitchesTextBox,
_bcc.ChordOffsTextBox,
_bcc.ChordDensitiesTextBox,
_bcc.RootInversionTextBox,
_bcc.InversionIndicesTextBox,
_bcc.VerticalVelocityFactorsTextBox,
BankIndicesTextBox,
PatchIndicesTextBox,
NumberOfOrnamentsTextBox
};
return textBoxes;
}
/************/
private List<TextBox> Get12OrnamentTextBoxes()
{
List<TextBox> textBoxes = new List<TextBox>
{
this.Ornament1TextBox,
this.Ornament2TextBox,
this.Ornament3TextBox,
this.Ornament4TextBox,
this.Ornament5TextBox,
this.Ornament6TextBox,
this.Ornament7TextBox,
this.Ornament8TextBox,
this.Ornament9TextBox,
this.Ornament10TextBox,
this.Ornament11TextBox,
this.Ornament12TextBox
};
return textBoxes;
}
/************/
#region TextChanged event handler
private void SetToWhiteTextBox_TextChanged(object sender, EventArgs e)
{
M.SetToWhite(sender as TextBox);
}
#endregion TextChanged event handler
#region TextBox_Leave handlers
/************/
private void NumBasicChordDefsTextBox_Leave(object sender, EventArgs e)
{
TextBox numBasicChordDefsTextBox = sender as TextBox;
M.LeaveIntRangeTextBox(numBasicChordDefsTextBox, false, 1, 0, 12, SetDialogState);
if(numBasicChordDefsTextBox.BackColor == M.TextBoxErrorColor)
{
DisableMainParameters();
}
else
{
this.EnableMainParameters();
_numberOfBasicChordDefs = int.Parse(numBasicChordDefsTextBox.Text);
_bcc.NumberOfChordValues = _numberOfBasicChordDefs;
_bcc.SetHelpLabels();
string valStr = (_numberOfBasicChordDefs == 1) ? " value" : " values";
string inRangeStr = " in range [ 0..127 ]";
BankIndicesHelpLabel.Text = _numberOfBasicChordDefs.ToString() + valStr + inRangeStr;
PatchIndicesHelpLabel.Text = _numberOfBasicChordDefs.ToString() + valStr + inRangeStr;
OrnamentDefRangeLabel.Text = "Each value in these ornament sequences must be in the range [ 1.." +
_numberOfBasicChordDefs.ToString() + " ].";
TouchAllTextBoxes();
}
}
private void DisableMainParameters()
{
_bcc.Enabled = false;
_bcc.SetChordControls();
BankIndicesTextBox.Enabled = false;
BankIndicesTextBox.Enabled = false;
BankIndicesTextBox.Enabled = false;
PatchIndicesTextBox.Enabled = false;
PatchIndicesTextBox.Enabled = false;
PatchIndicesTextBox.Enabled = false;
OrnamentsGroupBox.Enabled = false;
}
private void EnableMainParameters()
{
_bcc.Enabled = true;
_bcc.SetChordControls();
BankIndicesTextBox.Enabled = true;
BankIndicesTextBox.Enabled = true;
BankIndicesTextBox.Enabled = true;
PatchIndicesTextBox.Enabled = true;
PatchIndicesTextBox.Enabled = true;
PatchIndicesTextBox.Enabled = true;
OrnamentsGroupBox.Enabled = true;
}
private void TouchAllTextBoxes()
{
_bcc.NumberOfChordValues = _numberOfBasicChordDefs;
_bcc.TouchAllTextBoxes();
BankIndicesTextBox_Leave(BankIndicesTextBox, null);
PatchIndicesTextBox_Leave(PatchIndicesTextBox, null);
NumberOfOrnamentsTextBox_Leave(NumberOfOrnamentsTextBox, null);
if(NumberOfOrnamentsTextBox.BackColor == M.TextBoxErrorColor)
{
DisableOrnamentTextBoxes();
}
else
{
EnableOrnamentTextBoxes();
}
}
private void DisableOrnamentTextBoxes()
{
foreach(TextBox textBox in _12OrnamentTextBoxes)
{
textBox.Enabled = false;
}
}
private void EnableOrnamentTextBoxes()
{
foreach(TextBox textBox in _12OrnamentTextBoxes)
{
textBox.Enabled = true;
}
TouchOrnamentTextBoxes();
}
private void TouchOrnamentTextBoxes()
{
for(int i = 1; i <= _ornaments.Count; ++i)
{
switch(i)
{
case 1:
this.Ornament1TextBox_Leave(Ornament1TextBox, null);
break;
case 2:
this.Ornament2TextBox_Leave(Ornament2TextBox, null);
break;
case 3:
this.Ornament3TextBox_Leave(Ornament3TextBox, null);
break;
case 4:
this.Ornament4TextBox_Leave(Ornament4TextBox, null);
break;
case 5:
this.Ornament5TextBox_Leave(Ornament5TextBox, null);
break;
case 6:
this.Ornament6TextBox_Leave(Ornament6TextBox, null);
break;
case 7:
this.Ornament7TextBox_Leave(Ornament7TextBox, null);
break;
case 8:
this.Ornament8TextBox_Leave(Ornament8TextBox, null);
break;
case 9:
this.Ornament9TextBox_Leave(Ornament9TextBox, null);
break;
case 10:
this.Ornament10TextBox_Leave(Ornament10TextBox, null);
break;
case 11:
this.Ornament11TextBox_Leave(Ornament11TextBox, null);
break;
case 12:
this.Ornament12TextBox_Leave(Ornament12TextBox, null);
break;
}
}
}
/************/
private void BankIndicesTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, true, (uint)_bcc.NumberOfChordValues, 0, 127, SetDialogState);
}
/************/
private void PatchIndicesTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, true, (uint)_bcc.NumberOfChordValues, 0, 127, SetDialogState);
}
/************/
private void NumberOfOrnamentsTextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, (uint)1, 1, 12, SetDialogState);
_ornaments = _ornaments ?? new List<List<int>>();
if(textBox.BackColor != M.TextBoxErrorColor)
{
int numberOfOrnaments = int.Parse(textBox.Text);
while(_ornaments.Count < numberOfOrnaments)
{
_ornaments.Add(new List<int>());
}
while(_ornaments.Count > numberOfOrnaments)
{
_ornaments.RemoveAt(_ornaments.Count - 1);
}
EnableOrnamentTextBoxes();
TouchOrnamentTextBoxes();
SetDialogSize(numberOfOrnaments);
}
_paletteForm.SetOrnamentControls();
}
private void SetDialogSize(int numberOfOrnaments)
{
OrnamentsGroupBox.Size = new Size(OrnamentsGroupBox.Size.Width, (46 + (numberOfOrnaments * 26)));
this.Size = new Size(851,
OrnamentsGroupBox.Location.Y + OrnamentsGroupBox.Size.Height + 2
+ BottomPanel.Size.Height + 42);
#region set all ornamentGroupBox Control Locations
// the following positions are reset here, in case the anchors change while editing)
NumberOfOrnamentsLabel.Location = new Point(NumberOfOrnamentsLabel.Location.X, 22);
NumberOfOrnamentsTextBox.Location = new Point(NumberOfOrnamentsTextBox.Location.X, 19);
NumberOfOrnamentsHelpLabel.Location = new Point(NumberOfOrnamentsHelpLabel.Location.X, 22);
int x = Ornament1TextBox.Location.X;
Ornament1TextBox.Location = new Point(x, 45);
Ornament2TextBox.Location = new Point(x, 71);
Ornament3TextBox.Location = new Point(x, 97);
Ornament4TextBox.Location = new Point(x, 123);
Ornament5TextBox.Location = new Point(x, 149);
Ornament6TextBox.Location = new Point(x, 175);
Ornament7TextBox.Location = new Point(x, 201);
Ornament8TextBox.Location = new Point(x, 227);
Ornament9TextBox.Location = new Point(x, 253);
Ornament10TextBox.Location = new Point(x, 279);
Ornament11TextBox.Location = new Point(x, 305);
Ornament12TextBox.Location = new Point(x, 331);
x = OLabel1.Location.X;
OLabel1.Location = new Point(x, 45 + 3);
OLabel2.Location = new Point(x, 71 + 3);
OLabel3.Location = new Point(x, 97 + 3);
OLabel4.Location = new Point(x, 123 + 3);
OLabel5.Location = new Point(x, 149 + 3);
OLabel6.Location = new Point(x, 175 + 3);
OLabel7.Location = new Point(x, 201 + 3);
OLabel8.Location = new Point(x, 227 + 3);
OLabel9.Location = new Point(x, 253 + 3);
OLabel10.Location = new Point(x - 3, 279 + 3);
OLabel11.Location = new Point(x - 3, 305 + 3);
OLabel12.Location = new Point(x - 3, 331 + 3);
#endregion
for(int i = 0; i < _12OrnamentTextBoxes.Count; ++i)
{
if(i < numberOfOrnaments)
{
_12OrnamentTextBoxes[i].Visible = true;
}
else
{
_12OrnamentTextBoxes[i].Visible = false; // avoids shadow at bottom of group box
}
}
BottomPanel.Location = new Point(BottomPanel.Location.X,
OrnamentsGroupBox.Location.Y + OrnamentsGroupBox.Size.Height + 2);
}
/************/
private void Ornament1TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 1);
}
private void Ornament2TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 2);
}
private void Ornament3TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 3);
}
private void Ornament4TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 4);
}
private void Ornament5TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 5);
}
private void Ornament6TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 6);
}
private void Ornament7TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 7);
}
private void Ornament8TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 8);
}
private void Ornament9TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 9);
}
private void Ornament10TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 10);
}
private void Ornament11TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 11);
}
private void Ornament12TextBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
M.LeaveIntRangeTextBox(textBox, false, uint.MaxValue, 1, _numberOfBasicChordDefs, SetDialogState);
SetOrnaments(textBox, 12);
}
private void SetOrnaments(TextBox textBox, int ornamentNumber)
{
if(textBox.BackColor != M.TextBoxErrorColor)
{
Debug.Assert(_ornaments.Count >= ornamentNumber);
_ornaments[ornamentNumber - 1] = M.StringToIntList(textBox.Text, ',');
}
}
private void SetDialogState(TextBox textBox, bool okay)
{
M.SetTextBoxErrorColorIfNotOkay(textBox, okay);
_fsf.SetSettingsAreUnconfirmed(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
if(!_isLoading)
_assistantComposerForm.UpdateForChangedPaletteForm();
}
#endregion
/************/
#region buttons
private void ShowContainingPaletteButton_Click(object sender, EventArgs e)
{
if(_paletteForm.Enabled)
{
_paletteForm.BringToFront();
}
else
{
_paletteForm.BringPaletteChordFormToFront();
}
}
private void ShowMainScoreFormButton_Click(object sender, EventArgs e)
{
((Form)_assistantComposerForm).BringToFront();
}
private void ConfirmButton_Click(object sender, EventArgs e)
{
_fsf.SetSettingsAreConfirmed(this, M.HasError(_allTextBoxes), ConfirmButton);
_assistantComposerForm.UpdateForChangedPaletteForm();
}
private void RevertToSavedButton_Click(object sender, EventArgs e)
{
Debug.Assert(((SavedState)this.Tag) == SavedState.unconfirmed || ((SavedState)this.Tag) == SavedState.confirmed);
DialogResult result =
MessageBox.Show("Are you sure you want to revert these ornament settings to the saved version?", "Revert?",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if(result == System.Windows.Forms.DialogResult.Yes)
{
try
{
using(XmlReader r = XmlReader.Create(_assistantComposerForm.SettingsPath))
{
M.ReadToXmlElementTag(r, "moritzKrystalScore");
M.ReadToXmlElementTag(r, "palette");
while(r.Name == "palette")
{
if(r.NodeType != XmlNodeType.EndElement)
{
r.MoveToAttribute("name");
if(r.Value == _paletteForm.PaletteName)
{
M.ReadToXmlElementTag(r, "ornamentSettings");
_numberOfBasicChordDefs = ReadOrnamentSettingsForm(r);
break;
}
}
M.ReadToXmlElementTag(r, "palette", "moritzKrystalScore");
}
}
TouchAllTextBoxes();
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
_paletteForm.SetOrnamentControls();
}
catch(Exception ex)
{
string msg = "Exception message:\n\n" + ex.Message;
MessageBox.Show(msg, "Error reading moritz krystal score settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_assistantComposerForm.UpdateForChangedPaletteForm();
}
}
#endregion buttons
/************/
#region ReviewableForm
#endregion ReviewableForm
#region public interface
public void WriteOrnamentSettingsForm(XmlWriter w)
{
w.WriteStartElement("ornamentSettings");
Debug.Assert(!string.IsNullOrEmpty(NumBasicChordDefsTextBox.Text));
w.WriteStartElement("numBasicChordDefs");
w.WriteString(NumBasicChordDefsTextBox.Text);
w.WriteEndElement();
BasicChordControl.WriteBasicChordControl(w);
if(!string.IsNullOrEmpty(this.BankIndicesTextBox.Text))
{
w.WriteStartElement("bankIndices");
w.WriteString(BankIndicesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(this.PatchIndicesTextBox.Text))
{
w.WriteStartElement("patchIndices");
w.WriteString(PatchIndicesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
Debug.Assert(!string.IsNullOrEmpty(NumberOfOrnamentsTextBox.Text));
w.WriteStartElement("numOrnaments");
w.WriteString(NumberOfOrnamentsTextBox.Text);
w.WriteEndElement();
w.WriteStartElement("ornaments");
for(int i = 1; i <= _ornaments.Count; ++i)
{
#region write ornament elements
w.WriteStartElement("ornament");
switch(i)
{
case 1:
w.WriteString(this.Ornament1TextBox.Text.Replace(" ", ""));
break;
case 2:
w.WriteString(this.Ornament2TextBox.Text.Replace(" ", ""));
break;
case 3:
w.WriteString(this.Ornament3TextBox.Text.Replace(" ", ""));
break;
case 4:
w.WriteString(this.Ornament4TextBox.Text.Replace(" ", ""));
break;
case 5:
w.WriteString(this.Ornament5TextBox.Text.Replace(" ", ""));
break;
case 6:
w.WriteString(this.Ornament6TextBox.Text.Replace(" ", ""));
break;
case 7:
w.WriteString(this.Ornament7TextBox.Text.Replace(" ", ""));
break;
case 8:
w.WriteString(this.Ornament8TextBox.Text.Replace(" ", ""));
break;
case 9:
w.WriteString(this.Ornament9TextBox.Text.Replace(" ", ""));
break;
case 10:
w.WriteString(this.Ornament10TextBox.Text.Replace(" ", ""));
break;
case 11:
w.WriteString(this.Ornament11TextBox.Text.Replace(" ", ""));
break;
case 12:
w.WriteString(this.Ornament12TextBox.Text.Replace(" ", ""));
break;
}
w.WriteEndElement(); // end of ornament
#endregion
}
w.WriteEndElement(); // end of ornaments
w.WriteEndElement(); // end of ornamentSettings
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
}
public BasicChordControl BasicChordControl { get { return _bcc; } }
public List<List<int>> Ornaments { get { return _ornaments; } }
#endregion
#region private variables
private BasicChordControl _bcc = null;
private PaletteForm _paletteForm = null;
private int _numberOfBasicChordDefs = -1;
private List<TextBox> _allNonOrnamentTextBoxes;
private List<TextBox> _12OrnamentTextBoxes;
private List<TextBox> _allTextBoxes;
private List<List<int>> _ornaments = null;
private FormStateFunctions _fsf;
private bool _isLoading; // is true while the ornamentsForm is loading from a file, otherwise false
private IPaletteFormsHostForm _assistantComposerForm;
#endregion private variables
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.Pipes.Tests
{
/// <summary>
/// The Specific NamedPipe tests cover edge cases or otherwise narrow cases that
/// show up within particular server/client directional combinations.
/// </summary>
public class NamedPipeTest_Specific : NamedPipeTestBase
{
[Fact]
public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
{
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
}
}
[Fact]
[ActiveIssue(812, PlatformID.AnyUnix)] // Unix implementation currently ignores timeout and cancellation token once the operation has been initiated]
public async Task ConnectToNonExistentServer_Throws_TimeoutException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not cancelled in this test
}
}
[Fact]
public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Task clientConnectToken = client.ConnectAsync(ctx.Token);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix implementation uses bidirectional sockets
public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException()
{
string serverName1 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
string serverName2 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
}
[Theory]
[InlineData(PipeOptions.None)]
[InlineData(PipeOptions.Asynchronous)]
[PlatformSpecific(PlatformID.Windows)] // Unix currently doesn't support message mode
public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
{
byte[] msg1 = new byte[] { 5, 7, 9, 10 };
byte[] msg2 = new byte[] { 2, 4 };
byte[] received1 = new byte[] { 0, 0, 0, 0 };
byte[] received2 = new byte[] { 0, 0 };
byte[] received3 = new byte[] { 0, 0, 0, 0 };
byte[] received4 = new byte[] { 0, 0, 0, 0 };
byte[] received5 = new byte[] { 0, 0 };
byte[] received6 = new byte[] { 0, 0, 0, 0 };
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
server.ReadMode = PipeTransmissionMode.Message;
Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);
Task clientTask = Task.Run(() =>
{
client.Connect();
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
int serverCount = client.NumberOfServerInstances;
Assert.Equal(1, serverCount);
});
server.WaitForConnection();
int len1 = server.Read(received1, 0, msg1.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1.Length, len1);
Assert.Equal(msg1, received1);
int len2 = server.Read(received2, 0, msg2.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2.Length, len2);
Assert.Equal(msg2, received2);
int expectedRead = msg1.Length - 1;
int len3 = server.Read(received3, 0, expectedRead); // read one less than message
Assert.False(server.IsMessageComplete);
Assert.Equal(expectedRead, len3);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received3[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received3);
Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received4);
Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2, received5);
expectedRead = msg1.Length - 1;
Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message
Assert.False(server.IsMessageComplete);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received6[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received6);
await clientTask;
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix doesn't support MaxNumberOfServerInstances
public async Task Windows_Get_NumberOfServerInstances_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 3))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
int expectedNumberOfServerInstances;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetNumberOfServerInstances(client.SafePipeHandle, out expectedNumberOfServerInstances), "GetNamedPipeHandleState failed");
Assert.Equal(expectedNumberOfServerInstances, client.NumberOfServerInstances);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Win32 P/Invokes to verify the user name
public async Task Windows_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
string expectedUserName;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed");
Assert.Equal(expectedUserName, server.GetImpersonationUserName());
}
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public async Task Unix_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
string name = server.GetImpersonationUserName();
Assert.NotNull(name);
Assert.False(string.IsNullOrWhiteSpace(name));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_MessagePipeTransissionMode()
{
Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.Out)]
[InlineData(PipeDirection.InOut)]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void Unix_BufferSizeRoundtripping(PipeDirection direction)
{
int desiredBufferSize = 0;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
desiredBufferSize = server.OutBufferSize * 2;
}
using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
if ((direction & PipeDirection.Out) != 0)
{
Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue);
}
if ((direction & PipeDirection.In) != 0)
{
Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void Windows_BufferSizeRoundtripping()
{
int desiredBufferSize = 10;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.OutBufferSize);
Assert.Equal(desiredBufferSize, client.InBufferSize);
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.InBufferSize);
Assert.Equal(0, client.OutBufferSize);
}
}
[Fact]
public void PipeTransmissionMode_Returns_Byte()
{
using (ServerClientPair pair = CreateServerClientPair())
{
Assert.Equal(PipeTransmissionMode.Byte, pair.writeablePipe.TransmissionMode);
Assert.Equal(PipeTransmissionMode.Byte, pair.readablePipe.TransmissionMode);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix doesn't currently support message mode
public void Windows_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte);
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte);
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
client.ReadMode = PipeTransmissionMode.Byte;
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Theory]
[InlineData(PipeDirection.Out, PipeDirection.In)]
[InlineData(PipeDirection.In, PipeDirection.Out)]
public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection)
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, clientDirection))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);
Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace BlobIO
{
#region Blob Type Enum
public enum BlobEncoding : byte
{
Null = 0,
String = 1,
Map = 2,
Array = 3,
Int = 4,
Float = 5,
Bool = 6,
}
#endregion
#region Blob Base Class
public abstract class Blob
{
public virtual Blob this[string index]
{
get { return null; }
set {}
}
public virtual Blob this[int index]
{
get { return null; }
set {}
}
public BlobEncoding Encoding { get; private set; }
public virtual Blob Remove(string key) { return null; }
public virtual Blob Remove(int index) { return null; }
public virtual void Add(Blob blob) {}
public virtual void Add(int index, Blob blob) {}
public virtual void Add(string key, Blob blob) {}
public virtual IEnumerable<Blob> Children { get { yield break; } }
public IEnumerable<Blob> DeepChildren
{
get
{
foreach (var child in Children)
if (child != null)
foreach (var deepChild in child.DeepChildren)
yield return deepChild;
}
}
public virtual int AsInt
{
get
{
int result;
TryGetInt(out result);
return result;
}
}
public override string ToString()
{
string value = Value;
if (value != null)
return "\"" + value.Replace("\"", "\\\"") + "\""; //Escape string.
return "\"\"";
}
public virtual bool AsBool
{
get
{
bool result;
TryGetBool(out result);
return result;
}
}
public virtual float AsFloat
{
get
{
float result;
TryGetFloat(out result);
return result;
}
}
public virtual bool TryGetInt(out int result)
{
return Value != null ? int.TryParse(Value, out result) : false;
}
public virtual bool TryGetBool(out bool result)
{
return Value != null ? bool.TryParse(Value, out result) : false;
}
public virtual bool TryGetFloat(out float result)
{
return Value != null ? float.TryParse(Value, out result) : false;
}
public virtual int Count { get { return 0; } }
public virtual string Value { get { return null; } }
public Blob(BlobEncoding encoding) { Encoding = encoding; }
}
#endregion
#region Blob Primitives
public class BlobString : Blob
{
string _value;
public override string Value
{
get { return _value; }
}
public BlobString(string value = "") : base(BlobEncoding.String) { _value = value; }
}
public class BlobInt : Blob
{
int _value;
public override string Value
{
get { return _value.ToString(); }
}
public override bool TryGetInt(out int result)
{
result = _value;
return true;
}
public override bool TryGetFloat(out float result)
{
result = _value;
return true;
}
public override bool TryGetBool(out bool result)
{
result = _value == 0;
return true;
}
public BlobInt(int number = 0) : base(BlobEncoding.Int) { _value = number; }
}
public class BlobFloat : Blob
{
float _value;
public override string Value
{
get { return _value.ToString(); }
}
public override bool TryGetInt(out int result)
{
result = (int)_value;
return true;
}
public override bool TryGetFloat(out float result)
{
result = _value;
return true;
}
public override bool TryGetBool(out bool result)
{
result = _value == 0;
return true;
}
public BlobFloat(float number = 0) : base (BlobEncoding.Float) { _value = number; }
}
public class BlobBool : Blob
{
bool _value;
public override string Value
{
get { return _value.ToString(); }
}
public override bool TryGetInt(out int result)
{
result = _value ? 1 : 0;
return true;
}
public override bool TryGetFloat(out float result)
{
result = _value ? 1 : 0;
return true;
}
public override bool TryGetBool(out bool result)
{
result = _value;
return true;
}
public BlobBool(bool state = false) : base (BlobEncoding.Bool) { _value = state; }
}
#endregion
#region Blob Array
public class BlobArray : Blob, IEnumerable
{
private List<Blob> _list;
public override Blob this[int index]
{
get
{
if (index >= 0 && index < _list.Count)
return _list[index];
return null;
}
set
{
if (index >= 0)
{
if (index < _list.Count)
_list[index] = value;
else
_list.Insert(index, value);
}
}
}
public override int Count { get { return _list.Count; } }
public override Blob Remove(int index)
{
if (index >= 0 && index < _list.Count)
{
var existing = _list[index];
_list.RemoveAt(index);
return existing;
}
return null;
}
public override void Add(Blob blob)
{
_list.Add(blob);
}
public override void Add(int index, Blob blob)
{
if (index >= 0)
_list.Insert(index, blob);
}
public override IEnumerable<Blob> Children
{
get
{
foreach (var blob in _list)
yield return blob;
}
}
public IEnumerator GetEnumerator() { return _list.GetEnumerator(); }
public override string ToString ()
{
string str = "[";
for (int i = 0; i < _list.Count; i++)
{
var item = _list[i];
if (item != null)
str += item.ToString();
else
str += "\"\"";
if (i < _list.Count - 1)
str += ", ";
}
str += "]";
return str;
}
public BlobArray() : base (BlobEncoding.Array)
{
_list = new List<Blob>();
}
}
#endregion
#region Blob Map
public class BlobMap : Blob, IEnumerable
{
private Dictionary<string, Blob> _dic;
public override Blob this[string index]
{
get
{
if (index != null)
{
Blob result;
_dic.TryGetValue(index, out result);
return result;
}
return null;
}
set
{
if (index != null)
_dic[index] = value;
}
}
public override int Count
{
get { return _dic.Count; }
}
public IEnumerator GetEnumerator() { return _dic.GetEnumerator(); }
public override IEnumerable<Blob> Children
{
get
{
foreach (var pair in _dic)
yield return pair.Value;
}
}
public override void Add(string key, Blob value) { this[key] = value; }
public override Blob Remove(string key)
{
Blob removed;
if (_dic.TryGetValue(key, out removed))
_dic.Remove(key);
return removed;
}
public BlobMap() : base (BlobEncoding.Map) { _dic = new Dictionary<string, Blob>(); }
}
#endregion
}
| |
#region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Pomona.Common.Internals;
using Pomona.Common.TypeSystem;
namespace Pomona.Common.Serialization.Json
{
public class PomonaJsonDeserializer : ITextDeserializer
{
private static readonly Action<Type, PomonaJsonDeserializer, IDeserializerNode, Reader>
deserializeArrayNodeGenericMethod =
GenericInvoker.Instance<PomonaJsonDeserializer>().CreateAction1<IDeserializerNode, Reader>(
x => x.DeserializeArrayNodeGeneric<object>(null, null));
private static readonly Action<Type, PomonaJsonDeserializer, IDeserializerNode, Reader, DictionaryTypeSpec>
deserializeDictionaryGenericMethod =
GenericInvoker.Instance<PomonaJsonDeserializer>()
.CreateAction1<IDeserializerNode, Reader, DictionaryTypeSpec>(
x => x.DeserializeDictionaryGeneric<object>(null, null, null));
private static readonly char[] reservedFirstCharacters = "^-*!".ToCharArray();
private readonly ISerializationContextProvider contextProvider;
private readonly JsonSerializer jsonSerializer;
public PomonaJsonDeserializer(ISerializationContextProvider contextProvider)
{
if (contextProvider == null)
throw new ArgumentNullException(nameof(contextProvider));
this.contextProvider = contextProvider;
this.jsonSerializer = new JsonSerializer() { DateParseHandling = DateParseHandling.None };
this.jsonSerializer.Converters.Add(new StringEnumConverter());
}
private Reader CreateReader(TextReader textReader)
{
return
new Reader(JToken.ReadFrom(new JsonTextReader(textReader) { DateParseHandling = DateParseHandling.None }));
}
private object Deserialize(TextReader textReader,
TypeSpec expectedBaseType,
IDeserializationContext context,
object patchedObject)
{
var node = new ItemValueDeserializerNode(expectedBaseType, context);
node.Operation = patchedObject != null ? DeserializerNodeOperation.Patch : DeserializerNodeOperation.Post;
if (patchedObject != null)
node.Value = patchedObject;
var reader = CreateReader(textReader);
DeserializeThroughContext(node, reader);
return node.Value;
}
private void DeserializeArrayNode(IDeserializerNode node, Reader reader)
{
if (TryDeserializeAsReference(node, reader))
return;
TypeSpec elementType;
if (node.ExpectedBaseType != null && node.ExpectedBaseType.IsCollection)
elementType = node.ExpectedBaseType.ElementType;
else
elementType = node.Context.GetClassMapping(typeof(object));
deserializeArrayNodeGenericMethod(elementType, this, node, reader);
}
private void DeserializeArrayNodeGeneric<TElement>(IDeserializerNode node, Reader reader)
{
if (TryDeserializeAsReference(node, reader))
return;
var jarr = reader.Token as JArray;
if (jarr == null)
throw new PomonaSerializationException("Expected JSON token of type array, but was " + reader.Token.Type);
var expectedBaseType = node.ExpectedBaseType;
// Deserialize as object array by default
bool asArray;
TypeSpec elementType;
if (expectedBaseType != null && expectedBaseType.IsCollection)
{
elementType = expectedBaseType.ElementType;
asArray = expectedBaseType.IsArray;
}
else
{
elementType = node.Context.GetClassMapping(typeof(object));
asArray = true;
}
bool isPatching;
ICollection<TElement> collection;
if (node.Value == null)
{
if (expectedBaseType != null && expectedBaseType == typeof(ISet<TElement>))
collection = new HashSet<TElement>();
else
collection = new List<TElement>();
isPatching = false;
}
else
{
collection = (ICollection<TElement>)node.Value;
isPatching = true;
}
if (isPatching && node.Operation == DeserializerNodeOperation.Post)
{
// Clear list and add new items
node.CheckItemAccessRights(HttpMethod.Delete);
collection.Clear();
}
foreach (var jitem in jarr)
{
var jobj = jitem as JObject;
var itemNode = new ItemValueDeserializerNode(elementType, node.Context, node.ExpandPath, node);
if (jobj != null)
{
foreach (var jprop in jobj.Properties().Where(IsIdentifierProperty))
{
// Starts with "-@" or "*@"
var identifyPropName = jprop.Name.Substring(2);
var identifyProp =
itemNode.ValueType.Properties.FirstOrDefault(x => x.JsonName == identifyPropName);
if (identifyProp == null)
{
throw new PomonaSerializationException("Unable to find predicate property " + jprop.Name
+ " in object");
}
var identifierNode = new ItemValueDeserializerNode(identifyProp.PropertyType,
itemNode.Context,
parent : itemNode);
DeserializeThroughContext(identifierNode, new Reader(jprop.Value));
var identifierValue = identifierNode.Value;
if (jprop.Name[0] == '-')
itemNode.Operation = DeserializerNodeOperation.Delete;
else if (jprop.Name[0] == '*')
itemNode.Operation = DeserializerNodeOperation.Patch;
else
throw new PomonaSerializationException("Unexpected json patch identifier property.");
itemNode.Value =
collection.Cast<object>().First(
x => identifierValue.Equals(identifyProp.GetValue(x, itemNode.Context)));
}
}
if (itemNode.Operation == DeserializerNodeOperation.Delete)
{
node.CheckItemAccessRights(HttpMethod.Delete);
collection.Remove((TElement)itemNode.Value);
}
else
{
if (itemNode.Operation == DeserializerNodeOperation.Patch)
node.CheckItemAccessRights(HttpMethod.Patch);
else if (isPatching)
node.CheckAccessRights(HttpMethod.Post);
DeserializeThroughContext(itemNode, new Reader(jitem));
if (itemNode.Operation != DeserializerNodeOperation.Patch)
{
if (!(itemNode.ExpectedBaseType is StructuredType)
|| itemNode.ExpectedBaseType.IsAnonymous()
|| !collection.Contains((TElement)itemNode.Value))
collection.Add((TElement)itemNode.Value);
}
}
}
if (node.Value == null)
node.Value = asArray ? collection.ToArray() : collection;
}
private void DeserializeComplexNode(IDeserializerNode node, Reader reader)
{
if (TryDeserializeAsReference(node, reader))
return;
var jobj = reader.Token as JObject;
if (jobj == null)
{
throw new PomonaSerializationException(
"Trying to deserialize to complex type, expected a JSON object type but got " + reader.Token.Type);
}
SetNodeValueType(node, jobj);
if (node.Operation == DeserializerNodeOperation.Default)
node.Operation = node.Value == null ? DeserializerNodeOperation.Post : DeserializerNodeOperation.Patch;
var propertyValueSource = new PropertyValueSource(jobj, node, this);
propertyValueSource.Deserialize();
}
private void DeserializeDictionary(IDeserializerNode node, Reader reader)
{
if (TryDeserializeAsReference(node, reader))
return;
var dictType = node.ExpectedBaseType as DictionaryTypeSpec;
if (dictType == null)
dictType = (DictionaryTypeSpec)node.Context.GetClassMapping(typeof(Dictionary<string, object>));
var keyType = dictType.KeyType.Type;
if (keyType != typeof(string))
{
throw new NotImplementedException(
"Only supports deserialization to IDictionary<TKey,TValue> where TKey is of type string.");
}
var valueType = dictType.ValueType.Type;
deserializeDictionaryGenericMethod(valueType, this, node, reader, dictType);
}
private void DeserializeDictionaryGeneric<TValue>(IDeserializerNode node,
Reader reader,
DictionaryTypeSpec dictType)
{
IDictionary<string, TValue> dict;
if (node.Value != null)
dict = (IDictionary<string, TValue>)node.Value;
else
dict = new Dictionary<string, TValue>();
var jobj = reader.Token as JObject;
var valueType = dictType.ValueType;
if (jobj == null)
{
throw new PomonaSerializationException(
"Expected dictionary property to have a JSON object value, but was " + reader.Token.Type);
}
foreach (var jprop in jobj.Properties())
{
var jpropName = jprop.Name;
if (jpropName.Length > 0 && reservedFirstCharacters.Contains(jpropName[0]))
{
if (jpropName[0] == '-')
{
// Removal operation
var unescapedPropertyName = UnescapePropertyName(jpropName.Substring(1));
dict.Remove(unescapedPropertyName);
}
else
{
throw new PomonaSerializationException(
"Unexpected character in json property name. Have propertie names been correctly escaped?");
}
}
else
{
var unescapedPropertyName = UnescapePropertyName(jpropName);
var itemNode = new ItemValueDeserializerNode(valueType,
node.Context,
node.ExpandPath + "." + unescapedPropertyName);
DeserializeThroughContext(itemNode, new Reader(jprop.Value));
dict[unescapedPropertyName] = (TValue)itemNode.Value;
}
}
if (node.Value == null)
node.Value = dict;
}
private void DeserializeNode(IDeserializerNode node, Reader reader)
{
if (reader.Token.Type == JTokenType.Null)
{
if (node.ExpectedBaseType != null && node.ExpectedBaseType.Type.IsValueType && !node.ExpectedBaseType.IsNullable)
{
throw new PomonaSerializationException("Deserialized to null, which is not allowed value for casting to type "
+ node.ValueType.FullName);
}
node.Value = null;
return;
}
TypeSpec mappedType;
if (node.ExpectedBaseType != null && node.ExpectedBaseType != typeof(object))
{
if (SetNodeValueType(node, reader.Token))
mappedType = node.ValueType;
else
mappedType = node.ExpectedBaseType;
}
else if (reader.Token.Type == JTokenType.String)
{
node.SetValueType(node.Context.GetClassMapping(typeof(string)));
mappedType = node.ValueType;
}
else
{
if (!SetNodeValueType(node, reader.Token))
{
throw new PomonaSerializationException(
"No expected type to deserialize to provided, and unable to get type from incoming JSON.");
}
mappedType = node.ValueType;
}
switch (mappedType.SerializationMode)
{
case TypeSerializationMode.Structured:
DeserializeComplexNode(node, reader);
break;
case TypeSerializationMode.Value:
DeserializeValueNode(node, reader);
break;
case TypeSerializationMode.Array:
DeserializeArrayNode(node, reader);
break;
case TypeSerializationMode.Dictionary:
DeserializeDictionary(node, reader);
break;
default:
throw new NotImplementedException("Don't know how to deserialize node with mode " +
mappedType.SerializationMode);
}
}
private void DeserializeThroughContext(IDeserializerNode node, Reader reader)
{
node.Context.Deserialize(node, n => DeserializeNode(n, reader));
}
private void DeserializeValueNode(IDeserializerNode node, Reader reader)
{
if (reader.Token.Type == JTokenType.Object)
{
var jobj = reader.Token as JObject;
JToken typeNameToken;
if (!jobj.TryGetValue("_type", out typeNameToken))
{
throw new PomonaSerializationException(
"Trying to deserialize boxed value, but lacks _type property.");
}
JToken valueToken;
if (!jobj.TryGetValue("value", out valueToken))
{
throw new PomonaSerializationException(
"Trying to deserialize boxed value, but lacks value property.");
}
var typeName = typeNameToken.ToString();
node.SetValueType(typeName);
node.Value = valueToken.ToObject(node.ValueType.Type, this.jsonSerializer);
}
else
{
var converter = node.ValueType.GetCustomJsonConverter();
if (converter == null)
node.Value = reader.Token.ToObject(node.ValueType.Type, this.jsonSerializer);
else
{
node.Value = converter.ReadJson(new JTokenReader(reader.Token),
node.ValueType.Type,
null,
this.jsonSerializer);
}
}
}
private bool IsIdentifierProperty(JProperty jProperty)
{
var name = jProperty.Name;
return (name.StartsWith("-@") || name.StartsWith("*@"));
}
private static bool SetNodeValueType(IDeserializerNode node, JToken jtoken)
{
var jobj = jtoken as JObject;
if (jobj != null)
{
JToken explicitTypeSpec;
if (jobj.TryGetValue("_type", out explicitTypeSpec))
{
if (explicitTypeSpec.Type != JTokenType.String)
{
throw new PomonaSerializationException(
"Found _type property on JSON object and expected this to be string, but got " +
explicitTypeSpec.Type);
}
var typeName = explicitTypeSpec.Value<string>();
if (typeName == "__result__")
{
if (!(node.ExpectedBaseType is QueryResultType) && node.ExpectedBaseType is EnumerableTypeSpec)
{
Type queryResultGenericTypeDefinition;
if (node.ExpectedBaseType.Type.IsGenericInstanceOf(typeof(ISet<>)))
queryResultGenericTypeDefinition = typeof(QuerySetResult<>);
else
queryResultGenericTypeDefinition = typeof(QueryResult<>);
var queryResultTypeInstance = queryResultGenericTypeDefinition.MakeGenericType(node.ExpectedBaseType.ElementType);
if (node.ExpectedBaseType.Type.IsAssignableFrom(queryResultTypeInstance))
node.SetValueType(queryResultTypeInstance);
}
}
else
node.SetValueType(typeName);
return true;
}
}
if (node.ExpectedBaseType == null || node.ExpectedBaseType == typeof(object))
{
switch (jtoken.Type)
{
case JTokenType.String:
node.SetValueType(typeof(string));
return true;
case JTokenType.Boolean:
node.SetValueType(typeof(bool));
return true;
case JTokenType.Array:
node.SetValueType(typeof(object[]));
return true;
case JTokenType.Object:
node.SetValueType(typeof(Dictionary<string, object>));
return true;
default:
return false;
}
}
return false;
}
private static bool TryDeserializeAsReference(IDeserializerNode node, Reader reader)
{
var jobj = reader.Token as JObject;
if (jobj == null)
return false;
SetNodeValueType(node, jobj);
JToken refStringToken;
if (!jobj.TryGetValue("_ref", out refStringToken) || refStringToken.Type != JTokenType.String)
return false;
var refString = (string)((JValue)refStringToken).Value;
node.Uri = refString;
try
{
node.Value = node.Context.CreateReference(node);
}
catch (Exception ex)
{
throw new PomonaSerializationException("Failed to deserialize: " + ex.Message, ex);
}
return true;
}
private static string UnescapePropertyName(string value)
{
if (value.StartsWith("^"))
return value.Substring(1);
return value;
}
public object Deserialize(TextReader textReader, DeserializeOptions options = null)
{
try
{
options = options ?? new DeserializeOptions();
var returnTypeSpecified = options.ExpectedBaseType != null;
if (returnTypeSpecified && typeof(JToken).IsAssignableFrom(options.ExpectedBaseType))
{
// When asking for a JToken, just return the deserialized json object
using (var jr = new JsonTextReader(textReader))
{
return JToken.Load(jr);
}
}
var context = this.contextProvider.GetDeserializationContext(options);
var expectedBaseType = returnTypeSpecified
? context.GetClassMapping(options.ExpectedBaseType)
: null;
return Deserialize(textReader, expectedBaseType, context, options.Target);
}
catch (JsonReaderException exception)
{
throw new PomonaSerializationException(exception.Message, exception);
}
catch (JsonSerializationException exception)
{
throw new PomonaSerializationException(exception.Message, exception);
}
}
#region Nested type: IJsonPropertyValueSource
private interface IJsonPropertyValueSource : IConstructorPropertySource
{
void Deserialize();
}
#endregion
#region Nested type: PropertyValueSource
private class PropertyValueSource : IJsonPropertyValueSource
{
private readonly PomonaJsonDeserializer deserializer;
private readonly IDeserializerNode node;
private readonly Dictionary<string, PropertyContainer> propertyDict;
public PropertyValueSource(JObject jobj, IDeserializerNode node, PomonaJsonDeserializer deserializer)
{
this.node = node;
this.deserializer = deserializer;
this.propertyDict = jobj.Properties()
.Select(x => new PropertyContainer(x))
.ToDictionary(x => x.Name, x => x, StringComparer.InvariantCultureIgnoreCase);
}
private void DeserializeRemainingProperties()
{
foreach (var prop in this.node.ValueType.Properties)
{
PropertyContainer propContainer;
if (this.propertyDict.TryGetValue(prop.JsonName, out propContainer) && !propContainer.Fetched)
{
var propNode = new PropertyValueDeserializerNode(this.node, prop)
{
Operation = propContainer.Operation
};
var oldValue = propNode.Value = propNode.Property.GetValue(this.node.Value, propNode.Context);
this.deserializer.DeserializeThroughContext(propNode, new Reader(propContainer.JProperty.Value));
var newValue = propNode.Value;
if (oldValue != newValue)
this.node.SetProperty(prop, newValue);
propContainer.Fetched = true;
}
}
}
private void SetUri()
{
PropertyContainer propertyContainer;
if (this.propertyDict.TryGetValue("_uri", out propertyContainer))
{
var jprop = propertyContainer.JProperty;
if (jprop.Value.Type != JTokenType.String)
throw new PomonaSerializationException("_uri property is expected to be of JSON type string");
this.node.Uri = (string)((JValue)jprop.Value).Value;
}
}
public TContext Context<TContext>()
{
// This is a bit confusing. node.Context refers to the deserializationContext, ResolveContext
// actually resolves context of type TContext, which for now is limited to mean NancyContext.
return this.node.Context.GetInstance<TContext>();
}
public void Deserialize()
{
SetUri();
if (this.node.Value == null || this.node.Operation == DeserializerNodeOperation.Post)
this.node.Value = this.node.Context.CreateResource(this.node.ValueType, this);
DeserializeRemainingProperties();
}
public TProperty GetValue<TProperty>(PropertyInfo propertyInfo, Func<TProperty> defaultFactory)
{
var type = this.node.ValueType;
var targetProp = type.TypeResolver.FromProperty(type, propertyInfo);
PropertyContainer propContainer;
if (!this.propertyDict.TryGetValue(targetProp.JsonName, out propContainer))
{
if (defaultFactory == null)
{
this.node.Context.OnMissingRequiredPropertyError(this.node, targetProp);
throw new PomonaSerializationException("Missing required property " + targetProp.JsonName +
" in json.");
}
return defaultFactory();
}
var propNode = new PropertyValueDeserializerNode(this.node, targetProp);
this.deserializer.DeserializeThroughContext(propNode, new Reader(propContainer.JProperty.Value));
propContainer.Fetched = true;
return (TProperty)propNode.Value;
}
public TParentType Parent<TParentType>()
{
var resourceNode = (IResourceNode)this.node;
return
(TParentType)
resourceNode.Parent.WalkTree(x => x.Parent).Where(
x => x.ResultType == null || x.ResultType.Type.IsAssignableFrom(typeof(TParentType))).Select
(x => x.Value).OfType<TParentType>().First();
}
#region Nested type: PropertyContainer
private class PropertyContainer
{
public PropertyContainer(JProperty jProperty)
{
JProperty = jProperty;
if (jProperty.Name.StartsWith("!"))
{
Name = jProperty.Name.Substring(1);
Operation = DeserializerNodeOperation.Post;
}
else
{
Name = jProperty.Name;
Operation = DeserializerNodeOperation.Patch;
}
}
public bool Fetched { get; set; }
public JProperty JProperty { get; }
public string Name { get; }
public DeserializerNodeOperation Operation { get; }
}
#endregion
}
#endregion
#region Nested type: Reader
internal class Reader
{
public Reader(JToken token)
{
Token = token;
}
public JToken Token { get; }
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.