context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Vector3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
/// <summary>Holder for reflection information generated from Vector3.proto</summary>
public static partial class Vector3Reflection {
#region Descriptor
/// <summary>File descriptor for Vector3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Vector3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg1WZWN0b3IzLnByb3RvIioKB1ZlY3RvcjMSCQoBeBgBIAEoARIJCgF5GAIg",
"ASgBEgkKAXoYAyABKAFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Vector3), global::Vector3.Parser, new[]{ "X", "Y", "Z" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Vector3 : pb::IMessage<Vector3> {
private static readonly pb::MessageParser<Vector3> _parser = new pb::MessageParser<Vector3>(() => new Vector3());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Vector3> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Vector3Reflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Vector3() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Vector3(Vector3 other) : this() {
x_ = other.x_;
y_ = other.y_;
z_ = other.z_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Vector3 Clone() {
return new Vector3(this);
}
/// <summary>Field number for the "x" field.</summary>
public const int XFieldNumber = 1;
private double x_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double X {
get { return x_; }
set {
x_ = value;
}
}
/// <summary>Field number for the "y" field.</summary>
public const int YFieldNumber = 2;
private double y_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Y {
get { return y_; }
set {
y_ = value;
}
}
/// <summary>Field number for the "z" field.</summary>
public const int ZFieldNumber = 3;
private double z_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Z {
get { return z_; }
set {
z_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Vector3);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Vector3 other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (X != other.X) return false;
if (Y != other.Y) return false;
if (Z != other.Z) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (X != 0D) hash ^= X.GetHashCode();
if (Y != 0D) hash ^= Y.GetHashCode();
if (Z != 0D) hash ^= Z.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (X != 0D) {
output.WriteRawTag(9);
output.WriteDouble(X);
}
if (Y != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Y);
}
if (Z != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Z);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (X != 0D) {
size += 1 + 8;
}
if (Y != 0D) {
size += 1 + 8;
}
if (Z != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Vector3 other) {
if (other == null) {
return;
}
if (other.X != 0D) {
X = other.X;
}
if (other.Y != 0D) {
Y = other.Y;
}
if (other.Z != 0D) {
Z = other.Z;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
X = input.ReadDouble();
break;
}
case 17: {
Y = input.ReadDouble();
break;
}
case 25: {
Z = input.ReadDouble();
break;
}
}
}
}
}
#endregion
#endregion Designer generated code
| |
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Net.Http.Client;
#if !NET45
using System.Buffers;
#endif
namespace Docker.DotNet
{
public class MultiplexedStream : IDisposable
{
private readonly WriteClosableStream _stream;
private TargetStream _target;
private int _remaining;
private readonly byte[] _header = new byte[8];
private readonly bool _multiplexed;
const int BufferSize = 81920;
public MultiplexedStream(WriteClosableStream stream, bool multiplexed)
{
_stream = stream;
_multiplexed = multiplexed;
}
public enum TargetStream
{
StandardIn = 0,
StandardOut = 1,
StandardError = 2
}
public struct ReadResult
{
public int Count { get; set; }
public TargetStream Target { get; set; }
public bool EOF => Count == 0;
}
public void CloseWrite()
{
_stream.CloseWrite();
}
public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _stream.WriteAsync(buffer, offset, count, cancellationToken);
}
public async Task<ReadResult> ReadOutputAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!_multiplexed)
{
return new ReadResult
{
Count = await _stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false),
Target = TargetStream.StandardOut
};
}
while (_remaining == 0)
{
for (var i = 0; i < _header.Length;)
{
var n = await _stream.ReadAsync(_header, i, _header.Length - i, cancellationToken).ConfigureAwait(false);
if (n == 0)
{
if (i == 0)
{
// End of the stream.
return new ReadResult();
}
throw new EndOfStreamException();
}
i += n;
}
switch ((TargetStream)_header[0])
{
case TargetStream.StandardIn:
case TargetStream.StandardOut:
case TargetStream.StandardError:
_target = (TargetStream)_header[0];
break;
default:
throw new IOException("unknown stream type");
}
_remaining = (_header[4] << 24) |
(_header[5] << 16) |
(_header[6] << 8) |
_header[7];
}
var toRead = Math.Min(count, _remaining);
var read = await _stream.ReadAsync(buffer, offset, toRead, cancellationToken).ConfigureAwait(false);
if (read == 0)
{
throw new EndOfStreamException();
}
_remaining -= read;
return new ReadResult
{
Count = read,
Target = _target
};
}
public async Task<(string stdout, string stderr)> ReadOutputToEndAsync(CancellationToken cancellationToken)
{
using (MemoryStream outMem = new MemoryStream(), outErr = new MemoryStream())
{
await CopyOutputToAsync(Stream.Null, outMem, outErr, cancellationToken);
outMem.Seek(0, SeekOrigin.Begin);
outErr.Seek(0, SeekOrigin.Begin);
using (StreamReader outRdr = new StreamReader(outMem), errRdr = new StreamReader(outErr))
{
var stdout = outRdr.ReadToEnd();
var stderr = errRdr.ReadToEnd();
return (stdout, stderr);
}
}
}
public async Task CopyFromAsync(Stream input, CancellationToken cancellationToken)
{
#if !NET45
var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
#else
var buffer = new byte[BufferSize];
#endif
try
{
for (;;)
{
var count = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (count == 0)
{
break;
}
await WriteAsync(buffer, 0, count, cancellationToken).ConfigureAwait(false);
}
}
finally
{
#if !NET45
ArrayPool<byte>.Shared.Return(buffer);
#endif
}
}
public async Task CopyOutputToAsync(Stream stdin, Stream stdout, Stream stderr, CancellationToken cancellationToken)
{
#if !NET45
var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
#else
var buffer = new byte[BufferSize];
#endif
try
{
for (;;)
{
var result = await ReadOutputAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (result.EOF)
{
return;
}
Stream stream;
switch (result.Target)
{
case TargetStream.StandardIn:
stream = stdin;
break;
case TargetStream.StandardOut:
stream = stdout;
break;
case TargetStream.StandardError:
stream = stderr;
break;
default:
throw new InvalidOperationException($"Unknown TargetStream: '{result.Target}'.");
}
await stream.WriteAsync(buffer, 0, result.Count, cancellationToken).ConfigureAwait(false);
}
}
finally
{
#if !NET45
ArrayPool<byte>.Shared.Return(buffer);
#endif
}
}
public void Dispose()
{
((IDisposable)_stream).Dispose();
}
}
}
| |
// 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: The base class for all exceptional conditions.
**
**
=============================================================================*/
namespace System
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Security;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
public class Exception : ISerializable
{
private void Init()
{
_message = null;
_stackTrace = null;
_dynamicMethods = null;
HResult = __HResults.COR_E_EXCEPTION;
_xcode = _COMPlusExceptionCode;
_xptrs = (IntPtr)0;
// Initialize the WatsonBuckets to be null
_watsonBuckets = null;
// Initialize the watson bucketing IP
_ipForWatsonBuckets = UIntPtr.Zero;
}
public Exception()
{
Init();
}
public Exception(String message)
{
Init();
_message = message;
}
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
public Exception(String message, Exception innerException)
{
Init();
_message = message;
_innerException = innerException;
}
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
_className = info.GetString("ClassName");
_message = info.GetString("Message");
_data = (IDictionary)(info.GetValueNoThrow("Data", typeof(IDictionary)));
_innerException = (Exception)(info.GetValue("InnerException", typeof(Exception)));
_helpURL = info.GetString("HelpURL");
_stackTraceString = info.GetString("StackTraceString");
_remoteStackTraceString = info.GetString("RemoteStackTraceString");
_remoteStackIndex = info.GetInt32("RemoteStackIndex");
_exceptionMethodString = (String)(info.GetValue("ExceptionMethod", typeof(String)));
HResult = info.GetInt32("HResult");
_source = info.GetString("Source");
// Get the WatsonBuckets that were serialized - this is particularly
// done to support exceptions going across AD transitions.
//
// We use the no throw version since we could be deserializing a pre-V4
// exception object that may not have this entry. In such a case, we would
// get null.
_watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[]));
if (_className == null || HResult == 0)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
// If we are constructing a new exception after a cross-appdomain call...
if (context.State == StreamingContextStates.CrossAppDomain)
{
// ...this new exception may get thrown. It is logically a re-throw, but
// physically a brand-new exception. Since the stack trace is cleared
// on a new exception, the "_remoteStackTraceString" is provided to
// effectively import a stack trace from a "remote" exception. So,
// move the _stackTraceString into the _remoteStackTraceString. Note
// that if there is an existing _remoteStackTraceString, it will be
// preserved at the head of the new string, so everything works as
// expected.
// Even if this exception is NOT thrown, things will still work as expected
// because the StackTrace property returns the concatenation of the
// _remoteStackTraceString and the _stackTraceString.
_remoteStackTraceString = _remoteStackTraceString + _stackTraceString;
_stackTraceString = null;
}
}
public virtual String Message
{
get
{
if (_message == null)
{
if (_className == null)
{
_className = GetClassName();
}
return Environment.GetResourceString("Exception_WasThrown", _className);
}
else
{
return _message;
}
}
}
public virtual IDictionary Data
{
get
{
if (_data == null)
if (IsImmutableAgileException(this))
_data = new EmptyReadOnlyDictionaryInternal();
else
_data = new ListDictionaryInternal();
return _data;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsImmutableAgileException(Exception e);
#if FEATURE_COMINTEROP
//
// Exception requires anything to be added into Data dictionary is serializable
// This wrapper is made serializable to satisfy this requirement but does NOT serialize
// the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
// Once the exception is serialized to debugger, debugger only needs the error reference string
//
[Serializable]
internal class __RestrictedErrorObject
{
// Hold the error object instance but don't serialize/deserialize it
[NonSerialized]
private object _realErrorObject;
internal __RestrictedErrorObject(object errorObject)
{
_realErrorObject = errorObject;
}
public object RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
[FriendAccessAllowed]
internal void AddExceptionDataForRestrictedErrorInfo(
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
object restrictedErrorObject,
bool hasrestrictedLanguageErrorObject = false)
{
IDictionary dict = Data;
if (dict != null)
{
dict.Add("RestrictedDescription", restrictedError);
dict.Add("RestrictedErrorReference", restrictedErrorReference);
dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid);
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)));
dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject);
}
}
internal bool TryGetRestrictedLanguageErrorObject(out object restrictedErrorObject)
{
restrictedErrorObject = null;
if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject"))
{
if (Data.Contains("__RestrictedErrorObject"))
{
__RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject;
if (restrictedObject != null)
restrictedErrorObject = restrictedObject.RealErrorObject;
}
return (bool)Data["__HasRestrictedLanguageErrorObject"];
}
return false;
}
#endif // FEATURE_COMINTEROP
private string GetClassName()
{
// Will include namespace but not full instantiation and assembly name.
if (_className == null)
_className = GetType().ToString();
return _className;
}
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
while (inner != null)
{
back = inner;
inner = inner.InnerException;
}
return back;
}
// Returns the inner exception contained in this exception
//
public Exception InnerException
{
get { return _innerException; }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
private MethodBase GetExceptionMethodFromStackTrace()
{
IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace);
// Under certain race conditions when exceptions are re-used, this can be null
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
public MethodBase TargetSite
{
get
{
return GetTargetSiteInternal();
}
}
// this function is provided as a private helper to avoid the security demand
private MethodBase GetTargetSiteInternal()
{
if (_exceptionMethod != null)
{
return _exceptionMethod;
}
if (_stackTrace == null)
{
return null;
}
if (_exceptionMethodString != null)
{
_exceptionMethod = GetExceptionMethodFromString();
}
else
{
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
return _exceptionMethod;
}
// Returns the stack trace as a string. If no stack trace is
// available, null is returned.
public virtual String StackTrace
{
get
{
// By default attempt to include file and line number info
return GetStackTrace(true);
}
}
// Computes and returns the stack trace as a string
// Attempts to get source file and line number information if needFileInfo
// is true. Note that this requires FileIOPermission(PathDiscovery), and so
// will usually fail in CoreCLR. To avoid the demand and resulting
// SecurityException we can explicitly not even try to get fileinfo.
private string GetStackTrace(bool needFileInfo)
{
string stackTraceString = _stackTraceString;
string remoteStackTraceString = _remoteStackTraceString;
// if no stack trace, try to get one
if (stackTraceString != null)
{
return remoteStackTraceString + stackTraceString;
}
if (_stackTrace == null)
{
return remoteStackTraceString;
}
// Obtain the stack trace string. Note that since Environment.GetStackTrace
// will add the path to the source file if the PDB is present and a demand
// for FileIOPermission(PathDiscovery) succeeds, we need to make sure we
// don't store the stack trace string in the _stackTraceString member variable.
String tempStackTraceString = Environment.GetStackTrace(this, needFileInfo);
return remoteStackTraceString + tempStackTraceString;
}
[FriendAccessAllowed]
internal void SetErrorCode(int hr)
{
HResult = hr;
}
// Sets the help link for this exception.
// This should be in a URL/URN form, such as:
// "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
// Changed to be a read-write String and not return an exception
public virtual String HelpLink
{
get
{
return _helpURL;
}
set
{
_helpURL = value;
}
}
public virtual String Source
{
get
{
if (_source == null)
{
StackTrace st = new StackTrace(this, true);
if (st.FrameCount > 0)
{
StackFrame sf = st.GetFrame(0);
MethodBase method = sf.GetMethod();
Module module = method.Module;
RuntimeModule rtModule = module as RuntimeModule;
if (rtModule == null)
{
System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder;
if (moduleBuilder != null)
rtModule = moduleBuilder.InternalModule;
else
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject"));
}
_source = rtModule.GetRuntimeAssembly().GetSimpleName();
}
}
return _source;
}
set { _source = value; }
}
public override String ToString()
{
return ToString(true, true);
}
private String ToString(bool needFileLineInfo, bool needMessage)
{
String message = (needMessage ? Message : null);
String s;
if (message == null || message.Length <= 0)
{
s = GetClassName();
}
else
{
s = GetClassName() + ": " + message;
}
if (_innerException != null)
{
s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
" " + Environment.GetResourceString("Exception_EndOfInnerExceptionStack");
}
string stackTrace = GetStackTrace(needFileLineInfo);
if (stackTrace != null)
{
s += Environment.NewLine + stackTrace;
}
return s;
}
private String GetExceptionMethodString()
{
MethodBase methBase = GetTargetSiteInternal();
if (methBase == null)
{
return null;
}
if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod)
{
// DynamicMethods cannot be serialized
return null;
}
// Note that the newline separator is only a separator, chosen such that
// it won't (generally) occur in a method name. This string is used
// only for serialization of the Exception Method.
char separator = '\n';
StringBuilder result = new StringBuilder();
if (methBase is ConstructorInfo)
{
RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase;
Type t = rci.ReflectedType;
result.Append((int)MemberTypes.Constructor);
result.Append(separator);
result.Append(rci.Name);
if (t != null)
{
result.Append(separator);
result.Append(t.Assembly.FullName);
result.Append(separator);
result.Append(t.FullName);
}
result.Append(separator);
result.Append(rci.ToString());
}
else
{
Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
Type t = rmi.DeclaringType;
result.Append((int)MemberTypes.Method);
result.Append(separator);
result.Append(rmi.Name);
result.Append(separator);
result.Append(rmi.Module.Assembly.FullName);
result.Append(separator);
if (t != null)
{
result.Append(t.FullName);
result.Append(separator);
}
result.Append(rmi.ToString());
}
return result.ToString();
}
private MethodBase GetExceptionMethodFromString()
{
Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
String[] args = _exceptionMethodString.Split(new char[] { '\0', '\n' });
if (args.Length != 5)
{
throw new SerializationException();
}
SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter());
si.AddValue("MemberType", (int)Int32.Parse(args[0], CultureInfo.InvariantCulture), typeof(Int32));
si.AddValue("Name", args[1], typeof(String));
si.AddValue("AssemblyName", args[2], typeof(String));
si.AddValue("ClassName", args[3]);
si.AddValue("Signature", args[4]);
MethodBase result;
StreamingContext sc = new StreamingContext(StreamingContextStates.All);
try
{
result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc);
}
catch (SerializationException)
{
result = null;
}
return result;
}
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { throw new PlatformNotSupportedException(); }
remove { throw new PlatformNotSupportedException(); }
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
String tempStackTraceString = _stackTraceString;
if (_stackTrace != null)
{
if (tempStackTraceString == null)
{
tempStackTraceString = Environment.GetStackTrace(this, true);
}
if (_exceptionMethod == null)
{
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
}
if (_source == null)
{
_source = Source; // Set the Source information correctly before serialization
}
info.AddValue("ClassName", GetClassName(), typeof(String));
info.AddValue("Message", _message, typeof(String));
info.AddValue("Data", _data, typeof(IDictionary));
info.AddValue("InnerException", _innerException, typeof(Exception));
info.AddValue("HelpURL", _helpURL, typeof(String));
info.AddValue("StackTraceString", tempStackTraceString, typeof(String));
info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String));
info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32));
info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String));
info.AddValue("HResult", HResult);
info.AddValue("Source", _source, typeof(String));
// Serialize the Watson bucket details as well
info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[]));
}
// This method will clear the _stackTrace of the exception object upon deserialization
// to ensure that references from another AD/Process dont get accidently used.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_stackTrace = null;
// We wont serialize or deserialize the IP for Watson bucketing since
// we dont know where the deserialized object will be used in.
// Using it across process or an AppDomain could be invalid and result
// in AV in the runtime.
//
// Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
}
// This is used by the runtime when re-throwing a managed exception. It will
// copy the stack trace to _remoteStackTraceString.
internal void InternalPreserveStackTrace()
{
string tmpStackTraceString;
#if FEATURE_APPX
if (AppDomain.IsAppXModel())
{
// Call our internal GetStackTrace in AppX so we can parse the result should
// we need to strip file/line info from it to make it PII-free. Calling the
// public and overridable StackTrace getter here was probably not intended.
tmpStackTraceString = GetStackTrace(true);
// Make sure that the _source field is initialized if Source is not overriden.
// We want it to contain the original faulting point.
string source = Source;
}
else
#else // FEATURE_APPX
// Preinitialize _source on CoreSystem as well. The legacy behavior is not ideal and
// we keep it for back compat but we can afford to make the change on the Phone.
string source = Source;
#endif // FEATURE_APPX
{
// Call the StackTrace getter in classic for compat.
tmpStackTraceString = StackTrace;
}
if (tmpStackTraceString != null && tmpStackTraceString.Length > 0)
{
_remoteStackTraceString = tmpStackTraceString + Environment.NewLine;
}
_stackTrace = null;
_stackTraceString = null;
}
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
// that unrelated exception object restorations could get blocked
// for a small duration but that sounds reasonable considering
// such scenarios are going to be extremely rare, where timing
// matches precisely.
[OptionalField]
private static object s_EDILock = new object();
internal UIntPtr IPForWatsonBuckets
{
get
{
return _ipForWatsonBuckets;
}
}
internal object WatsonBuckets
{
get
{
return _watsonBuckets;
}
}
internal string RemoteStackTrace
{
get
{
return _remoteStackTraceString;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PrepareForForeignExceptionRaise();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyStackTrace(object currentStackTrace);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyDynamicMethods(object currentDynamicMethods);
internal object DeepCopyStackTrace(object currentStackTrace)
{
if (currentStackTrace != null)
{
return CopyStackTrace(currentStackTrace);
}
else
{
return null;
}
}
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
{
return CopyDynamicMethods(currentDynamicMethods);
}
else
{
return null;
}
}
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
}
// This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the
// exception, just before the exception is "rethrown".
internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
{
bool fCanProcessException = !(IsImmutableAgileException(this));
// Restore only for non-preallocated exceptions
if (fCanProcessException)
{
// Take a lock to ensure only one thread can restore the details
// at a time against this exception object that could have
// multiple ExceptionDispatchInfo instances associated with it.
//
// We do this inside a finally clause to ensure ThreadAbort cannot
// be injected while we have taken the lock. This is to prevent
// unrelated exception restorations from getting blocked due to TAE.
try { }
finally
{
// When restoring back the fields, we again create a copy and set reference to them
// in the exception object. This will ensure that when this exception is thrown and these
// fields are modified, then EDI's references remain intact.
//
// Since deep copying can throw on OOM, try to get the copies
// outside the lock.
object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null) ? null : DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray);
object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null) ? null : DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray);
// Finally, restore the information.
//
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
lock (Exception.s_EDILock)
{
_watsonBuckets = exceptionDispatchInfo.WatsonBuckets;
_ipForWatsonBuckets = exceptionDispatchInfo.IPForWatsonBuckets;
_remoteStackTraceString = exceptionDispatchInfo.RemoteStackTrace;
SaveStackTracesFromDeepCopy(this, _stackTraceCopy, _dynamicMethodsCopy);
}
_stackTraceString = null;
// Marks the TES state to indicate we have restored foreign exception
// dispatch information.
Exception.PrepareForForeignExceptionRaise();
}
}
}
private String _className; //Needed for serialization.
private MethodBase _exceptionMethod; //Needed for serialization.
private String _exceptionMethodString; //Needed for serialization.
internal String _message;
private IDictionary _data;
private Exception _innerException;
private String _helpURL;
private Object _stackTrace;
[OptionalField] // This isnt present in pre-V4 exception objects that would be serialized.
private Object _watsonBuckets;
private String _stackTraceString; //Needed for serialization.
private String _remoteStackTraceString;
private int _remoteStackIndex;
#pragma warning disable 414 // Field is not used from managed.
// _dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of the exception. We do this because
// the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
// unless a System.Resolver object roots it.
private Object _dynamicMethods;
#pragma warning restore 414
// @MANAGED: HResult is used from within the EE! Rename with care - check VM directory
internal int _HResult; // HResult
public int HResult
{
get
{
return _HResult;
}
protected set
{
_HResult = value;
}
}
private String _source; // Mainly used by VB.
// WARNING: Don't delete/rename _xptrs and _xcode - used by functions
// on Marshal class. Native functions are in COMUtilNative.cpp & AppDomain
private IntPtr _xptrs; // Internal EE stuff
#pragma warning disable 414 // Field is not used from managed.
private int _xcode; // Internal EE stuff
#pragma warning restore 414
[OptionalField]
private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing
// See src\inc\corexcep.h's EXCEPTION_COMPLUS definition:
private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions
// InternalToString is called by the runtime to get the exception text
// and create a corresponding CrossAppDomainMarshaledException
internal virtual String InternalToString()
{
// Get the current stack trace string.
return ToString(true, true);
}
// this method is required so Object.GetType is not made virtual by the compiler
// _Exception.GetType()
public new Type GetType()
{
return base.GetType();
}
internal bool IsTransient
{
get
{
return nIsTransient(_HResult);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool nIsTransient(int hr);
// This piece of infrastructure exists to help avoid deadlocks
// between parts of mscorlib that might throw an exception while
// holding a lock that are also used by mscorlib's ResourceManager
// instance. As a special case of code that may throw while holding
// a lock, we also need to fix our asynchronous exceptions to use
// Win32 resources as well (assuming we ever call a managed
// constructor on instances of them). We should grow this set of
// exception messages as we discover problems, then move the resources
// involved to native code.
internal enum ExceptionMessageKind
{
ThreadAbort = 1,
ThreadInterrupted = 2,
OutOfMemory = 3
}
// See comment on ExceptionMessageKind
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg));
return retMesg;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
}
//--------------------------------------------------------------------------
// Telesto: Telesto doesn't support appdomain marshaling of objects so
// managed exceptions that leak across appdomain boundaries are flatted to
// its ToString() output and rethrown as an CrossAppDomainMarshaledException.
// The Message field is set to the ToString() output of the original exception.
//--------------------------------------------------------------------------
internal sealed class CrossAppDomainMarshaledException : SystemException
{
public CrossAppDomainMarshaledException(String message, int errorCode)
: base(message)
{
SetErrorCode(errorCode);
}
// Normally, only Telesto's UEF will see these exceptions.
// This override prints out the original Exception's ToString()
// output and hides the fact that it is wrapped inside another excepton.
internal override String InternalToString()
{
return Message;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
namespace Microsoft.AspNetCore.Mvc.Analyzers;
public class TagHelpersInCodeBlocksAnalyzerTest
{
private readonly DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1006_FunctionsContainingTagHelpersMustBeAsyncAndReturnTask;
private static readonly DiagnosticResult CS4033Result = new ("CS4033", DiagnosticSeverity.Error);
private static readonly DiagnosticResult CS4034Result = new ("CS4034", DiagnosticSeverity.Error);
[Fact]
public Task DiagnosticsAreReturned_ForUseOfTagHelpersInActions()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class DiagnosticsAreReturned_ForUseOfTagHelpersInActions : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
WriteLiteral(""\r\n"");
Action sometMethod = {|#0:() =>
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""d946c1cd0bbc2f1bde41a0f3eb6596ec7dca5c342925"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}|};
sometMethod();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0)
.WithArguments("lambda expression", "System.Func<System.Threading.Tasks.Task>");
return VerifyAnalyzerAsync(source, diagnosticResult, CS4034Result.WithLocation(1), CS4034Result.WithLocation(2));
}
[Fact]
public Task DiagnosticsAreReturned_ForUseOfTagHelpersInNonAsyncFunc()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class DiagnosticsAreReturned_ForUseOfTagHelpersInNonAsyncFunc : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
WriteLiteral(""\r\n"");
Func<Task> sometMethod = {|#0:() =>
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""452e9bab960ded6307b3903ebf73278bb1b2bec32959"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
return Task.CompletedTask;
}|};
sometMethod();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0);
return VerifyAnalyzerAsync(source, diagnosticResult, CS4034Result.WithLocation(1), CS4034Result.WithLocation(2));
}
[Fact]
public Task DiagnosticsAreReturned_ForUseOfTagHelpersInVoidClassMethods()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@""SHA1"", @""186d75f4b59675515143af9ff43784abaabd24a9"", @""/DiagnosticsAreReturned_ForUseOfTagHelpersInVoidClassMethods.cshtml"")]
public class DiagnosticsAreReturned_ForUseOfTagHelpersInVoidClassMethods : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
SometMethod();
WriteLiteral(""\r\n"");
}
#pragma warning restore 1998
{|#0:void SometMethod()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""186d75f4b59675515143af9ff43784abaabd24a93243"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}|}
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0);
return VerifyAnalyzerAsync(source, diagnosticResult, CS4033Result.WithLocation(1), CS4033Result.WithLocation(2));
}
[Fact]
public Task DiagnosticsAreReturned_ForUseOfTagHelpersInVoidDelegates()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class DiagnosticsAreReturned_ForUseOfTagHelpersInVoidDelegates : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
WriteLiteral(""\r\n"");
TestDelegate sometMethod = {|#0:delegate ()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""c63f59d4d7a4db461bc9f052a7833885a8d13dcf2972"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}|};
sometMethod();
WriteLiteral(""\r\n"");
}
#pragma warning restore 1998
delegate void TestDelegate();
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0);
return VerifyAnalyzerAsync(source, diagnosticResult, CS4034Result.WithLocation(1), CS4034Result.WithLocation(2));
}
[Fact]
public Task DiagnosticsAreReturned_ForUseOfTagHelpersInVoidLocalFunctions()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class DiagnosticsAreReturned_ForUseOfTagHelpersInVoidLocalFunctions : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
{|#0:void SometMethod()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""5a4c42fadc056422c6be6ab14a6bd877e2fa382d2948"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}|}
SometMethod();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0);
return VerifyAnalyzerAsync(source, diagnosticResult, CS4033Result.WithLocation(1), CS4033Result.WithLocation(2));
}
[Fact]
public Task NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncClassMethods()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncClassMethods_ : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
await SometMethod();
WriteLiteral(""\r\n"");
}
#pragma warning restore 1998
async Task SometMethod()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""8a14df240fb31e930618408064cdb1e343ff38f43283"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
return VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);
}
[Fact]
public Task NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncDelegates()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncDelegates_ : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
WriteLiteral(""\r\n"");
TestDelegate sometMethod = async delegate ()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""028e6be2d2e1a766b4ea9e3949a9e9797bb524083002"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
};
await sometMethod();
WriteLiteral(""\r\n"");
}
#pragma warning restore 1998
delegate Task TestDelegate();
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
return VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);
}
[Fact]
public Task NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions()
{
var source = @"
#pragma checksum ""C:\Users\nimullen\Documents\Projects\AnalyzerTest\NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions..cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""d5d5a28106f24c1bb31f07635157a3503dfdcb2d""
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions_), @""mvc.1.0.view"", @""/NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions..cshtml"")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@""SHA1"", @""d5d5a28106f24c1bb31f07635157a3503dfdcb2d"", @""/NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions..cshtml"")]
public class NoDiagnosticsAreReturned_ForUseOfTagHelpersInAsyncLocalFunctions_ : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
async Task SometMethod()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""d5d5a28106f24c1bb31f07635157a3503dfdcb2d2978"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}
await SometMethod();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
return VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);
}
[Fact]
public Task SingleDiagnosticIsReturned_ForMultipleTagHelpersInVoidMethod()
{
var source = @"
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public class SingleDiagnosticIsReturned_ForMultipleTagHelpersInVoidMethod : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(""\r\n"");
SometMethod();
WriteLiteral(""\r\n"");
}
#pragma warning restore 1998
{|#0:void SometMethod()
{
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""a49ad3383d0802d134e8f9ec401bad4c2f47d14d3250"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#1:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#2:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""a49ad3383d0802d134e8f9ec401bad4c2f47d14d4821"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#3:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#4:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
WriteLiteral("" "");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin(""cache"", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, ""a49ad3383d0802d134e8f9ec401bad4c2f47d14d6392"", async() => {
WriteLiteral(""\r\n <p>The current time is "");
Write(DateTime.Now);
WriteLiteral(""</p>\r\n "");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_CacheTagHelper);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute(""asp-vary-by-user"", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
{|#5:await __tagHelperRunner.RunAsync(__tagHelperExecutionContext)|};
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
{|#6:await __tagHelperExecutionContext.SetOutputContentAsync()|};
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(""\r\n"");
}|}
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
";
var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor)
.WithLocation(0);
return VerifyAnalyzerAsync(source,
diagnosticResult,
CS4033Result.WithLocation(1),
CS4033Result.WithLocation(2),
CS4033Result.WithLocation(3),
CS4033Result.WithLocation(4),
CS4033Result.WithLocation(5),
CS4033Result.WithLocation(6));
}
private static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
{
var test = new TagHelpersInCodeBlocksCSharpAnalzyerTest(TestReferences.MetadataReferences)
{
TestCode = source,
ReferenceAssemblies = TestReferences.EmptyReferenceAssemblies,
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync();
}
private sealed class TagHelpersInCodeBlocksCSharpAnalzyerTest : CSharpAnalyzerTest<AttributesShouldNotBeAppliedToPageModelAnalyzer, XUnitVerifier>
{
public TagHelpersInCodeBlocksCSharpAnalzyerTest(ImmutableArray<MetadataReference> metadataReferences)
{
TestState.AdditionalReferences.AddRange(metadataReferences);
}
protected override IEnumerable<DiagnosticAnalyzer> GetDiagnosticAnalyzers() => new[] { new TagHelpersInCodeBlocksAnalyzer() };
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Diagnostics.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpHandlerDiagnosticListenerTests
{
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is added into the list of DiagnosticListeners.
/// </summary>
[Fact]
public void TestHttpDiagnosticListenerIsRegistered()
{
bool listenerFound = false;
using (DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener =>
{
if (diagnosticListener.Name == "System.Net.Http.Desktop")
{
listenerFound = true;
}
})))
{
Assert.True(listenerFound, "The Http Diagnostic Listener didn't get added to the AllListeners list.");
}
}
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using
/// the subscribe overload with just the observer argument.
/// </summary>
[OuterLoop]
[Fact]
public void TestReflectInitializationViaSubscription1()
{
using (var eventRecords = new EventObserverAndRecorder())
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
// Just make sure some events are written, to confirm we successfully subscribed to it.
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
}
}
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using
/// the subscribe overload with just the observer argument and the more complicating enable filter function.
/// </summary>
[OuterLoop]
[Fact]
public void TestReflectInitializationViaSubscription2()
{
using (var eventRecords = new EventObserverAndRecorder(eventName => true))
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
// Just make sure some events are written, to confirm we successfully subscribed to it.
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
}
}
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using
/// the subscribe overload with the observer argument and the simple predicate argument.
/// </summary>
[OuterLoop]
[Fact]
public void TestReflectInitializationViaSubscription3()
{
using (var eventRecords = new EventObserverAndRecorder((eventName, arg1, arg2) => true))
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
// Just make sure some events are written, to confirm we successfully subscribed to it.
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
}
}
/// <summary>
/// Test to make sure we get both request and response events.
/// </summary>
[OuterLoop]
[Fact]
public async Task TestBasicReceiveAndResponseEvents()
{
using (var eventRecords = new EventObserverAndRecorder())
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
// We should have exactly one Start and one Stop event
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
Assert.Equal(2, eventRecords.Records.Count);
// Check to make sure: The first record must be a request, the next record must be a response.
KeyValuePair<string, object> startEvent;
Assert.True(eventRecords.Records.TryDequeue(out startEvent));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key);
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request");
Assert.NotNull(startRequest);
Assert.NotNull(startRequest.Headers["Request-Id"]);
Assert.Null(startRequest.Headers["traceparent"]);
Assert.Null(startRequest.Headers["tracestate"]);
KeyValuePair<string, object> stopEvent;
Assert.True(eventRecords.Records.TryDequeue(out stopEvent));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Stop", stopEvent.Key);
HttpWebRequest stopRequest = ReadPublicProperty<HttpWebRequest>(stopEvent.Value, "Request");
Assert.Equal(startRequest, stopRequest);
HttpWebResponse response = ReadPublicProperty<HttpWebResponse>(stopEvent.Value, "Response");
Assert.NotNull(response);
}
}
[OuterLoop]
[Fact]
public async Task TestW3CHeaders()
{
try
{
using (var eventRecords = new EventObserverAndRecorder())
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
// Check to make sure: The first record must be a request, the next record must be a response.
KeyValuePair<string, object> startEvent;
Assert.True(eventRecords.Records.TryDequeue(out startEvent));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key);
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request");
Assert.NotNull(startRequest);
var traceparent = startRequest.Headers["traceparent"];
Assert.NotNull(traceparent);
Assert.True(Regex.IsMatch(traceparent, "^[0-9a-f][0-9a-f]-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f][0-9a-f]$"));
Assert.Null(startRequest.Headers["tracestate"]);
Assert.Null(startRequest.Headers["Request-Id"]);
}
}
finally
{
CleanUp();
}
}
[OuterLoop]
[Fact]
public async Task TestW3CHeadersTraceStateAndCorrelationContext()
{
try
{
using (var eventRecords = new EventObserverAndRecorder())
{
var parent = new Activity("w3c activity");
parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom());
parent.TraceStateString = "some=state";
parent.AddBaggage("k", "v");
parent.Start();
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
parent.Stop();
// Check to make sure: The first record must be a request, the next record must be a response.
Assert.True(eventRecords.Records.TryDequeue(out var evnt));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", evnt.Key);
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request");
Assert.NotNull(startRequest);
var traceparent = startRequest.Headers["traceparent"];
var tracestate = startRequest.Headers["tracestate"];
var correlationContext = startRequest.Headers["Correlation-Context"];
Assert.NotNull(traceparent);
Assert.Equal("some=state", tracestate);
Assert.Equal("k=v", correlationContext);
Assert.True(traceparent.StartsWith($"00-{parent.TraceId.ToHexString()}-"));
Assert.True(Regex.IsMatch(traceparent, "^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"));
Assert.Null(startRequest.Headers["Request-Id"]);
}
}
finally
{
CleanUp();
}
}
[OuterLoop]
[Fact]
public async Task DoNotInjectRequestIdWhenPresent()
{
using (var eventRecords = new EventObserverAndRecorder())
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.RemoteEchoServer))
{
request.Headers.Add("Request-Id", "|rootId.1.");
(await client.SendAsync(request)).Dispose();
}
// Check to make sure: The first record must be a request, the next record must be a response.
Assert.True(eventRecords.Records.TryDequeue(out var evnt));
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request");
Assert.NotNull(startRequest);
Assert.Equal("|rootId.1.", startRequest.Headers["Request-Id"]);
}
}
[OuterLoop]
[Fact]
public async Task DoNotInjectTraceParentWhenPresent()
{
try
{
using (var eventRecords = new EventObserverAndRecorder())
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
// Send a random Http request to generate some events
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.RemoteEchoServer))
{
request.Headers.Add("traceparent", "00-abcdef0123456789abcdef0123456789-abcdef0123456789-01");
(await client.SendAsync(request)).Dispose();
}
// Check to make sure: The first record must be a request, the next record must be a response.
Assert.True(eventRecords.Records.TryDequeue(out var evnt));
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request");
Assert.NotNull(startRequest);
Assert.Equal("00-abcdef0123456789abcdef0123456789-abcdef0123456789-01", startRequest.Headers["traceparent"]);
}
}
finally
{
CleanUp();
}
}
/// <summary>
/// Test to make sure we get both request and response events.
/// </summary>
[OuterLoop]
[Fact]
public async Task TestResponseWithoutContentEvents()
{
using (var eventRecords = new EventObserverAndRecorder())
{
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEmptyContentServer)).Dispose();
}
// We should have exactly one Start and one Stop event
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
Assert.Equal(2, eventRecords.Records.Count);
// Check to make sure: The first record must be a request, the next record must be a response.
KeyValuePair<string, object> startEvent;
Assert.True(eventRecords.Records.TryDequeue(out startEvent));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key);
HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request");
Assert.NotNull(startRequest);
Assert.NotNull(startRequest.Headers["Request-Id"]);
KeyValuePair<string, object> stopEvent;
Assert.True(eventRecords.Records.TryDequeue(out stopEvent));
Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Ex.Stop", stopEvent.Key);
HttpWebRequest stopRequest = ReadPublicProperty<HttpWebRequest>(stopEvent.Value, "Request");
Assert.Equal(startRequest, stopRequest);
HttpStatusCode status = ReadPublicProperty<HttpStatusCode>(stopEvent.Value, "StatusCode");
Assert.NotNull(status);
WebHeaderCollection headers = ReadPublicProperty<WebHeaderCollection>(stopEvent.Value, "Headers");
Assert.NotNull(headers);
}
}
/// <summary>
/// Test that if request is redirected, it gets only one Start and one Stop event
/// </summary>
[OuterLoop]
[Fact]
public async Task TestRedirectedRequest()
{
using (var eventRecords = new EventObserverAndRecorder())
{
using (var client = new HttpClient())
{
Uri uriWithRedirect =
Configuration.Http.RemoteSecureHttp11Server.RedirectUriForDestinationUri(302, Configuration.Http.RemoteEchoServer, 10);
(await client.GetAsync(uriWithRedirect)).Dispose();
}
// We should have exactly one Start and one Stop event
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
}
}
/// <summary>
/// Test exception in request processing: exception should have expected type/status and now be swallowed by reflection hook
/// </summary>
[OuterLoop]
[Fact]
public async Task TestRequestWithException()
{
using (var eventRecords = new EventObserverAndRecorder())
{
var ex =
await Assert.ThrowsAsync<HttpRequestException>(
() => new HttpClient().GetAsync($"http://{Guid.NewGuid()}.com"));
// check that request failed because of the wrong domain name and not because of reflection
var webException = (WebException)ex.InnerException;
Assert.NotNull(webException);
Assert.True(webException.Status == WebExceptionStatus.NameResolutionFailure);
// We should have one Start event and no stop event
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(0, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
}
}
/// <summary>
/// Test request cancellation: reflection hook does not throw
/// </summary>
[OuterLoop]
[Fact]
public async Task TestCanceledRequest()
{
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using (var eventRecords = new EventObserverAndRecorder(_ => { cts.Cancel(); }))
{
using (var client = new HttpClient())
{
var ex = await Assert.ThrowsAnyAsync<Exception>(() => client.GetAsync(Configuration.Http.RemoteEchoServer, cts.Token));
Assert.True(ex is TaskCanceledException || ex is WebException);
}
// We should have one Start event and no stop event
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(0, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
}
}
/// <summary>
/// Test Request-Id and Correlation-Context headers injection
/// </summary>
[OuterLoop]
[Fact]
public async Task TestActivityIsCreated()
{
var parentActivity = new Activity("parent").AddBaggage("k1", "v1").AddBaggage("k2", "v2").Start();
using (var eventRecords = new EventObserverAndRecorder())
{
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
WebRequest thisRequest = ReadPublicProperty<WebRequest>(eventRecords.Records.First().Value, "Request");
var requestId = thisRequest.Headers["Request-Id"];
var correlationContext = thisRequest.Headers["Correlation-Context"];
Assert.NotNull(requestId);
Assert.True(requestId.StartsWith(parentActivity.Id));
Assert.NotNull(correlationContext);
Assert.True(correlationContext == "k1=v1,k2=v2" || correlationContext == "k2=v2,k1=v1");
}
parentActivity.Stop();
}
[OuterLoop]
[Fact]
public async Task TestInvalidBaggage()
{
var parentActivity = new Activity("parent")
.AddBaggage("key", "value")
.AddBaggage("bad/key", "value")
.AddBaggage("goodkey", "bad/value")
.Start();
using (var eventRecords = new EventObserverAndRecorder())
{
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
WebRequest thisRequest = ReadPublicProperty<WebRequest>(eventRecords.Records.First().Value, "Request");
string[] correlationContext = thisRequest.Headers["Correlation-Context"].Split(',');
Assert.Equal(3, correlationContext.Length);
Assert.True(correlationContext.Contains("key=value"));
Assert.True(correlationContext.Contains("bad%2Fkey=value"));
Assert.True(correlationContext.Contains("goodkey=bad%2Fvalue"));
}
parentActivity.Stop();
}
/// <summary>
/// Tests IsEnabled order and parameters
/// </summary>
[OuterLoop]
[Fact]
public async Task TestIsEnabled()
{
int eventNumber = 0;
bool IsEnabled(string evnt, object arg1, object arg2)
{
if (eventNumber == 0)
{
Assert.True(evnt == "System.Net.Http.Desktop.HttpRequestOut");
Assert.True(arg1 is WebRequest);
}
else if (eventNumber == 1)
{
Assert.True(evnt == "System.Net.Http.Desktop.HttpRequestOut.Start");
}
eventNumber++;
return true;
}
using (new EventObserverAndRecorder(IsEnabled))
{
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
Assert.Equal(2, eventNumber);
}
}
/// <summary>
/// Tests that nothing happens if IsEnabled returns false
/// </summary>
[OuterLoop]
[Fact]
public async Task TestIsEnabledAllOff()
{
using (var eventRecords = new EventObserverAndRecorder((evnt, arg1, arg2) => false))
{
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
}
Assert.Equal(0, eventRecords.Records.Count);
}
}
/// <summary>
/// Tests that if IsEnabled for request is false, request is not instrumented
/// </summary>
[OuterLoop]
[Fact]
public async Task TestIsEnabledRequestOff()
{
bool IsEnabled(string evnt, object arg1, object arg2)
{
if (evnt == "System.Net.Http.Desktop.HttpRequestOut")
{
return (arg1 as WebRequest).RequestUri.Scheme == "https";
}
return true;
}
using (var eventRecords = new EventObserverAndRecorder(IsEnabled))
{
using (var client = new HttpClient())
{
(await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose();
Assert.Equal(0, eventRecords.Records.Count);
(await client.GetAsync(Configuration.Http.SecureRemoteEchoServer)).Dispose();
Assert.Equal(2, eventRecords.Records.Count);
}
}
}
/// <summary>
/// Test to make sure every event record has the right dynamic properties.
/// </summary>
[OuterLoop]
[Fact]
public void TestMultipleConcurrentRequests()
{
ServicePointManager.DefaultConnectionLimit = int.MaxValue;
var parentActivity = new Activity("parent").Start();
using (var eventRecords = new EventObserverAndRecorder())
{
Dictionary<Uri, Tuple<WebRequest, WebResponse>> requestData =
new Dictionary<Uri, Tuple<WebRequest, WebResponse>>();
for (int i = 0; i < 10; i++)
{
Uri uriWithRedirect =
Configuration.Http.RemoteSecureHttp11Server.RedirectUriForDestinationUri(302, new Uri($"{Configuration.Http.RemoteEchoServer}?q={i}"), 3);
requestData[uriWithRedirect] = null;
}
// Issue all requests simultaneously
HttpClient httpClient = new HttpClient();
Dictionary<Uri, Task<HttpResponseMessage>> tasks = new Dictionary<Uri, Task<HttpResponseMessage>>();
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
foreach (var url in requestData.Keys)
{
tasks.Add(url, httpClient.GetAsync(url, cts.Token));
}
// wait up to 10 sec for all requests and suppress exceptions
Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(tt =>
{
foreach (var task in tasks)
{
task.Value.Result?.Dispose();
}
}).Wait();
// Examine the result. Make sure we got all successful requests.
// Just make sure some events are written, to confirm we successfully subscribed to it. We should have
// exactly 1 Start event per request and exaclty 1 Stop event per response (if request succeeded)
var successfulTasks = tasks.Where(t => t.Value.Status == TaskStatus.RanToCompletion);
Assert.Equal(tasks.Count, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start")));
Assert.Equal(successfulTasks.Count(), eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop")));
// Check to make sure: We have a WebRequest and a WebResponse for each successful request
foreach (var pair in eventRecords.Records)
{
object eventFields = pair.Value;
Assert.True(
pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Start" ||
pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Stop",
"An unexpected event of name " + pair.Key + "was received");
WebRequest request = ReadPublicProperty<WebRequest>(eventFields, "Request");
Assert.Equal(request.GetType().Name, "HttpWebRequest");
if (pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Start")
{
// Make sure this is an URL that we recognize. If not, just skip
Tuple<WebRequest, WebResponse> tuple = null;
if (!requestData.TryGetValue(request.RequestUri, out tuple))
{
continue;
}
// all requests have Request-Id with proper parent Id
var requestId = request.Headers["Request-Id"];
Assert.True(requestId.StartsWith(parentActivity.Id));
// all request activities are siblings:
var childSuffix = requestId.Substring(0, parentActivity.Id.Length);
Assert.True(childSuffix.IndexOf('.') == childSuffix.Length - 1);
Assert.Null(requestData[request.RequestUri]);
requestData[request.RequestUri] =
new Tuple<WebRequest, WebResponse>(request, null);
}
else
{
// This must be the response.
WebResponse response = ReadPublicProperty<WebResponse>(eventFields, "Response");
Assert.Equal(response.GetType().Name, "HttpWebResponse");
// By the time we see the response, the request object may already have been redirected with a different
// url. Hence, it's not reliable to just look up requestData by the URL/hostname. Instead, we have to look
// through each one and match by object reference on the request object.
Tuple<WebRequest, WebResponse> tuple = null;
foreach (Tuple<WebRequest, WebResponse> currentTuple in requestData.Values)
{
if (currentTuple != null && currentTuple.Item1 == request)
{
// Found it!
tuple = currentTuple;
break;
}
}
// Update the tuple with the response object
Assert.NotNull(tuple);
requestData[request.RequestUri] =
new Tuple<WebRequest, WebResponse>(request, response);
}
}
// Finally, make sure we have request and response objects for every successful request
foreach (KeyValuePair<Uri, Tuple<WebRequest, WebResponse>> pair in requestData)
{
if (successfulTasks.Any(t => t.Key == pair.Key))
{
Assert.NotNull(pair.Value);
Assert.NotNull(pair.Value.Item1);
Assert.NotNull(pair.Value.Item2);
}
}
}
}
private void CleanUp()
{
Activity.DefaultIdFormat = ActivityIdFormat.Hierarchical;
Activity.ForceDefaultIdFormat = false;
while (Activity.Current != null)
{
Activity.Current.Stop();
}
}
private static T ReadPublicProperty<T>(object obj, string propertyName)
{
Type type = obj.GetType();
PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
return (T)property.GetValue(obj);
}
/// <summary>
/// CallbackObserver is an adapter class that creates an observer (which you can pass
/// to IObservable.Subscribe), and calls the given callback every time the 'next'
/// operation on the IObserver happens.
/// </summary>
/// <typeparam name="T"></typeparam>
private class CallbackObserver<T> : IObserver<T>
{
public CallbackObserver(Action<T> callback) { _callback = callback; }
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value) { _callback(value); }
private Action<T> _callback;
}
/// <summary>
/// EventObserverAndRecorder is an observer that watches all Http diagnostic listener events flowing
/// through, and record all of them
/// </summary>
private class EventObserverAndRecorder : IObserver<KeyValuePair<string, object>>, IDisposable
{
private readonly Action<KeyValuePair<string, object>> onEvent;
public EventObserverAndRecorder(Action<KeyValuePair<string, object>> onEvent = null)
{
listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener =>
{
if (diagnosticListener.Name == "System.Net.Http.Desktop")
{
httpSubscription = diagnosticListener.Subscribe(this);
}
}));
this.onEvent = onEvent;
}
public EventObserverAndRecorder(Predicate<string> isEnabled)
{
listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener =>
{
if (diagnosticListener.Name == "System.Net.Http.Desktop")
{
httpSubscription = diagnosticListener.Subscribe(this, isEnabled);
}
}));
}
public EventObserverAndRecorder(Func<string, object, object, bool> isEnabled)
{
listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener =>
{
if (diagnosticListener.Name == "System.Net.Http.Desktop")
{
httpSubscription = diagnosticListener.Subscribe(this, isEnabled);
}
}));
}
public void Dispose()
{
listSubscription.Dispose();
httpSubscription.Dispose();
}
public ConcurrentQueue<KeyValuePair<string, object>> Records { get; } = new ConcurrentQueue<KeyValuePair<string, object>>();
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(KeyValuePair<string, object> record)
{
Records.Enqueue(record);
onEvent?.Invoke(record);
}
private readonly IDisposable listSubscription;
private IDisposable httpSubscription;
}
}
}
| |
using Lucene.Net.Support.IO;
using Lucene.Net.Util;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Lucene.Net.Store
{
/*
* 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.
*/
/// <summary>
/// Base <see cref="IndexInput"/> implementation that uses an array
/// of <see cref="ByteBuffer"/>s to represent a file.
/// <para/>
/// Because Java's <see cref="ByteBuffer"/> uses an <see cref="int"/> to address the
/// values, it's necessary to access a file greater
/// <see cref="int.MaxValue"/> in size using multiple byte buffers.
/// <para/>
/// For efficiency, this class requires that the buffers
/// are a power-of-two (<c>chunkSizePower</c>).
/// </summary>
public abstract class ByteBufferIndexInput : IndexInput
{
private ByteBuffer[] buffers;
private readonly long chunkSizeMask;
private readonly int chunkSizePower;
private int offset;
private long length;
private string sliceDescription;
private int curBufIndex;
private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex]
private bool isClone = false;
private readonly WeakIdentityMap<ByteBufferIndexInput, BoolRefWrapper> clones;
private class BoolRefWrapper
{
// .NET port: this is needed as bool is not a reference type
public BoolRefWrapper(bool value)
{
this.Value = value;
}
public bool Value { get; private set; }
}
internal ByteBufferIndexInput(string resourceDescription, ByteBuffer[] buffers, long length, int chunkSizePower, bool trackClones)
: base(resourceDescription)
{
//this.buffers = buffers; // LUCENENET: this is set in SetBuffers()
this.length = length;
this.chunkSizePower = chunkSizePower;
this.chunkSizeMask = (1L << chunkSizePower) - 1L;
this.clones = trackClones ? WeakIdentityMap<ByteBufferIndexInput, BoolRefWrapper>.NewConcurrentHashMap() : null;
Debug.Assert(chunkSizePower >= 0 && chunkSizePower <= 30);
Debug.Assert(((long)((ulong)length >> chunkSizePower)) < int.MaxValue);
// LUCENENET specific: MMapIndexInput calls SetBuffers() to populate
// the buffers, so we need to skip that call if it is null here, and
// do the seek inside SetBuffers()
if (buffers != null)
{
SetBuffers(buffers);
}
}
// LUCENENET specific for encapsulating buffers field.
internal void SetBuffers(ByteBuffer[] buffers) // necessary for MMapIndexInput
{
this.buffers = buffers;
Seek(0L);
}
public override sealed byte ReadByte()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.HasRemaining)
{
return curBuf.Get();
}
do
{
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
} while (!curBuf.HasRemaining);
return curBuf.Get();
}
public override sealed void ReadBytes(byte[] b, int offset, int len)
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
int curAvail = curBuf.Remaining;
if (len <= curAvail)
{
curBuf.Get(b, offset, len);
}
else
{
while (len > curAvail)
{
curBuf.Get(b, offset, curAvail);
len -= curAvail;
offset += curAvail;
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
curAvail = curBuf.Remaining;
}
curBuf.Get(b, offset, len);
}
}
/// <summary>
/// NOTE: this was readShort() in Lucene
/// </summary>
public override sealed short ReadInt16()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 2)
{
return curBuf.GetInt16();
}
return base.ReadInt16();
}
/// <summary>
/// NOTE: this was readInt() in Lucene
/// </summary>
public override sealed int ReadInt32()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 4)
{
return curBuf.GetInt32();
}
return base.ReadInt32();
}
/// <summary>
/// NOTE: this was readLong() in Lucene
/// </summary>
public override sealed long ReadInt64()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 8)
{
return curBuf.GetInt64();
}
return base.ReadInt64();
}
public override sealed long GetFilePointer()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
return (((long)curBufIndex) << chunkSizePower) + curBuf.Position - offset;
}
public override sealed void Seek(long pos)
{
// necessary in case offset != 0 and pos < 0, but pos >= -offset
if (pos < 0L)
{
throw new ArgumentException("Seeking to negative position: " + this);
}
pos += offset;
// we use >> here to preserve negative, so we will catch AIOOBE,
// in case pos + offset overflows.
int bi = (int)(pos >> chunkSizePower);
try
{
ByteBuffer b = buffers[bi];
b.Position = ((int)(pos & chunkSizeMask));
// write values, on exception all is unchanged
this.curBufIndex = bi;
this.curBuf = b;
}
catch (IndexOutOfRangeException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (ArgumentException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (NullReferenceException)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
}
public override sealed long Length
{
get { return length; }
}
public override sealed object Clone()
{
ByteBufferIndexInput clone = BuildSlice(0L, this.length);
try
{
clone.Seek(GetFilePointer());
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
/// <summary>
/// Creates a slice of this index input, with the given description, offset, and length. The slice is seeked to the beginning.
/// </summary>
public ByteBufferIndexInput Slice(string sliceDescription, long offset, long length)
{
if (isClone) // well we could, but this is stupid
{
throw new InvalidOperationException("cannot slice() " + sliceDescription + " from a cloned IndexInput: " + this);
}
ByteBufferIndexInput clone = BuildSlice(offset, length);
clone.sliceDescription = sliceDescription;
try
{
clone.Seek(0L);
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
private ByteBufferIndexInput BuildSlice(long offset, long length)
{
if (buffers == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
if (offset < 0 || length < 0 || offset + length > this.length)
{
throw new ArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset + ",length=" + length + ",fileLength=" + this.length + ": " + this);
}
// include our own offset into the final offset:
offset += this.offset;
ByteBufferIndexInput clone = (ByteBufferIndexInput)base.Clone();
clone.isClone = true;
// we keep clone.clones, so it shares the same map with original and we have no additional cost on clones
Debug.Assert(clone.clones == this.clones);
clone.buffers = BuildSlice(buffers, offset, length);
clone.offset = (int)(offset & chunkSizeMask);
clone.length = length;
// register the new clone in our clone list to clean it up on closing:
if (clones != null)
{
this.clones.Put(clone, new BoolRefWrapper(true));
}
return clone;
}
/// <summary>
/// Returns a sliced view from a set of already-existing buffers:
/// the last buffer's <see cref="Support.IO.Buffer.Limit"/> will be correct, but
/// you must deal with <paramref name="offset"/> separately (the first buffer will not be adjusted)
/// </summary>
private ByteBuffer[] BuildSlice(ByteBuffer[] buffers, long offset, long length)
{
long sliceEnd = offset + length;
int startIndex = (int)((long)((ulong)offset >> chunkSizePower));
int endIndex = (int)((long)((ulong)sliceEnd >> chunkSizePower));
// we always allocate one more slice, the last one may be a 0 byte one
ByteBuffer[] slices = new ByteBuffer[endIndex - startIndex + 1];
for (int i = 0; i < slices.Length; i++)
{
slices[i] = buffers[startIndex + i].Duplicate();
}
// set the last buffer's limit for the sliced view.
slices[slices.Length - 1].Limit = ((int)(sliceEnd & chunkSizeMask));
return slices;
}
private void UnsetBuffers()
{
buffers = null;
curBuf = null;
curBufIndex = 0;
}
// LUCENENET specific - rather than using all of this exception catching nonsense
// for control flow, we check whether we are disposed first.
private void EnsureOpen()
{
if (buffers == null || curBuf == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
if (buffers == null)
{
return;
}
// make local copy, then un-set early
ByteBuffer[] bufs = buffers;
UnsetBuffers();
if (clones != null)
{
clones.Remove(this);
}
if (isClone)
{
return;
}
// for extra safety unset also all clones' buffers:
if (clones != null)
{
foreach (ByteBufferIndexInput clone in clones.Keys)
{
clone.UnsetBuffers();
}
this.clones.Clear();
}
foreach (ByteBuffer b in bufs)
{
FreeBuffer(b);
}
}
finally
{
UnsetBuffers();
}
}
}
/// <summary>
/// Called when the contents of a buffer will be no longer needed.
/// </summary>
protected abstract void FreeBuffer(ByteBuffer b);
public override sealed string ToString()
{
if (sliceDescription != null)
{
return base.ToString() + " [slice=" + sliceDescription + "]";
}
else
{
return base.ToString();
}
}
}
}
| |
namespace ZetaHtmlEditControl.UI.EditControlDerives
{
public partial class HtmlEditControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HtmlEditControl));
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.textModulesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dummyTextModuleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.textModulesSeparator = new System.Windows.Forms.ToolStripSeparator();
this.boldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.italicToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.underlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteFromMsWordToolStripItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteAsTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.tableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertNewTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator();
this.insertRowBeforeCurrentRowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertColumnBeforeCurrentColumnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.addRowAfterTheLastTableRowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addColumnAfterTheLastTableColumnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.tablePropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rowPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.columnPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cellPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.deleteRowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteColumnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.foreColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColorNoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.foreColor01ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor02ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor03ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor04ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor05ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor06ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor07ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor08ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor09ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.foreColor10ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.backColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackColorNoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.BackColor01ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackColor02ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackColor03ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackColor04ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackColor05ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.justifyLeftToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.justifyCenterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.justifyRightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.bullettedListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.numberedListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.outdentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.hyperLinkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.removeFormattingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.htmlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip.SuspendLayout();
this.SuspendLayout();
//
// contextMenuStrip
//
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.textModulesToolStripMenuItem,
this.textModulesSeparator,
this.boldToolStripMenuItem,
this.italicToolStripMenuItem,
this.underlineToolStripMenuItem,
this.toolStripSeparator1,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.pasteFromMsWordToolStripItem,
this.pasteAsTextToolStripMenuItem,
this.deleteToolStripMenuItem,
this.toolStripSeparator9,
this.tableToolStripMenuItem,
this.toolStripSeparator2,
this.foreColorToolStripMenuItem,
this.backColorToolStripMenuItem,
this.toolStripSeparator6,
this.justifyLeftToolStripMenuItem,
this.justifyCenterToolStripMenuItem,
this.justifyRightToolStripMenuItem,
this.toolStripSeparator3,
this.bullettedListToolStripMenuItem,
this.numberedListToolStripMenuItem,
this.indentToolStripMenuItem,
this.outdentToolStripMenuItem,
this.toolStripSeparator4,
this.hyperLinkToolStripMenuItem,
this.toolStripSeparator5,
this.removeFormattingToolStripMenuItem,
this.htmlToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip";
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
//
// textModulesToolStripMenuItem
//
this.textModulesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.dummyTextModuleToolStripMenuItem});
resources.ApplyResources(this.textModulesToolStripMenuItem, "textModulesToolStripMenuItem");
this.textModulesToolStripMenuItem.Name = "textModulesToolStripMenuItem";
this.textModulesToolStripMenuItem.DropDownOpening += new System.EventHandler(this.textModulesToolStripMenuItem_DropDownOpening);
//
// dummyTextModuleToolStripMenuItem
//
this.dummyTextModuleToolStripMenuItem.Name = "dummyTextModuleToolStripMenuItem";
resources.ApplyResources(this.dummyTextModuleToolStripMenuItem, "dummyTextModuleToolStripMenuItem");
//
// textModulesSeparator
//
this.textModulesSeparator.Name = "textModulesSeparator";
resources.ApplyResources(this.textModulesSeparator, "textModulesSeparator");
//
// boldToolStripMenuItem
//
resources.ApplyResources(this.boldToolStripMenuItem, "boldToolStripMenuItem");
this.boldToolStripMenuItem.Name = "boldToolStripMenuItem";
this.boldToolStripMenuItem.Click += new System.EventHandler(this.boldToolStripMenuItem_Click);
//
// italicToolStripMenuItem
//
resources.ApplyResources(this.italicToolStripMenuItem, "italicToolStripMenuItem");
this.italicToolStripMenuItem.Name = "italicToolStripMenuItem";
this.italicToolStripMenuItem.Click += new System.EventHandler(this.italicToolStripMenuItem_Click);
//
// underlineToolStripMenuItem
//
resources.ApplyResources(this.underlineToolStripMenuItem, "underlineToolStripMenuItem");
this.underlineToolStripMenuItem.Name = "underlineToolStripMenuItem";
this.underlineToolStripMenuItem.Click += new System.EventHandler(this.underlineToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// cutToolStripMenuItem
//
resources.ApplyResources(this.cutToolStripMenuItem, "cutToolStripMenuItem");
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem");
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
resources.ApplyResources(this.pasteToolStripMenuItem, "pasteToolStripMenuItem");
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// pasteFromMsWordToolStripItem
//
this.pasteFromMsWordToolStripItem.Name = "pasteFromMsWordToolStripItem";
resources.ApplyResources(this.pasteFromMsWordToolStripItem, "pasteFromMsWordToolStripItem");
this.pasteFromMsWordToolStripItem.Click += new System.EventHandler(this.pasteFromMsWordToolStripItem_Click);
//
// pasteAsTextToolStripMenuItem
//
this.pasteAsTextToolStripMenuItem.Name = "pasteAsTextToolStripMenuItem";
resources.ApplyResources(this.pasteAsTextToolStripMenuItem, "pasteAsTextToolStripMenuItem");
this.pasteAsTextToolStripMenuItem.Click += new System.EventHandler(this.pasteAsTextToolStripMenuItem_Click);
//
// deleteToolStripMenuItem
//
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// tableToolStripMenuItem
//
this.tableToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.insertNewTableToolStripMenuItem,
this.toolStripSeparator13,
this.insertRowBeforeCurrentRowToolStripMenuItem,
this.insertColumnBeforeCurrentColumnToolStripMenuItem,
this.toolStripSeparator10,
this.addRowAfterTheLastTableRowToolStripMenuItem,
this.addColumnAfterTheLastTableColumnToolStripMenuItem,
this.toolStripSeparator11,
this.tablePropertiesToolStripMenuItem,
this.rowPropertiesToolStripMenuItem,
this.columnPropertiesToolStripMenuItem,
this.cellPropertiesToolStripMenuItem,
this.toolStripSeparator12,
this.deleteRowToolStripMenuItem,
this.deleteColumnToolStripMenuItem,
this.deleteTableToolStripMenuItem});
resources.ApplyResources(this.tableToolStripMenuItem, "tableToolStripMenuItem");
this.tableToolStripMenuItem.Name = "tableToolStripMenuItem";
//
// insertNewTableToolStripMenuItem
//
resources.ApplyResources(this.insertNewTableToolStripMenuItem, "insertNewTableToolStripMenuItem");
this.insertNewTableToolStripMenuItem.Name = "insertNewTableToolStripMenuItem";
this.insertNewTableToolStripMenuItem.Click += new System.EventHandler(this.insertNewTableToolStripMenuItem_Click);
//
// toolStripSeparator13
//
this.toolStripSeparator13.Name = "toolStripSeparator13";
resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13");
//
// insertRowBeforeCurrentRowToolStripMenuItem
//
resources.ApplyResources(this.insertRowBeforeCurrentRowToolStripMenuItem, "insertRowBeforeCurrentRowToolStripMenuItem");
this.insertRowBeforeCurrentRowToolStripMenuItem.Name = "insertRowBeforeCurrentRowToolStripMenuItem";
this.insertRowBeforeCurrentRowToolStripMenuItem.Click += new System.EventHandler(this.insertRowBeforeCurrentRowToolStripMenuItem_Click);
//
// insertColumnBeforeCurrentColumnToolStripMenuItem
//
resources.ApplyResources(this.insertColumnBeforeCurrentColumnToolStripMenuItem, "insertColumnBeforeCurrentColumnToolStripMenuItem");
this.insertColumnBeforeCurrentColumnToolStripMenuItem.Name = "insertColumnBeforeCurrentColumnToolStripMenuItem";
this.insertColumnBeforeCurrentColumnToolStripMenuItem.Click += new System.EventHandler(this.insertColumnBeforeCurrentColumnToolStripMenuItem_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// addRowAfterTheLastTableRowToolStripMenuItem
//
resources.ApplyResources(this.addRowAfterTheLastTableRowToolStripMenuItem, "addRowAfterTheLastTableRowToolStripMenuItem");
this.addRowAfterTheLastTableRowToolStripMenuItem.Name = "addRowAfterTheLastTableRowToolStripMenuItem";
this.addRowAfterTheLastTableRowToolStripMenuItem.Click += new System.EventHandler(this.addRowAfterTheLastTableRowToolStripMenuItem_Click);
//
// addColumnAfterTheLastTableColumnToolStripMenuItem
//
resources.ApplyResources(this.addColumnAfterTheLastTableColumnToolStripMenuItem, "addColumnAfterTheLastTableColumnToolStripMenuItem");
this.addColumnAfterTheLastTableColumnToolStripMenuItem.Name = "addColumnAfterTheLastTableColumnToolStripMenuItem";
this.addColumnAfterTheLastTableColumnToolStripMenuItem.Click += new System.EventHandler(this.addColumnAfterTheLastTableColumnToolStripMenuItem_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11");
//
// tablePropertiesToolStripMenuItem
//
resources.ApplyResources(this.tablePropertiesToolStripMenuItem, "tablePropertiesToolStripMenuItem");
this.tablePropertiesToolStripMenuItem.Name = "tablePropertiesToolStripMenuItem";
this.tablePropertiesToolStripMenuItem.Click += new System.EventHandler(this.tablePropertiesToolStripMenuItem_Click);
//
// rowPropertiesToolStripMenuItem
//
resources.ApplyResources(this.rowPropertiesToolStripMenuItem, "rowPropertiesToolStripMenuItem");
this.rowPropertiesToolStripMenuItem.Name = "rowPropertiesToolStripMenuItem";
this.rowPropertiesToolStripMenuItem.Click += new System.EventHandler(this.rowPropertiesToolStripMenuItem_Click);
//
// columnPropertiesToolStripMenuItem
//
resources.ApplyResources(this.columnPropertiesToolStripMenuItem, "columnPropertiesToolStripMenuItem");
this.columnPropertiesToolStripMenuItem.Name = "columnPropertiesToolStripMenuItem";
this.columnPropertiesToolStripMenuItem.Click += new System.EventHandler(this.columnPropertiesToolStripMenuItem_Click);
//
// cellPropertiesToolStripMenuItem
//
resources.ApplyResources(this.cellPropertiesToolStripMenuItem, "cellPropertiesToolStripMenuItem");
this.cellPropertiesToolStripMenuItem.Name = "cellPropertiesToolStripMenuItem";
this.cellPropertiesToolStripMenuItem.Click += new System.EventHandler(this.cellPropertiesToolStripMenuItem_Click);
//
// toolStripSeparator12
//
this.toolStripSeparator12.Name = "toolStripSeparator12";
resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12");
//
// deleteRowToolStripMenuItem
//
resources.ApplyResources(this.deleteRowToolStripMenuItem, "deleteRowToolStripMenuItem");
this.deleteRowToolStripMenuItem.Name = "deleteRowToolStripMenuItem";
this.deleteRowToolStripMenuItem.Click += new System.EventHandler(this.deleteRowToolStripMenuItem_Click);
//
// deleteColumnToolStripMenuItem
//
resources.ApplyResources(this.deleteColumnToolStripMenuItem, "deleteColumnToolStripMenuItem");
this.deleteColumnToolStripMenuItem.Name = "deleteColumnToolStripMenuItem";
this.deleteColumnToolStripMenuItem.Click += new System.EventHandler(this.deleteColumnToolStripMenuItem_Click);
//
// deleteTableToolStripMenuItem
//
resources.ApplyResources(this.deleteTableToolStripMenuItem, "deleteTableToolStripMenuItem");
this.deleteTableToolStripMenuItem.Name = "deleteTableToolStripMenuItem";
this.deleteTableToolStripMenuItem.Click += new System.EventHandler(this.deleteTableToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// foreColorToolStripMenuItem
//
this.foreColorToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.foreColorNoneToolStripMenuItem,
this.toolStripSeparator7,
this.foreColor01ToolStripMenuItem,
this.foreColor02ToolStripMenuItem,
this.foreColor03ToolStripMenuItem,
this.foreColor04ToolStripMenuItem,
this.foreColor05ToolStripMenuItem,
this.foreColor06ToolStripMenuItem,
this.foreColor07ToolStripMenuItem,
this.foreColor08ToolStripMenuItem,
this.foreColor09ToolStripMenuItem,
this.foreColor10ToolStripMenuItem});
resources.ApplyResources(this.foreColorToolStripMenuItem, "foreColorToolStripMenuItem");
this.foreColorToolStripMenuItem.Name = "foreColorToolStripMenuItem";
//
// foreColorNoneToolStripMenuItem
//
this.foreColorNoneToolStripMenuItem.Name = "foreColorNoneToolStripMenuItem";
resources.ApplyResources(this.foreColorNoneToolStripMenuItem, "foreColorNoneToolStripMenuItem");
this.foreColorNoneToolStripMenuItem.Click += new System.EventHandler(this.foreColorNoneToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// foreColor01ToolStripMenuItem
//
resources.ApplyResources(this.foreColor01ToolStripMenuItem, "foreColor01ToolStripMenuItem");
this.foreColor01ToolStripMenuItem.Name = "foreColor01ToolStripMenuItem";
this.foreColor01ToolStripMenuItem.Click += new System.EventHandler(this.foreColor01ToolStripMenuItem_Click);
//
// foreColor02ToolStripMenuItem
//
resources.ApplyResources(this.foreColor02ToolStripMenuItem, "foreColor02ToolStripMenuItem");
this.foreColor02ToolStripMenuItem.Name = "foreColor02ToolStripMenuItem";
this.foreColor02ToolStripMenuItem.Click += new System.EventHandler(this.foreColor02ToolStripMenuItem_Click);
//
// foreColor03ToolStripMenuItem
//
resources.ApplyResources(this.foreColor03ToolStripMenuItem, "foreColor03ToolStripMenuItem");
this.foreColor03ToolStripMenuItem.Name = "foreColor03ToolStripMenuItem";
this.foreColor03ToolStripMenuItem.Click += new System.EventHandler(this.foreColor03ToolStripMenuItem_Click);
//
// foreColor04ToolStripMenuItem
//
resources.ApplyResources(this.foreColor04ToolStripMenuItem, "foreColor04ToolStripMenuItem");
this.foreColor04ToolStripMenuItem.Name = "foreColor04ToolStripMenuItem";
this.foreColor04ToolStripMenuItem.Click += new System.EventHandler(this.foreColor04ToolStripMenuItem_Click);
//
// foreColor05ToolStripMenuItem
//
resources.ApplyResources(this.foreColor05ToolStripMenuItem, "foreColor05ToolStripMenuItem");
this.foreColor05ToolStripMenuItem.Name = "foreColor05ToolStripMenuItem";
this.foreColor05ToolStripMenuItem.Click += new System.EventHandler(this.foreColor05ToolStripMenuItem_Click);
//
// foreColor06ToolStripMenuItem
//
resources.ApplyResources(this.foreColor06ToolStripMenuItem, "foreColor06ToolStripMenuItem");
this.foreColor06ToolStripMenuItem.Name = "foreColor06ToolStripMenuItem";
this.foreColor06ToolStripMenuItem.Click += new System.EventHandler(this.foreColor06ToolStripMenuItem_Click);
//
// foreColor07ToolStripMenuItem
//
resources.ApplyResources(this.foreColor07ToolStripMenuItem, "foreColor07ToolStripMenuItem");
this.foreColor07ToolStripMenuItem.Name = "foreColor07ToolStripMenuItem";
this.foreColor07ToolStripMenuItem.Click += new System.EventHandler(this.foreColor07ToolStripMenuItem_Click);
//
// foreColor08ToolStripMenuItem
//
resources.ApplyResources(this.foreColor08ToolStripMenuItem, "foreColor08ToolStripMenuItem");
this.foreColor08ToolStripMenuItem.Name = "foreColor08ToolStripMenuItem";
this.foreColor08ToolStripMenuItem.Click += new System.EventHandler(this.foreColor08ToolStripMenuItem_Click);
//
// foreColor09ToolStripMenuItem
//
resources.ApplyResources(this.foreColor09ToolStripMenuItem, "foreColor09ToolStripMenuItem");
this.foreColor09ToolStripMenuItem.Name = "foreColor09ToolStripMenuItem";
this.foreColor09ToolStripMenuItem.Click += new System.EventHandler(this.foreColor09ToolStripMenuItem_Click);
//
// foreColor10ToolStripMenuItem
//
resources.ApplyResources(this.foreColor10ToolStripMenuItem, "foreColor10ToolStripMenuItem");
this.foreColor10ToolStripMenuItem.Name = "foreColor10ToolStripMenuItem";
this.foreColor10ToolStripMenuItem.Click += new System.EventHandler(this.foreColor10ToolStripMenuItem_Click);
//
// backColorToolStripMenuItem
//
this.backColorToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.BackColorNoneToolStripMenuItem,
this.toolStripSeparator8,
this.BackColor01ToolStripMenuItem,
this.BackColor02ToolStripMenuItem,
this.BackColor03ToolStripMenuItem,
this.BackColor04ToolStripMenuItem,
this.BackColor05ToolStripMenuItem});
resources.ApplyResources(this.backColorToolStripMenuItem, "backColorToolStripMenuItem");
this.backColorToolStripMenuItem.Name = "backColorToolStripMenuItem";
//
// BackColorNoneToolStripMenuItem
//
this.BackColorNoneToolStripMenuItem.Name = "BackColorNoneToolStripMenuItem";
resources.ApplyResources(this.BackColorNoneToolStripMenuItem, "BackColorNoneToolStripMenuItem");
this.BackColorNoneToolStripMenuItem.Click += new System.EventHandler(this.backColorNoneToolStripMenuItem_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// BackColor01ToolStripMenuItem
//
resources.ApplyResources(this.BackColor01ToolStripMenuItem, "BackColor01ToolStripMenuItem");
this.BackColor01ToolStripMenuItem.Name = "BackColor01ToolStripMenuItem";
this.BackColor01ToolStripMenuItem.Click += new System.EventHandler(this.backColor01ToolStripMenuItem_Click);
//
// BackColor02ToolStripMenuItem
//
resources.ApplyResources(this.BackColor02ToolStripMenuItem, "BackColor02ToolStripMenuItem");
this.BackColor02ToolStripMenuItem.Name = "BackColor02ToolStripMenuItem";
this.BackColor02ToolStripMenuItem.Click += new System.EventHandler(this.backColor02ToolStripMenuItem_Click);
//
// BackColor03ToolStripMenuItem
//
resources.ApplyResources(this.BackColor03ToolStripMenuItem, "BackColor03ToolStripMenuItem");
this.BackColor03ToolStripMenuItem.Name = "BackColor03ToolStripMenuItem";
this.BackColor03ToolStripMenuItem.Click += new System.EventHandler(this.backColor03ToolStripMenuItem_Click);
//
// BackColor04ToolStripMenuItem
//
resources.ApplyResources(this.BackColor04ToolStripMenuItem, "BackColor04ToolStripMenuItem");
this.BackColor04ToolStripMenuItem.Name = "BackColor04ToolStripMenuItem";
this.BackColor04ToolStripMenuItem.Click += new System.EventHandler(this.backColor04ToolStripMenuItem_Click);
//
// BackColor05ToolStripMenuItem
//
resources.ApplyResources(this.BackColor05ToolStripMenuItem, "BackColor05ToolStripMenuItem");
this.BackColor05ToolStripMenuItem.Name = "BackColor05ToolStripMenuItem";
this.BackColor05ToolStripMenuItem.Click += new System.EventHandler(this.backColor05ToolStripMenuItem_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// justifyLeftToolStripMenuItem
//
resources.ApplyResources(this.justifyLeftToolStripMenuItem, "justifyLeftToolStripMenuItem");
this.justifyLeftToolStripMenuItem.Name = "justifyLeftToolStripMenuItem";
this.justifyLeftToolStripMenuItem.Click += new System.EventHandler(this.justifyLeftToolStripMenuItem_Click);
//
// justifyCenterToolStripMenuItem
//
resources.ApplyResources(this.justifyCenterToolStripMenuItem, "justifyCenterToolStripMenuItem");
this.justifyCenterToolStripMenuItem.Name = "justifyCenterToolStripMenuItem";
this.justifyCenterToolStripMenuItem.Click += new System.EventHandler(this.justifyCenterToolStripMenuItem_Click);
//
// justifyRightToolStripMenuItem
//
resources.ApplyResources(this.justifyRightToolStripMenuItem, "justifyRightToolStripMenuItem");
this.justifyRightToolStripMenuItem.Name = "justifyRightToolStripMenuItem";
this.justifyRightToolStripMenuItem.Click += new System.EventHandler(this.justifyRightToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// bullettedListToolStripMenuItem
//
resources.ApplyResources(this.bullettedListToolStripMenuItem, "bullettedListToolStripMenuItem");
this.bullettedListToolStripMenuItem.Name = "bullettedListToolStripMenuItem";
this.bullettedListToolStripMenuItem.Click += new System.EventHandler(this.bullettedListToolStripMenuItem_Click);
//
// numberedListToolStripMenuItem
//
resources.ApplyResources(this.numberedListToolStripMenuItem, "numberedListToolStripMenuItem");
this.numberedListToolStripMenuItem.Name = "numberedListToolStripMenuItem";
this.numberedListToolStripMenuItem.Click += new System.EventHandler(this.numberedListToolStripMenuItem_Click);
//
// indentToolStripMenuItem
//
resources.ApplyResources(this.indentToolStripMenuItem, "indentToolStripMenuItem");
this.indentToolStripMenuItem.Name = "indentToolStripMenuItem";
this.indentToolStripMenuItem.Click += new System.EventHandler(this.indentToolStripMenuItem_Click);
//
// outdentToolStripMenuItem
//
resources.ApplyResources(this.outdentToolStripMenuItem, "outdentToolStripMenuItem");
this.outdentToolStripMenuItem.Name = "outdentToolStripMenuItem";
this.outdentToolStripMenuItem.Click += new System.EventHandler(this.outdentToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// hyperLinkToolStripMenuItem
//
resources.ApplyResources(this.hyperLinkToolStripMenuItem, "hyperLinkToolStripMenuItem");
this.hyperLinkToolStripMenuItem.Name = "hyperLinkToolStripMenuItem";
this.hyperLinkToolStripMenuItem.Click += new System.EventHandler(this.hyperLinkToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// removeFormattingToolStripMenuItem
//
resources.ApplyResources(this.removeFormattingToolStripMenuItem, "removeFormattingToolStripMenuItem");
this.removeFormattingToolStripMenuItem.Name = "removeFormattingToolStripMenuItem";
this.removeFormattingToolStripMenuItem.Click += new System.EventHandler(this.removeFormattingToolStripMenuItem_Click);
//
// htmlToolStripMenuItem
//
resources.ApplyResources(this.htmlToolStripMenuItem, "htmlToolStripMenuItem");
this.htmlToolStripMenuItem.Name = "htmlToolStripMenuItem";
this.htmlToolStripMenuItem.Click += new System.EventHandler(this.htmlToolStripMenuItem_Click);
//
// HtmlEditControl
//
this.IsWebBrowserContextMenuEnabled = false;
this.contextMenuStrip.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem boldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem italicToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteAsTextToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem htmlToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem justifyLeftToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem justifyCenterToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem justifyRightToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem bullettedListToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem numberedListToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem outdentToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem hyperLinkToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem foreColorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem backColorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColorNoneToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem foreColor01ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor02ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor03ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor04ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor05ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor06ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor07ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor08ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor09ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem foreColor10ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem BackColorNoneToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem BackColor01ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem BackColor02ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem BackColor03ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem BackColor04ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem BackColor05ToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripMenuItem tableToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem insertRowBeforeCurrentRowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem insertColumnBeforeCurrentColumnToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem addRowAfterTheLastTableRowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addColumnAfterTheLastTableColumnToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripMenuItem tablePropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem rowPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem columnPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cellPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
private System.Windows.Forms.ToolStripMenuItem deleteRowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteColumnToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteTableToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem insertNewTableToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator13;
private System.Windows.Forms.ToolStripMenuItem underlineToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem textModulesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator textModulesSeparator;
private System.Windows.Forms.ToolStripMenuItem dummyTextModuleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteFromMsWordToolStripItem;
private System.Windows.Forms.ToolStripMenuItem removeFormattingToolStripMenuItem;
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace VulkanCore.Khr
{
/// <summary>
/// Opaque handle to a swapchain object.
/// <para>
/// A swapchain object (a.k.a. swapchain) provides the ability to present rendering results to a surface.
/// </para>
/// <para>
/// A swapchain is an abstraction for an array of presentable images that are associated with a
/// surface. The swapchain images are represented by <see cref="Image"/> objects created by the
/// platform. One image (which can be an array image for multiview/stereoscopic-3D surfaces) is
/// displayed at a time, but multiple images can be queued for presentation. An application
/// renders to the image, and then queues the image for presentation to the surface.
/// </para>
/// <para>A native window cannot be associated with more than one swapchain at a time.</para>
/// <para>
/// Further, swapchains cannot be created for native windows that have a non-Vulkan graphics API
/// surface associated with them.
/// </para>
/// </summary>
public unsafe class SwapchainKhr : DisposableHandle<long>
{
internal SwapchainKhr(Device parent, ref SwapchainCreateInfoKhr createInfo, ref AllocationCallbacks? allocator)
{
Parent = parent;
Allocator = allocator;
Format = createInfo.ImageFormat;
long handle;
createInfo.ToNative(out SwapchainCreateInfoKhr.Native nativeCreateInfo);
Result result = vkCreateSwapchainKHR(Parent, &nativeCreateInfo, NativeAllocator, &handle);
nativeCreateInfo.Free();
VulkanException.ThrowForInvalidResult(result);
Handle = handle;
}
internal SwapchainKhr(Device parent, long handle, ref AllocationCallbacks? allocator)
{
Parent = parent;
Allocator = allocator;
Handle = handle;
}
/// <summary>
/// Gets the parent of this resource.
/// </summary>
public Device Parent { get; }
/// <summary>
/// Gets the format.
/// </summary>
public Format Format { get; }
/// <summary>
/// Obtain the array of presentable images associated with a swapchain.
/// </summary>
/// <returns>An array of <see cref="Image"/> objects.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public Image[] GetImages()
{
int swapchainImageCount;
Result result = vkGetSwapchainImagesKHR(Parent, this, &swapchainImageCount, null);
VulkanException.ThrowForInvalidResult(result);
var swapchainImages = stackalloc long[swapchainImageCount];
result = vkGetSwapchainImagesKHR(Parent, this, &swapchainImageCount, swapchainImages);
VulkanException.ThrowForInvalidResult(result);
var images = new Image[swapchainImageCount];
for (int i = 0; i < swapchainImageCount; i++)
images[i] = new Image(Parent, swapchainImages[i], Allocator);
return images;
}
/// <summary>
/// Retrieve the index of the next available presentable image.
/// </summary>
/// <param name="timeout">
/// Indicates how long the function waits, in nanoseconds, if no image is available.
/// <para>
/// If timeout is 0, the command will not block, but will either succeed or throw with <see
/// cref="Result.NotReady"/>. If timeout is -1, the function will not return until an image
/// is acquired from the presentation engine. Other values for timeout will cause the
/// function to return when an image becomes available, or when the specified number of
/// nanoseconds have passed (in which case it will return throw with <see
/// cref="Result.Timeout"/>). An error can also cause the command to return early.
/// </para>
/// </param>
/// <param name="semaphore">
/// <c>null</c> or a semaphore to signal. <paramref name="semaphore"/> and <paramref
/// name="fence"/> must not both be equal to <c>null</c>.
/// </param>
/// <param name="fence">
/// <c>null</c> or a fence to signal. <paramref name="semaphore"/> and <paramref
/// name="fence"/> must not both be equal to <c>null</c>.
/// </param>
/// <returns>The index of the next available presentable image.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public int AcquireNextImage(long timeout = ~0, Semaphore semaphore = null, Fence fence = null)
{
int nextImageIndex;
Result result = vkAcquireNextImageKHR(Parent, this, timeout, semaphore, fence, &nextImageIndex);
VulkanException.ThrowForInvalidResult(result);
return nextImageIndex;
}
/// <summary>
/// Get a swapchain's status. The possible return values should be interpreted as follows:
/// <para>
/// * <see cref="Result.Success"/> - Indicates the presentation engine is presenting the
/// contents of the shared presentable image, as per the swapchain's <see cref="PresentModeKhr"/>
/// </para>
/// <para>
/// * <see cref="Result.SuboptimalKhr"/> - The swapchain no longer matches the surface
/// properties exactly, but the presentation engine is presenting the contents of the
/// shared presentable image, as per the swapchain's <see cref="PresentModeKhr"/>
/// </para>
/// <para>
/// * <see cref="Result.ErrorOutOfDateKhr"/> - The surface has changed in such a way that it
/// is no longer compatible with the swapchain
/// </para>
/// <para>* <see cref="Result.ErrorSurfaceLostKhr"/> - The surface is no longer available</para>
/// </summary>
/// <returns>Status of the swapchain.</returns>
public Result GetStatus()
{
return vkGetSwapchainStatusKHR(this)(Parent, this);
}
internal static SwapchainKhr[] CreateSharedKhr(Device parent, SwapchainCreateInfoKhr[] createInfos,
ref AllocationCallbacks? allocator)
{
int count = createInfos?.Length ?? 0;
var nativeCreateInfos = stackalloc SwapchainCreateInfoKhr.Native[count];
for (int i = 0; i < count; i++)
createInfos[i].ToNative(out nativeCreateInfos[i]);
AllocationCallbacks.Native nativeAllocator;
allocator?.ToNative(&nativeAllocator);
long* handles = stackalloc long[count];
Result result = vkCreateSharedSwapchainsKHR(parent, count, nativeCreateInfos,
allocator.HasValue ? &nativeAllocator : null, handles);
for (int i = 0; i < count; i++)
nativeCreateInfos[i].Free();
VulkanException.ThrowForInvalidResult(result);
var swapchains = new SwapchainKhr[count];
for (int i = 0; i < count; i++)
swapchains[i] = new SwapchainKhr(parent, handles[i], ref allocator);
return swapchains;
}
/// <summary>
/// Destroy a swapchain object.
/// </summary>
public override void Dispose()
{
if (!Disposed) vkDestroySwapchainKHR(Parent, this, NativeAllocator);
base.Dispose();
}
private delegate Result vkCreateSwapchainKHRDelegate(IntPtr device, SwapchainCreateInfoKhr.Native* createInfo, AllocationCallbacks.Native* allocator, long* swapchain);
private static readonly vkCreateSwapchainKHRDelegate vkCreateSwapchainKHR = VulkanLibrary.GetStaticProc<vkCreateSwapchainKHRDelegate>(nameof(vkCreateSwapchainKHR));
private delegate void vkDestroySwapchainKHRDelegate(IntPtr device, long swapchain, AllocationCallbacks.Native* allocator);
private static readonly vkDestroySwapchainKHRDelegate vkDestroySwapchainKHR = VulkanLibrary.GetStaticProc<vkDestroySwapchainKHRDelegate>(nameof(vkDestroySwapchainKHR));
private delegate Result vkGetSwapchainImagesKHRDelegate(IntPtr device, long swapchain, int* swapchainImageCount, long* swapchainImages);
private static readonly vkGetSwapchainImagesKHRDelegate vkGetSwapchainImagesKHR = VulkanLibrary.GetStaticProc<vkGetSwapchainImagesKHRDelegate>(nameof(vkGetSwapchainImagesKHR));
private delegate Result vkAcquireNextImageKHRDelegate(IntPtr device, long swapchain, long timeout, long semaphore, long fence, int* imageIndex);
private static readonly vkAcquireNextImageKHRDelegate vkAcquireNextImageKHR = VulkanLibrary.GetStaticProc<vkAcquireNextImageKHRDelegate>(nameof(vkAcquireNextImageKHR));
private delegate Result vkCreateSharedSwapchainsKHRDelegate(IntPtr device, int swapchainCount, SwapchainCreateInfoKhr.Native* createInfos, AllocationCallbacks.Native* allocator, long* swapchains);
private static readonly vkCreateSharedSwapchainsKHRDelegate vkCreateSharedSwapchainsKHR = VulkanLibrary.GetStaticProc<vkCreateSharedSwapchainsKHRDelegate>(nameof(vkCreateSharedSwapchainsKHR));
private delegate Result vkGetSwapchainStatusKHRDelegate(IntPtr device, long swapchain);
private static vkGetSwapchainStatusKHRDelegate vkGetSwapchainStatusKHR(SwapchainKhr swapchain) => swapchain.Parent.GetProc<vkGetSwapchainStatusKHRDelegate>(nameof(vkGetSwapchainStatusKHR));
}
/// <summary>
/// Structure specifying parameters of a newly created swapchain object.
/// </summary>
public struct SwapchainCreateInfoKhr
{
/// <summary>
/// A bitmask indicating parameters of the swapchain creation.
/// </summary>
public SwapchainCreateFlagsKhr Flags;
/// <summary>
/// The <see cref="SurfaceKhr"/> onto which the swapchain will present images. If the
/// creation succeeds, the swapchain becomes associated with <see cref="SurfaceKhr"/>.
/// </summary>
public long Surface;
/// <summary>
/// The minimum number of presentable images that the application needs.
/// <para>
/// The implementation will either create the swapchain with at least that many images, or it
/// will fail to create the swapchain.
/// </para>
/// </summary>
public int MinImageCount;
/// <summary>
/// A format value specifying the format the swapchain image(s) will be created with.
/// </summary>
public Format ImageFormat;
/// <summary>
/// Color space value specifying the way the swapchain interprets image data.
/// </summary>
public ColorSpaceKhr ImageColorSpace;
/// <summary>
/// The size (in pixels) of the swapchain image(s).
/// <para>
/// The behavior is platform-dependent if the image extent does not match the surface's <see
/// cref="SurfaceCapabilitiesKhr.CurrentExtent"/> as returned by <see cref="PhysicalDeviceExtensions.GetSurfaceCapabilitiesKhr"/>.
/// </para>
/// </summary>
public Extent2D ImageExtent;
/// <summary>
/// The number of views in a multiview/stereo surface.
/// <para>For non-stereoscopic-3D applications, this value is 1.</para>
/// </summary>
public int ImageArrayLayers;
/// <summary>
/// A bitmask describing the intended usage of the (acquired) swapchain images.
/// </summary>
public ImageUsages ImageUsage;
/// <summary>
/// The sharing mode used for the image(s) of the swapchain.
/// </summary>
public SharingMode ImageSharingMode;
/// <summary>
/// Queue family indices having access to the image(s) of the swapchain when <see
/// cref="ImageSharingMode"/> is <see cref="SharingMode.Concurrent"/>.
/// </summary>
public int[] QueueFamilyIndices;
/// <summary>
/// A value describing the transform, relative to the presentation engine's natural
/// orientation, applied to the image content prior to presentation.
/// <para>
/// If it does not match the <see cref="SurfaceCapabilitiesKhr.CurrentTransform"/> value
/// returned by <see cref="PhysicalDeviceExtensions.GetSurfaceCapabilitiesKhr"/>, the
/// presentation engine will transform the image content as part of the presentation operation.
/// </para>
/// </summary>
public SurfaceTransformsKhr PreTransform;
/// <summary>
/// A value indicating the alpha compositing mode to use when this surface is composited
/// together with other surfaces on certain window systems.
/// </summary>
public CompositeAlphasKhr CompositeAlpha;
/// <summary>
/// The presentation mode the swapchain will use.
/// <para>
/// A swapchain's present mode determines how incoming present requests will be processed and
/// queued internally.
/// </para>
/// </summary>
public PresentModeKhr PresentMode;
/// <summary>
/// Indicates whether the Vulkan implementation is allowed to discard rendering operations
/// that affect regions of the surface that are not visible.
/// <para>
/// If set to <c>true</c>, the presentable images associated with the swapchain may not own
/// all of their pixels. Pixels in the presentable images that correspond to regions of the
/// target surface obscured by another window on the desktop, or subject to some other
/// clipping mechanism will have undefined content when read back. Pixel shaders may not
/// execute for these pixels, and thus any side effects they would have had will not occur.
/// </para>
/// <para>
/// <c>true</c> value does not guarantee any clipping will occur, but allows more optimal
/// presentation methods to be used on some platforms.
/// </para>
/// <para>
/// If set to <c>false</c>, presentable images associated with the swapchain will own all of
/// the pixels they contain.
/// </para>
/// </summary>
public Bool Clipped;
/// <summary>
/// Is <c>null</c>, or the existing non-retired swapchain currently associated with <c>Surface</c>.
/// <para>
/// Providing a valid <see cref="OldSwapchain"/> may aid in the resource reuse, and also
/// allows the application to still present any images that are already acquired from it.
/// </para>
/// </summary>
public SwapchainKhr OldSwapchain;
/// <summary>
/// Initializes a new instance of the <see cref="SwapchainCreateInfoKhr"/> structure.
/// </summary>
/// <param name="surface">
/// The <see cref="SurfaceKhr"/> that the swapchain will present images to.
/// </param>
/// <param name="imageFormat">A format that is valid for swapchains on the specified surface.</param>
/// <param name="imageExtent">
/// The size (in pixels) of the swapchain.
/// <para>
/// Behavior is platform-dependent when the image extent does not match the surface's <see
/// cref="SurfaceCapabilitiesKhr.CurrentExtent"/> as returned by <see cref="PhysicalDeviceExtensions.GetSurfaceCapabilitiesKhr"/>.
/// </para>
/// </param>
/// <param name="minImageCount">
/// The minimum number of presentable images that the application needs. The platform will
/// either create the swapchain with at least that many images, or will fail to create the swapchain.
/// </param>
/// <param name="imageColorSpace">Color space value specifying the way the swapchain interprets image data.</param>
/// <param name="imageArrayLayers">
/// The number of views in a multiview/stereo surface.
/// <para>For non-stereoscopic-3D applications, this value is 1.</para>
/// </param>
/// <param name="imageUsage">A bitmask describing the intended usage of the (acquired) swapchain images.</param>
/// <param name="imageSharingMode">The sharing mode used for the image(s) of the swapchain.</param>
/// <param name="queueFamilyIndices">
/// Queue family indices having access to the image(s) of the swapchain when <see
/// cref="ImageSharingMode"/> is <see cref="SharingMode.Concurrent"/>.
/// </param>
/// <param name="preTransform">
/// A value describing the transform, relative to the presentation engine's natural
/// orientation, applied to the image content prior to presentation.
/// <para>
/// If it does not match the <see cref="SurfaceCapabilitiesKhr.CurrentTransform"/> value
/// returned by <see cref="PhysicalDeviceExtensions.GetSurfaceCapabilitiesKhr"/>, the
/// presentation engine will transform the image content as part of the presentation operation.
/// </para>
/// </param>
/// <param name="compositeAlpha">
/// A bitmask indicating the alpha compositing mode to use when this surface is composited
/// together with other surfaces on certain window systems.
/// </param>
/// <param name="presentMode">
/// The presentation mode the swapchain will use.
/// <para>
/// A swapchain's present mode determines how incoming present requests will be processed and
/// queued internally.
/// </para>
/// </param>
/// <param name="clipped">
/// Indicates whether the Vulkan implementation is allowed to discard rendering operations
/// that affect regions of the surface which are not visible.</param>
/// <param name="oldSwapchain">Existing swapchain to replace, if any.</param>
public SwapchainCreateInfoKhr(
SurfaceKhr surface,
Format imageFormat,
Extent2D imageExtent,
int minImageCount = 2,
ColorSpaceKhr imageColorSpace = ColorSpaceKhr.SRgbNonlinear,
int imageArrayLayers = 1,
ImageUsages imageUsage = ImageUsages.ColorAttachment | ImageUsages.TransferDst,
SharingMode imageSharingMode = SharingMode.Exclusive,
int[] queueFamilyIndices = null,
SurfaceTransformsKhr preTransform = SurfaceTransformsKhr.Identity,
CompositeAlphasKhr compositeAlpha = CompositeAlphasKhr.Opaque,
PresentModeKhr presentMode = PresentModeKhr.Fifo,
bool clipped = true,
SwapchainKhr oldSwapchain = null)
{
Flags = SwapchainCreateFlagsKhr.None;
Surface = surface;
MinImageCount = minImageCount;
ImageFormat = imageFormat;
ImageColorSpace = imageColorSpace;
ImageExtent = imageExtent;
ImageArrayLayers = imageArrayLayers;
ImageUsage = imageUsage;
ImageSharingMode = imageSharingMode;
QueueFamilyIndices = queueFamilyIndices;
PreTransform = preTransform;
CompositeAlpha = compositeAlpha;
PresentMode = presentMode;
Clipped = clipped;
OldSwapchain = oldSwapchain;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public SwapchainCreateFlagsKhr Flags;
public long Surface;
public int MinImageCount;
public Format ImageFormat;
public ColorSpaceKhr ImageColorSpace;
public Extent2D ImageExtent;
public int ImageArrayLayers;
public ImageUsages ImageUsage;
public SharingMode ImageSharingMode;
public int QueueFamilyIndexCount;
public IntPtr QueueFamilyIndices;
public SurfaceTransformsKhr PreTransform;
public CompositeAlphasKhr CompositeAlpha;
public PresentModeKhr PresentMode;
public Bool Clipped;
public long OldSwapchain;
public void Free()
{
Interop.Free(QueueFamilyIndices);
}
}
internal void ToNative(out Native native)
{
native.Type = StructureType.SwapchainCreateInfoKhr;
native.Next = IntPtr.Zero;
native.Flags = Flags;
native.Surface = Surface;
native.MinImageCount = MinImageCount;
native.ImageFormat = ImageFormat;
native.ImageColorSpace = ImageColorSpace;
native.ImageExtent = ImageExtent;
native.ImageArrayLayers = ImageArrayLayers;
native.ImageUsage = ImageUsage;
native.ImageSharingMode = ImageSharingMode;
native.QueueFamilyIndexCount = QueueFamilyIndices?.Length ?? 0;
native.QueueFamilyIndices = Interop.Struct.AllocToPointer(QueueFamilyIndices);
native.PreTransform = PreTransform;
native.CompositeAlpha = CompositeAlpha;
native.PresentMode = PresentMode;
native.Clipped = Clipped;
native.OldSwapchain = OldSwapchain;
}
}
/// <summary>
/// Bitmask controlling swapchain creation.
/// </summary>
[Flags]
public enum SwapchainCreateFlagsKhr
{
/// <summary>
/// No flags.
/// </summary>
None = 0
}
/// <summary>
/// Supported color space of the presentation engine.
/// </summary>
public enum ColorSpaceKhr
{
/// <summary>
/// Indicates support for the sRGB color space.
/// </summary>
SRgbNonlinear = 0,
/// <summary>
/// Indicates support for the Display-P3 color space and applies an sRGB-like transfer function.
/// </summary>
DisplayP3NonlinearExt = 1000104001,
/// <summary>
/// Indicates support for the extended sRGB color space and applies a linear transfer function.
/// </summary>
ExtendedSRgbLinearExt = 1000104002,
/// <summary>
/// Indicates support for the DCI-P3 color space and applies a linear OETF.
/// </summary>
DciP3LinearExt = 1000104003,
/// <summary>
/// Indicates support for the DCI-P3 color space and applies the Gamma 2.6 OETF.
/// </summary>
DciP3NonlinearExt = 1000104004,
/// <summary>
/// Indicates support for the BT709 color space and applies a linear OETF.
/// </summary>
BT709LinearExt = 1000104005,
/// <summary>
/// Indicates support for the BT709 color space and applies the SMPTE 170M OETF.
/// </summary>
BT709NonlinearExt = 1000104006,
/// <summary>
/// Indicates support for the BT2020 color space and applies a linear OETF.
/// </summary>
BT2020LinearExt = 1000104007,
/// <summary>
/// Indicates support for HDR10 (BT2020 color) space and applies the SMPTE ST2084 Perceptual
/// Quantizer (PQ) OETF.
/// </summary>
Hdr10ST2084Ext = 1000104008,
/// <summary>
/// Indicates support for Dolby Vision (BT2020 color space), proprietary encoding, and
/// applies the SMPTE ST2084 OETF.
/// </summary>
DolbyVisionExt = 1000104009,
/// <summary>
/// Indicates support for HDR10 (BT2020 color space) and applies the Hybrid Log Gamma (HLG) OETF.
/// </summary>
Hdr10HlgExt = 1000104010,
/// <summary>
/// Indicates support for the AdobeRGB color space and applies a linear OETF.
/// </summary>
AdobeRgbLinearExt = 1000104011,
/// <summary>
/// Indicates support for the AdobeRGB color space and applies the Gamma 2.2 OETF.
/// </summary>
AdobeRgbNonlinearExt = 1000104012,
/// <summary>
/// Indicates that color components are used "as is". This is intended to allow application
/// to supply data for color spaces not described here.
/// </summary>
PassThroughExt = 1000104013,
/// <summary>
/// Indicates support for the extended sRGB color space and applies an sRGB transfer function.
/// </summary>
ExtendedSRgbNonlinearExt = 1000104014
}
/// <summary>
/// Presentation transforms supported on a device.
/// </summary>
[Flags]
public enum SurfaceTransformsKhr
{
/// <summary>
/// Indicates that image content is presented without being transformed.
/// </summary>
Identity = 1 << 0,
/// <summary>
/// Indicates that image content is rotated 90 degrees clockwise.
/// </summary>
Rotate90 = 1 << 1,
/// <summary>
/// Indicates that image content is rotated 180 degrees clockwise.
/// </summary>
Rotate180 = 1 << 2,
/// <summary>
/// Indicates that image content is rotated 270 degrees clockwise.
/// </summary>
Rotate270 = 1 << 3,
/// <summary>
/// Indicates that image content is mirrored horizontally.
/// </summary>
HorizontalMirror = 1 << 4,
/// <summary>
/// Indicates that image content is mirrored horizontally, then rotated 90 degrees clockwise.
/// </summary>
HorizontalMirrorRotate90 = 1 << 5,
/// <summary>
/// Indicates that image content is mirrored horizontally, then rotated 180 degrees clockwise.
/// </summary>
HorizontalMirrorRotate180 = 1 << 6,
/// <summary>
/// Indicates that image content is mirrored horizontally, then rotated 270 degrees clockwise.
/// </summary>
HorizontalMirrorRotate270 = 1 << 7,
/// <summary>
/// Indicates that presentation transform is not specified, and is instead determined by
/// platform-specific considerations and mechanisms outside Vulkan.
/// </summary>
Inherit = 1 << 8
}
/// <summary>
/// Alpha compositing modes supported on a device.
/// </summary>
[Flags]
public enum CompositeAlphasKhr
{
/// <summary>
/// The alpha channel, if it exists, of the images is ignored in the compositing process.
/// Instead, the image is treated as if it has a constant alpha of 1.0.
/// </summary>
Opaque = 1 << 0,
/// <summary>
/// The alpha channel, if it exists, of the images is respected in the compositing process.
/// The non-alpha channels of the image are expected to already be multiplied by the alpha
/// channel by the application.
/// </summary>
PreMultiplied = 1 << 1,
/// <summary>
/// The alpha channel, if it exists, of the images is respected in the compositing process.
/// The non-alpha channels of the image are not expected to already be multiplied by the
/// alpha channel by the application; instead, the compositor will multiply the non-alpha
/// channels of the image by the alpha channel during compositing.
/// </summary>
PostMultiplied = 1 << 2,
/// <summary>
/// The way in which the presentation engine treats the alpha channel in the images is
/// unknown to the Vulkan API. Instead, the application is responsible for setting the
/// composite alpha blending mode using native window system commands. If the application
/// does not set the blending mode using native window system commands, then a
/// platform-specific default will be used.
/// </summary>
Inherit = 1 << 3
}
/// <summary>
/// Presentation mode supported for a surface.
/// </summary>
public enum PresentModeKhr
{
/// <summary>
/// Indicates that the presentation engine does not wait for a vertical blanking period to
/// update the current image, meaning this mode may result in visible tearing. No internal
/// queuing of presentation requests is needed, as the requests are applied immediately.
/// </summary>
Immediate = 0,
/// <summary>
/// Indicates that the presentation engine waits for the next vertical blanking period to
/// update the current image. Tearing cannot be observed. An internal single-entry queue is
/// used to hold pending presentation requests. If the queue is full when a new presentation
/// request is received, the new request replaces the existing entry, and any images
/// associated with the prior entry become available for re-use by the application. One
/// request is removed from the queue and processed during each vertical blanking period in
/// which the queue is non-empty.
/// </summary>
Mailbox = 1,
/// <summary>
/// Indicates that the presentation engine waits for the next vertical blanking period to
/// update the current image. Tearing cannot be observed. An internal queue is used to hold
/// pending presentation requests. New requests are appended to the end of the queue, and one
/// request is removed from the beginning of the queue and processed during each vertical
/// blanking period in which the queue is non-empty. This is the only value of presentMode
/// that is required: to be supported.
/// </summary>
Fifo = 2,
/// <summary>
/// Indicates that the presentation engine generally waits for the next vertical blanking
/// period to update the current image. If a vertical blanking period has already passed
/// since the last update of the current image then the presentation engine does not wait for
/// another vertical blanking period for the update, meaning this mode may result in visible
/// tearing in this case. This mode is useful for reducing visual stutter with an application
/// that will mostly present a new image before the next vertical blanking period, but may
/// occasionally be late, and present a new image just after the next vertical blanking
/// period. An internal queue is used to hold pending presentation requests. New requests are
/// appended to the end of the queue, and one request is removed from the beginning of the
/// queue and processed during or after each vertical blanking period in which the queue is non-empty.
/// </summary>
FifoRelaxed = 3,
/// <summary>
/// Indicates that the presentation engine and application have concurrent access to a single
/// image, which is referred to as a shared presentable image. The presentation engine is
/// only required to update the current image after a new presentation request is received.
/// Therefore the application must make a presentation request whenever an update is
/// required. However, the presentation engine may update the current image at any point,
/// meaning this mode may result in visible tearing.
/// </summary>
SharedDemandRefreshKhr = 1000111000,
/// <summary>
/// Indicates that the presentation engine and application have concurrent access to a single
/// image, which is referred to as a shared presentable image. The presentation engine
/// periodically updates the current image on its regular refresh cycle. The application is
/// only required to make one initial presentation request, after which the presentation
/// engine must update the current image without any need for further presentation requests.
/// The application can indicate the image contents have been updated by making a
/// presentation request, but this does not guarantee the timing of when it will be updated.
/// This mode may result in visible tearing if rendering to the image is not timed correctly.
/// </summary>
SharedContinuousRefreshKhr = 1000111001
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Collections;
using System.Globalization;
using System.Security.Cryptography;
using OpenSource.Utilities;
namespace OpenSource.UPnP
{
public class MiniWebServerException : Exception
{
public MiniWebServerException(String x) : base(x) { }
}
/// <summary>
/// A generic Web Server
/// </summary>
public sealed class MiniWebServer
{
public bool IdleTimeout = true;
private LifeTimeMonitor KeepAliveTimer = new LifeTimeMonitor();
private LifeTimeMonitor SessionTimer = new LifeTimeMonitor();
private Hashtable SessionTable = new Hashtable();
private IPEndPoint endpoint_local;
public delegate void NewSessionHandler(MiniWebServer sender, HTTPSession session);
private WeakEvent OnSessionEvent = new WeakEvent();
/// <summary>
/// Triggered when a new session is created
/// </summary>
public event NewSessionHandler OnSession
{
add { OnSessionEvent.Register(value); }
remove { OnSessionEvent.UnRegister(value); }
}
public delegate void HTTPReceiveHandler(HTTPMessage msg, HTTPSession WebSession);
private WeakEvent OnReceiveEvent = new WeakEvent();
/// <summary>
/// This is triggered when an HTTP packet is received
/// </summary>
public event HTTPReceiveHandler OnReceive
{
add { OnReceiveEvent.Register(value); }
remove { OnReceiveEvent.UnRegister(value); }
}
private WeakEvent OnHeaderEvent = new WeakEvent();
/// <summary>
/// Triggered when an HTTP Header is received
/// </summary>
public event HTTPReceiveHandler OnHeader
{
add { OnHeaderEvent.Register(value); }
remove { OnHeaderEvent.UnRegister(value); }
}
/// <summary>
/// Instantiates a new MiniWebServer listenting on the given EndPoint
/// </summary>
/// <param name="local">IPEndPoint to listen on</param>
public MiniWebServer(IPEndPoint local)
{
OpenSource.Utilities.InstanceTracker.Add(this);
SessionTimer.OnExpired += new LifeTimeMonitor.LifeTimeHandler(SessionTimerSink);
KeepAliveTimer.OnExpired += new LifeTimeMonitor.LifeTimeHandler(KeepAliveSink);
endpoint_local = local;
MainSocket = new Socket(local.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
MainSocket.Bind(local);
if (MainSocket.LocalEndPoint != null) endpoint_local = (IPEndPoint)MainSocket.LocalEndPoint;
MainSocket.Listen(25);
MainSocket.BeginAccept(new AsyncCallback(Accept), null);
KeepAliveTimer.Add(false, 7);
}
~MiniWebServer()
{
Dispose();
}
private void SessionTimerSink(LifeTimeMonitor sender, object obj)
{
HTTPSession s = (HTTPSession)obj;
s.Close();
}
private void KeepAliveSink(LifeTimeMonitor sender, object obj)
{
if (IdleTimeout == false) return;
ArrayList RemoveList = new ArrayList();
lock (SessionTable)
{
IDictionaryEnumerator en = SessionTable.GetEnumerator();
while (en.MoveNext())
{
if (((HTTPSession)en.Value).Monitor.IsTimeout())
{
RemoveList.Add(en.Value);
}
}
}
foreach (HTTPSession HS in RemoveList)
{
HS.Close();
}
KeepAliveTimer.Add(false, 7);
}
public void Dispose()
{
MainSocket.Close();
}
private void HandleHeader(HTTPSession sender, HTTPMessage Header, Stream StreamObject)
{
SessionTimer.Remove(sender);
OnHeaderEvent.Fire(Header, sender);
}
private void HandleRequest(HTTPSession WebSession, HTTPMessage request)
{
OnReceiveEvent.Fire(request, WebSession);
}
private void CloseSink(HTTPSession s)
{
lock (SessionTable)
{
SessionTable.Remove(s);
}
}
private void Accept(IAsyncResult result)
{
HTTPSession WebSession = null;
try
{
Socket AcceptedSocket = MainSocket.EndAccept(result);
lock (SessionTable)
{
WebSession = new HTTPSession(this.LocalIPEndPoint, AcceptedSocket);
WebSession.OnClosed += new HTTPSession.SessionHandler(CloseSink);
WebSession.OnHeader += new HTTPSession.ReceiveHeaderHandler(HandleHeader);
WebSession.OnReceive += new HTTPSession.ReceiveHandler(HandleRequest);
SessionTable[WebSession] = WebSession;
}
SessionTimer.Add(WebSession, 3);
OnSessionEvent.Fire(this, WebSession);
WebSession.StartReading();
}
catch (Exception err)
{
if (err.GetType() != typeof(System.ObjectDisposedException))
{
// Error
OpenSource.Utilities.EventLogger.Log(err);
}
}
try
{
MainSocket.BeginAccept(new AsyncCallback(Accept), null);
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
// Socket was closed
}
}
public IPEndPoint LocalIPEndPoint
{
get
{
return (endpoint_local);
}
}
private Socket MainSocket;
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - [email protected]
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using MimeKit;
using MimeKit.Cryptography;
using MailKit;
using MailKit.Net.Pop3;
using HtmlAgilityPack;
using Magix.Core;
namespace Magix.email
{
/*
* email pop3 helper
*/
internal class Pop3Helper
{
/*
* returns message count from pop3 server
*/
internal static int GetMessageCount(Core.Node ip, Core.Node dp)
{
string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false);
int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false);
bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false);
string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false);
string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false);
using (Pop3Client client = new Pop3Client())
{
client.Connect(host, port, implicitSsl);
client.AuthenticationMechanisms.Remove("XOAUTH2");
if (!string.IsNullOrEmpty(username))
client.Authenticate(username, password);
int retVal = client.GetMessageCount();
client.Disconnect(true);
return retVal;
}
}
/*
* returns messages from pop3 server
*/
internal static void GetMessages(
Node pars,
Node ip,
Node dp,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory)
{
string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false);
int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false);
bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false);
string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false);
string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false);
Node exeNode = null;
if (ip.Contains("code"))
exeNode = ip["code"];
using (Pop3Client client = new Pop3Client())
{
client.Connect(host, port, implicitSsl);
client.AuthenticationMechanisms.Remove("XOAUTH2");
if (!string.IsNullOrEmpty(username))
client.Authenticate(username, password);
try
{
RetrieveMessagesFromServer(
pars,
dp,
ip,
basePath,
attachmentDirectory,
linkedAttachmentDirectory,
exeNode,
client);
}
finally
{
if (client.IsConnected)
client.Disconnect(true);
}
}
}
/*
* retrieves messages from pop3 server
*/
private static void RetrieveMessagesFromServer(
Node pars,
Node dp,
Node ip,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory,
Node exeNode,
Pop3Client client)
{
int serverCount = client.GetMessageCount();
int count = Expressions.GetExpressionValue<int>(ip.GetValue("count", serverCount.ToString()), dp, ip, false);
count = Math.Min(serverCount, count);
bool delete = Expressions.GetExpressionValue<bool>(ip.GetValue("delete", "false"), dp, ip, false);
for (int idxMsg = 0; idxMsg < count; idxMsg++)
{
MimeMessage msg = client.GetMessage(idxMsg);
HandleMessage(
pars,
ip,
basePath,
attachmentDirectory,
linkedAttachmentDirectory,
exeNode,
idxMsg,
msg);
if (delete)
client.DeleteMessage(idxMsg);
}
}
/*
* handles one message from server
*/
private static void HandleMessage(
Node pars,
Node ip,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory,
Node exeNode,
int idxMsg,
MimeMessage msg)
{
if (exeNode == null)
{
// returning messages back to caller as a list of emails
BuildMessage(msg, ip["values"]["msg_" + idxMsg], basePath, attachmentDirectory, linkedAttachmentDirectory);
}
else
{
HandleMessageInCallback(
pars,
basePath,
attachmentDirectory,
linkedAttachmentDirectory,
exeNode,
msg);
}
}
/*
* handles message by callback
*/
private static void HandleMessageInCallback(
Node pars,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory,
Node exeNode,
MimeMessage msg)
{
// we have a code callback
Node callbackNode = exeNode.Clone();
BuildMessage(msg, exeNode["_message"], basePath, attachmentDirectory, linkedAttachmentDirectory);
pars["_ip"].Value = exeNode;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Pop3Helper),
"magix.execute",
pars);
exeNode.Clear();
exeNode.AddRange(callbackNode);
}
/*
* puts a message into a node for returning back to client
*/
private static void BuildMessage(
MimeMessage msg,
Node node,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory)
{
ExtractHeaders(msg, node);
ExtractBody(new MimeEntity[] { msg.Body }, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory);
}
/*
* extract headers from email and put into node
*/
private static void ExtractHeaders(MimeMessage msg, Node node)
{
GetAddress(msg.Sender, "sender", node);
GetAddress(msg.From[0], "from", node);
if (msg.ReplyTo.Count > 0)
GetAddress(msg.ReplyTo[0], "reply-to", node);
foreach (InternetAddress idxAdr in msg.To)
GetAddress(idxAdr, "", node["to"]);
foreach (InternetAddress idxAdr in msg.Cc)
GetAddress(idxAdr, "", node["cc"]);
node["date"].Value = msg.Date.DateTime;
if (!string.IsNullOrEmpty(msg.InReplyTo))
node["in-reply-to"].Value = msg.InReplyTo;
node["message-id"].Value = msg.MessageId;
node["subject"].Value = msg.Subject ?? "";
node["download-date"].Value = DateTime.Now;
}
/*
* extracts body parts from message and put into node
*/
private static void ExtractBody(
IEnumerable<MimeEntity> entities,
Node node,
bool skipSignature,
MimeMessage msg,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory)
{
foreach (MimeEntity idxBody in entities)
{
if (idxBody is TextPart)
{
TextPart tp = idxBody as TextPart;
if (idxBody.ContentType.MediaType == "text")
{
if (idxBody.ContentType.MediaSubtype == "plain")
{
node["body"]["plain"].Value = tp.Text;
}
else if (idxBody.ContentType.MediaSubtype == "html")
{
node["body"]["html"].Value = CleanHtml(tp.Text);
}
}
}
else if (idxBody is ApplicationPkcs7Mime)
{
ApplicationPkcs7Mime pkcs7 = idxBody as ApplicationPkcs7Mime;
if (pkcs7.SecureMimeType == SecureMimeType.EnvelopedData)
{
try
{
MimeEntity entity = pkcs7.Decrypt();
ExtractBody(new MimeEntity[] { entity }, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory);
node["encrypted"].Value = true;
}
catch (Exception err)
{
// couldn't decrypt
node["body"]["plain"].Value = "couldn't decrypt message, exceptions was; '" + err.Message + "'";
node["encrypted"].Value = true;
}
}
}
else if (!skipSignature && idxBody is MultipartSigned)
{
MultipartSigned signed = idxBody as MultipartSigned;
bool valid = false;
foreach (IDigitalSignature signature in signed.Verify())
{
valid = signature.Verify();
if (!valid)
break;
}
node["signed"].Value = valid;
ExtractBody(new MimeEntity[] { signed }, node, true, msg, basePath, attachmentDirectory, linkedAttachmentDirectory);
}
else if (idxBody is Multipart)
{
Multipart mp = idxBody as Multipart;
ExtractBody(mp, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory);
}
else if (idxBody is MimePart)
{
// this is an attachment
ExtractAttachments(idxBody as MimePart, msg, node, basePath, attachmentDirectory, linkedAttachmentDirectory);
}
}
}
/*
* cleans up html from email
*/
private static string CleanHtml(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
doc.DocumentNode.Descendants()
.Where(n => n.Name == "script" || n.Name == "style" || n.Name == "#comment")
.ToList()
.ForEach(n => n.Remove());
HtmlNode el = doc.DocumentNode.SelectSingleNode("//body");
if (el != null)
return el.InnerHtml;
else
return doc.DocumentNode.InnerHtml;
}
/*
* extracts attachments from message
*/
private static void ExtractAttachments(
MimePart entity,
MimeMessage msg,
Node node,
string basePath,
string attachmentDirectory,
string linkedAttachmentDirectory)
{
if (entity is ApplicationPkcs7Mime)
return; // don't bother about p7m attachments
string fileName;
if (entity.Headers.Contains("Content-Location"))
{
// this is a linked resource, replacing references inside html with local filename
fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName;
if (node.Contains("body") && node["body"].ContainsValue("html"))
node["body"]["html"].Value =
node["body"]["html"].Get<string>().Replace(entity.Headers["Content-Location"], fileName);
}
else if (entity.Headers.Contains("Content-ID"))
{
fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName;
string contentId = entity.Headers["Content-ID"].Trim('<').Trim('>');
if (node.Contains("body") && node["body"].ContainsValue("html"))
node["body"]["html"].Value =
node["body"]["html"].Get<string>().Replace("cid:" + contentId, fileName);
}
else
{
fileName = attachmentDirectory + msg.MessageId + "_" + entity.FileName;
Node attNode = new Node("", entity.FileName ?? "");
attNode["local-file-name"].Value = fileName;
node["attachments"].Add(attNode);
}
using (Stream stream = File.Create(basePath + fileName))
{
entity.ContentObject.DecodeTo(stream);
}
}
/*
* puts in an email address into the given node
*/
private static void GetAddress(InternetAddress adr, string field, Node node)
{
if (adr == null || !(adr is MailboxAddress))
return;
MailboxAddress mailboxAdr = adr as MailboxAddress;
Node nNode = new Node(field, mailboxAdr.Address);
if (!string.IsNullOrEmpty(mailboxAdr.Name))
nNode.Add("display-name", mailboxAdr.Name);
node.Add(nNode);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Subject Classes
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SCL : EduHubEntity
{
#region Navigation Property Cache
private TH Cache_QUILT_TH;
private SU Cache_SUBJECT_SU;
private SF Cache_TEACHER01_SF;
private SF Cache_TEACHER02_SF;
private SM Cache_ROOM01_SM;
private SM Cache_ROOM02_SM;
private SCI Cache_CAMPUS_SCI;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<TXAS> Cache_SCLKEY_TXAS_SCL_LINK;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Class code
/// [Uppercase Alphanumeric (17)]
/// </summary>
public string SCLKEY { get; internal set; }
/// <summary>
/// Applicable quilt
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string QUILT { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJECT { get; internal set; }
/// <summary>
/// Class number
/// </summary>
public short? CLASS { get; internal set; }
/// <summary>
/// Teachers
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string TEACHER01 { get; internal set; }
/// <summary>
/// Teachers
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string TEACHER02 { get; internal set; }
/// <summary>
/// Rooms
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string ROOM01 { get; internal set; }
/// <summary>
/// Rooms
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string ROOM02 { get; internal set; }
/// <summary>
/// Number of sessions per timetable cycle
/// </summary>
public short? FREQUENCY { get; internal set; }
/// <summary>
/// Report print flags
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PRINT_FLAGS01 { get; internal set; }
/// <summary>
/// Report print flags
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PRINT_FLAGS02 { get; internal set; }
/// <summary>
/// Report print flags
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PRINT_FLAGS03 { get; internal set; }
/// <summary>
/// Will period absences be recorded (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PERIOD_ABSENCES { get; internal set; }
/// <summary>
/// Campus where the class is held
/// </summary>
public int? CAMPUS { get; internal set; }
/// <summary>
/// Optional alias name eg 7A Eng, 7B Maths
/// [Alphanumeric (10)]
/// </summary>
public string ALIAS { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// TH (Timetable Quilt Headers) related entity by [SCL.QUILT]->[TH.THKEY]
/// Applicable quilt
/// </summary>
public TH QUILT_TH
{
get
{
if (QUILT == null)
{
return null;
}
if (Cache_QUILT_TH == null)
{
Cache_QUILT_TH = Context.TH.FindByTHKEY(QUILT);
}
return Cache_QUILT_TH;
}
}
/// <summary>
/// SU (Subjects) related entity by [SCL.SUBJECT]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJECT_SU
{
get
{
if (SUBJECT == null)
{
return null;
}
if (Cache_SUBJECT_SU == null)
{
Cache_SUBJECT_SU = Context.SU.FindBySUKEY(SUBJECT);
}
return Cache_SUBJECT_SU;
}
}
/// <summary>
/// SF (Staff) related entity by [SCL.TEACHER01]->[SF.SFKEY]
/// Teachers
/// </summary>
public SF TEACHER01_SF
{
get
{
if (TEACHER01 == null)
{
return null;
}
if (Cache_TEACHER01_SF == null)
{
Cache_TEACHER01_SF = Context.SF.FindBySFKEY(TEACHER01);
}
return Cache_TEACHER01_SF;
}
}
/// <summary>
/// SF (Staff) related entity by [SCL.TEACHER02]->[SF.SFKEY]
/// Teachers
/// </summary>
public SF TEACHER02_SF
{
get
{
if (TEACHER02 == null)
{
return null;
}
if (Cache_TEACHER02_SF == null)
{
Cache_TEACHER02_SF = Context.SF.FindBySFKEY(TEACHER02);
}
return Cache_TEACHER02_SF;
}
}
/// <summary>
/// SM (Rooms) related entity by [SCL.ROOM01]->[SM.ROOM]
/// Rooms
/// </summary>
public SM ROOM01_SM
{
get
{
if (ROOM01 == null)
{
return null;
}
if (Cache_ROOM01_SM == null)
{
Cache_ROOM01_SM = Context.SM.FindByROOM(ROOM01);
}
return Cache_ROOM01_SM;
}
}
/// <summary>
/// SM (Rooms) related entity by [SCL.ROOM02]->[SM.ROOM]
/// Rooms
/// </summary>
public SM ROOM02_SM
{
get
{
if (ROOM02 == null)
{
return null;
}
if (Cache_ROOM02_SM == null)
{
Cache_ROOM02_SM = Context.SM.FindByROOM(ROOM02);
}
return Cache_ROOM02_SM;
}
}
/// <summary>
/// SCI (School Information) related entity by [SCL.CAMPUS]->[SCI.SCIKEY]
/// Campus where the class is held
/// </summary>
public SCI CAMPUS_SCI
{
get
{
if (CAMPUS == null)
{
return null;
}
if (Cache_CAMPUS_SCI == null)
{
Cache_CAMPUS_SCI = Context.SCI.FindBySCIKEY(CAMPUS.Value);
}
return Cache_CAMPUS_SCI;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// TXAS (Actual Sessions) related entities by [SCL.SCLKEY]->[TXAS.SCL_LINK]
/// Class code
/// </summary>
public IReadOnlyList<TXAS> SCLKEY_TXAS_SCL_LINK
{
get
{
if (Cache_SCLKEY_TXAS_SCL_LINK == null &&
!Context.TXAS.TryFindBySCL_LINK(SCLKEY, out Cache_SCLKEY_TXAS_SCL_LINK))
{
Cache_SCLKEY_TXAS_SCL_LINK = new List<TXAS>().AsReadOnly();
}
return Cache_SCLKEY_TXAS_SCL_LINK;
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics.Containers;
using osu.Game.IO.Archives;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Replays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Scoring.Legacy;
using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osu.Game.Users;
namespace osu.Game.Screens.Play
{
[Cached]
public class Player : ScreenWithBeatmapBackground
{
public override bool AllowBackButton => false; // handled by HoldForMenuButton
protected override UserActivity InitialActivity => new UserActivity.SoloGame(Beatmap.Value.BeatmapInfo, Ruleset.Value);
public override float BackgroundParallaxAmount => 0.1f;
public override bool HideOverlaysOnEnter => true;
public override OverlayActivation InitialOverlayActivationMode => OverlayActivation.UserTriggered;
/// <summary>
/// Whether gameplay should pause when the game window focus is lost.
/// </summary>
protected virtual bool PauseOnFocusLost => true;
public Action RestartRequested;
public bool HasFailed { get; private set; }
private Bindable<bool> mouseWheelDisabled;
private readonly Bindable<bool> storyboardReplacesBackground = new Bindable<bool>();
public int RestartCount;
[Resolved]
private ScoreManager scoreManager { get; set; }
private RulesetInfo rulesetInfo;
private Ruleset ruleset;
[Resolved]
private IAPIProvider api { get; set; }
private SampleChannel sampleRestart;
public BreakOverlay BreakOverlay;
private BreakTracker breakTracker;
protected ScoreProcessor ScoreProcessor { get; private set; }
protected HealthProcessor HealthProcessor { get; private set; }
protected DrawableRuleset DrawableRuleset { get; private set; }
protected HUDOverlay HUDOverlay { get; private set; }
public bool LoadedBeatmapSuccessfully => DrawableRuleset?.Objects.Any() == true;
protected GameplayClockContainer GameplayClockContainer { get; private set; }
public DimmableStoryboard DimmableStoryboard { get; private set; }
[Cached]
[Cached(Type = typeof(IBindable<IReadOnlyList<Mod>>))]
protected new readonly Bindable<IReadOnlyList<Mod>> Mods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>());
/// <summary>
/// Whether failing should be allowed.
/// By default, this checks whether all selected mods allow failing.
/// </summary>
protected virtual bool AllowFail => Mods.Value.OfType<IApplicableFailOverride>().All(m => m.AllowFail);
private readonly bool allowPause;
private readonly bool showResults;
/// <summary>
/// Create a new player instance.
/// </summary>
/// <param name="allowPause">Whether pausing should be allowed. If not allowed, attempting to pause will quit.</param>
/// <param name="showResults">Whether results screen should be pushed on completion.</param>
public Player(bool allowPause = true, bool showResults = true)
{
this.allowPause = allowPause;
this.showResults = showResults;
}
private GameplayBeatmap gameplayBeatmap;
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
protected override void LoadComplete()
{
base.LoadComplete();
PrepareReplay();
}
private Replay recordingReplay;
/// <summary>
/// Run any recording / playback setup for replays.
/// </summary>
protected virtual void PrepareReplay()
{
DrawableRuleset.SetRecordTarget(recordingReplay = new Replay());
}
[BackgroundDependencyLoader]
private void load(AudioManager audio, OsuConfigManager config)
{
Mods.Value = base.Mods.Value.Select(m => m.CreateCopy()).ToArray();
if (Beatmap.Value is DummyWorkingBeatmap)
return;
IBeatmap playableBeatmap = loadPlayableBeatmap();
if (playableBeatmap == null)
return;
sampleRestart = audio.Samples.Get(@"Gameplay/restart");
mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, Mods.Value);
ScoreProcessor = ruleset.CreateScoreProcessor();
ScoreProcessor.ApplyBeatmap(playableBeatmap);
ScoreProcessor.Mods.BindTo(Mods);
HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime);
HealthProcessor.ApplyBeatmap(playableBeatmap);
if (!ScoreProcessor.Mode.Disabled)
config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode);
InternalChild = GameplayClockContainer = new GameplayClockContainer(Beatmap.Value, Mods.Value, DrawableRuleset.GameplayStartTime);
AddInternal(gameplayBeatmap = new GameplayBeatmap(playableBeatmap));
dependencies.CacheAs(gameplayBeatmap);
addUnderlayComponents(GameplayClockContainer);
addGameplayComponents(GameplayClockContainer, Beatmap.Value, playableBeatmap);
addOverlayComponents(GameplayClockContainer, Beatmap.Value);
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updatePauseOnFocusLostState(), true);
// bind clock into components that require it
DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);
DrawableRuleset.OnNewResult += r =>
{
HealthProcessor.ApplyResult(r);
ScoreProcessor.ApplyResult(r);
};
DrawableRuleset.OnRevertResult += r =>
{
HealthProcessor.RevertResult(r);
ScoreProcessor.RevertResult(r);
};
// Bind the judgement processors to ourselves
ScoreProcessor.AllJudged += onCompletion;
HealthProcessor.Failed += onFail;
foreach (var mod in Mods.Value.OfType<IApplicableToScoreProcessor>())
mod.ApplyToScoreProcessor(ScoreProcessor);
foreach (var mod in Mods.Value.OfType<IApplicableToHealthProcessor>())
mod.ApplyToHealthProcessor(HealthProcessor);
breakTracker.IsBreakTime.BindValueChanged(onBreakTimeChanged, true);
}
private void addUnderlayComponents(Container target)
{
target.Add(DimmableStoryboard = new DimmableStoryboard(Beatmap.Value.Storyboard) { RelativeSizeAxes = Axes.Both });
}
private void addGameplayComponents(Container target, WorkingBeatmap working, IBeatmap playableBeatmap)
{
var beatmapSkinProvider = new BeatmapSkinProvidingContainer(working.Skin);
// the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation
// full access to all skin sources.
var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider, playableBeatmap));
// load the skinning hierarchy first.
// this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources.
target.Add(new ScalingContainer(ScalingMode.Gameplay)
.WithChild(beatmapSkinProvider
.WithChild(target = rulesetSkinProvider)));
target.AddRange(new Drawable[]
{
DrawableRuleset,
new ComboEffects(ScoreProcessor)
});
DrawableRuleset.FrameStableComponents.AddRange(new Drawable[]
{
ScoreProcessor,
HealthProcessor,
breakTracker = new BreakTracker(DrawableRuleset.GameplayStartTime, ScoreProcessor)
{
Breaks = working.Beatmap.Breaks
}
});
HealthProcessor.IsBreakTime.BindTo(breakTracker.IsBreakTime);
}
private void addOverlayComponents(Container target, WorkingBeatmap working)
{
target.AddRange(new[]
{
BreakOverlay = new BreakOverlay(working.Beatmap.BeatmapInfo.LetterboxInBreaks, ScoreProcessor)
{
Clock = DrawableRuleset.FrameStableClock,
ProcessCustomClock = false,
Breaks = working.Beatmap.Breaks
},
// display the cursor above some HUD elements.
DrawableRuleset.Cursor?.CreateProxy() ?? new Container(),
DrawableRuleset.ResumeOverlay?.CreateProxy() ?? new Container(),
HUDOverlay = new HUDOverlay(ScoreProcessor, HealthProcessor, DrawableRuleset, Mods.Value)
{
HoldToQuit =
{
Action = performUserRequestedExit,
IsPaused = { BindTarget = GameplayClockContainer.IsPaused }
},
PlayerSettingsOverlay = { PlaybackSettings = { UserPlaybackRate = { BindTarget = GameplayClockContainer.UserPlaybackRate } } },
KeyCounter =
{
AlwaysVisible = { BindTarget = DrawableRuleset.HasReplayLoaded },
IsCounting = false
},
RequestSeek = GameplayClockContainer.Seek,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
},
new SkipOverlay(DrawableRuleset.GameplayStartTime)
{
RequestSkip = GameplayClockContainer.Skip
},
FailOverlay = new FailOverlay
{
OnRetry = Restart,
OnQuit = performUserRequestedExit,
},
PauseOverlay = new PauseOverlay
{
OnResume = Resume,
Retries = RestartCount,
OnRetry = Restart,
OnQuit = performUserRequestedExit,
},
new HotkeyRetryOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
Restart();
},
},
new HotkeyExitOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
performImmediateExit();
},
},
failAnimation = new FailAnimation(DrawableRuleset) { OnComplete = onFailComplete, },
});
}
private void onBreakTimeChanged(ValueChangedEvent<bool> isBreakTime)
{
updatePauseOnFocusLostState();
HUDOverlay.KeyCounter.IsCounting = !isBreakTime.NewValue;
}
private void updatePauseOnFocusLostState() =>
HUDOverlay.HoldToQuit.PauseOnFocusLost = PauseOnFocusLost
&& !DrawableRuleset.HasReplayLoaded.Value
&& !breakTracker.IsBreakTime.Value;
private IBeatmap loadPlayableBeatmap()
{
IBeatmap playable;
try
{
if (Beatmap.Value.Beatmap == null)
throw new InvalidOperationException("Beatmap was not loaded");
rulesetInfo = Ruleset.Value ?? Beatmap.Value.BeatmapInfo.Ruleset;
ruleset = rulesetInfo.CreateInstance();
try
{
playable = Beatmap.Value.GetPlayableBeatmap(ruleset.RulesetInfo, Mods.Value);
}
catch (BeatmapInvalidForRulesetException)
{
// A playable beatmap may not be creatable with the user's preferred ruleset, so try using the beatmap's default ruleset
rulesetInfo = Beatmap.Value.BeatmapInfo.Ruleset;
ruleset = rulesetInfo.CreateInstance();
playable = Beatmap.Value.GetPlayableBeatmap(rulesetInfo, Mods.Value);
}
if (playable.HitObjects.Count == 0)
{
Logger.Log("Beatmap contains no hit objects!", level: LogLevel.Error);
return null;
}
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap sucessfully!");
//couldn't load, hard abort!
return null;
}
return playable;
}
private void performImmediateExit()
{
// if a restart has been requested, cancel any pending completion (user has shown intent to restart).
completionProgressDelegate?.Cancel();
ValidForResume = false;
performUserRequestedExit();
}
private void performUserRequestedExit()
{
if (!this.IsCurrentScreen()) return;
if (ValidForResume && HasFailed && !FailOverlay.IsPresent)
{
failAnimation.FinishTransforms(true);
return;
}
if (canPause)
Pause();
else
this.Exit();
}
/// <summary>
/// Restart gameplay via a parent <see cref="PlayerLoader"/>.
/// <remarks>This can be called from a child screen in order to trigger the restart process.</remarks>
/// </summary>
public void Restart()
{
sampleRestart?.Play();
RestartRequested?.Invoke();
if (this.IsCurrentScreen())
performImmediateExit();
else
this.MakeCurrent();
}
private ScheduledDelegate completionProgressDelegate;
private void onCompletion()
{
// screen may be in the exiting transition phase.
if (!this.IsCurrentScreen())
return;
// Only show the completion screen if the player hasn't failed
if (HealthProcessor.HasFailed || completionProgressDelegate != null)
return;
ValidForResume = false;
if (!showResults) return;
using (BeginDelayedSequence(1000))
scheduleGotoRanking();
}
protected virtual ScoreInfo CreateScore()
{
var score = new ScoreInfo
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = rulesetInfo,
Mods = Mods.Value.ToArray(),
};
if (DrawableRuleset.ReplayScore != null)
score.User = DrawableRuleset.ReplayScore.ScoreInfo?.User ?? new GuestUser();
else
score.User = api.LocalUser.Value;
ScoreProcessor.PopulateScore(score);
return score;
}
protected override bool OnScroll(ScrollEvent e) => mouseWheelDisabled.Value && !GameplayClockContainer.IsPaused.Value;
protected virtual ResultsScreen CreateResults(ScoreInfo score) => new ResultsScreen(score);
#region Fail Logic
protected FailOverlay FailOverlay { get; private set; }
private FailAnimation failAnimation;
private bool onFail()
{
if (!AllowFail)
return false;
HasFailed = true;
// There is a chance that we could be in a paused state as the ruleset's internal clock (see FrameStabilityContainer)
// could process an extra frame after the GameplayClock is stopped.
// In such cases we want the fail state to precede a user triggered pause.
if (PauseOverlay.State.Value == Visibility.Visible)
PauseOverlay.Hide();
failAnimation.Start();
if (Mods.Value.OfType<IApplicableFailOverride>().Any(m => m.RestartOnFail))
Restart();
return true;
}
// Called back when the transform finishes
private void onFailComplete()
{
GameplayClockContainer.Stop();
FailOverlay.Retries = RestartCount;
FailOverlay.Show();
}
#endregion
#region Pause Logic
public bool IsResuming { get; private set; }
/// <summary>
/// The amount of gameplay time after which a second pause is allowed.
/// </summary>
private const double pause_cooldown = 1000;
protected PauseOverlay PauseOverlay { get; private set; }
private double? lastPauseActionTime;
private bool canPause =>
// must pass basic screen conditions (beatmap loaded, instance allows pause)
LoadedBeatmapSuccessfully && allowPause && ValidForResume
// replays cannot be paused and exit immediately
&& !DrawableRuleset.HasReplayLoaded.Value
// cannot pause if we are already in a fail state
&& !HasFailed
// cannot pause if already paused (or in a cooldown state) unless we are in a resuming state.
&& (IsResuming || (GameplayClockContainer.IsPaused.Value == false && !pauseCooldownActive));
private bool pauseCooldownActive =>
lastPauseActionTime.HasValue && GameplayClockContainer.GameplayClock.CurrentTime < lastPauseActionTime + pause_cooldown;
private bool canResume =>
// cannot resume from a non-paused state
GameplayClockContainer.IsPaused.Value
// cannot resume if we are already in a fail state
&& !HasFailed
// already resuming
&& !IsResuming;
public void Pause()
{
if (!canPause) return;
if (IsResuming)
{
DrawableRuleset.CancelResume();
IsResuming = false;
}
GameplayClockContainer.Stop();
PauseOverlay.Show();
lastPauseActionTime = GameplayClockContainer.GameplayClock.CurrentTime;
}
public void Resume()
{
if (!canResume) return;
IsResuming = true;
PauseOverlay.Hide();
// breaks and time-based conditions may allow instant resume.
if (breakTracker.IsBreakTime.Value)
completeResume();
else
DrawableRuleset.RequestResume(completeResume);
void completeResume()
{
GameplayClockContainer.Start();
IsResuming = false;
}
}
#endregion
#region Screen Logic
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
if (!LoadedBeatmapSuccessfully)
return;
Alpha = 0;
this
.ScaleTo(0.7f)
.ScaleTo(1, 750, Easing.OutQuint)
.Delay(250)
.FadeIn(250);
Background.EnableUserDim.Value = true;
Background.BlurAmount.Value = 0;
// bind component bindables.
Background.IsBreakTime.BindTo(breakTracker.IsBreakTime);
DimmableStoryboard.IsBreakTime.BindTo(breakTracker.IsBreakTime);
Background.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
DimmableStoryboard.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable;
GameplayClockContainer.Restart();
GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint);
foreach (var mod in Mods.Value.OfType<IApplicableToPlayer>())
mod.ApplyToPlayer(this);
foreach (var mod in Mods.Value.OfType<IApplicableToHUD>())
mod.ApplyToHUD(HUDOverlay);
}
public override void OnSuspending(IScreen next)
{
fadeOut();
base.OnSuspending(next);
}
public override bool OnExiting(IScreen next)
{
if (completionProgressDelegate != null && !completionProgressDelegate.Cancelled && !completionProgressDelegate.Completed)
{
// proceed to result screen if beatmap already finished playing
completionProgressDelegate.RunTask();
return true;
}
// ValidForResume is false when restarting
if (ValidForResume)
{
if (pauseCooldownActive && !GameplayClockContainer.IsPaused.Value)
// still want to block if we are within the cooldown period and not already paused.
return true;
}
if (canPause)
{
Pause();
return true;
}
// GameplayClockContainer performs seeks / start / stop operations on the beatmap's track.
// as we are no longer the current screen, we cannot guarantee the track is still usable.
GameplayClockContainer?.StopUsingBeatmapClock();
fadeOut();
return base.OnExiting(next);
}
protected virtual void GotoRanking()
{
if (DrawableRuleset.ReplayScore != null)
{
// if a replay is present, we likely don't want to import into the local database.
this.Push(CreateResults(CreateScore()));
return;
}
LegacyByteArrayReader replayReader = null;
var score = new Score { ScoreInfo = CreateScore() };
if (recordingReplay?.Frames.Count > 0)
{
score.Replay = recordingReplay;
using (var stream = new MemoryStream())
{
new LegacyScoreEncoder(score, gameplayBeatmap.PlayableBeatmap).Encode(stream);
replayReader = new LegacyByteArrayReader(stream.ToArray(), "replay.osr");
}
}
scoreManager.Import(score.ScoreInfo, replayReader)
.ContinueWith(imported => Schedule(() =>
{
// screen may be in the exiting transition phase.
if (this.IsCurrentScreen())
this.Push(CreateResults(imported.Result));
}));
}
private void fadeOut(bool instant = false)
{
float fadeOutDuration = instant ? 0 : 250;
this.FadeOut(fadeOutDuration);
Background.EnableUserDim.Value = false;
storyboardReplacesBackground.Value = false;
}
private void scheduleGotoRanking()
{
completionProgressDelegate?.Cancel();
completionProgressDelegate = Schedule(GotoRanking);
}
#endregion
}
}
| |
//---------------------------------------------
// CylinderMesh.cs (c) 2007 by Charles Petzold
//---------------------------------------------
using System;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace Petzold.Media3D
{
/// <summary>
/// Generates a MeshGeometry3D object for a cylinder.
/// </summary>
/// <remarks>
/// The MeshGeometry3D object this class creates is available as the
/// Geometry property. You can share the same instance of a
/// CylinderMesh object with multiple 3D visuals.
/// In XAML files, the CylinderMesh
/// tag will probably appear in a resource section.
/// The cylinder is centered on the positive Y axis.
/// </remarks>
public class CylinderMesh : CylindricalMeshBase
{
/// <summary>
/// Initializes a new instance of the CylinderMesh class.
/// </summary>
public CylinderMesh()
{
PropertyChanged(new DependencyPropertyChangedEventArgs());
}
/// <summary>
/// Identifies the EndStacks dependency property.
/// </summary>
public static readonly DependencyProperty EndStacksProperty =
DependencyProperty.Register("EndStacks",
typeof(int),
typeof(CylinderMesh),
new PropertyMetadata(1, PropertyChanged),
ValidateEndStacks);
// Validation callback for EndStacks.
static bool ValidateEndStacks(object obj)
{
return (int)obj > 0;
}
/// <summary>
/// Gets or sets the number of radial divisions on each end of
/// the cylinder.
/// </summary>
/// <value>
/// The number of radial divisions on the end of the cylinder.
/// This property must be at least 1, which is also the default value.
/// </value>
/// <remarks>
/// The default value of 1 is appropriate in many cases.
/// However, if PointLight or SpotLight objects are applied to the
/// cylinder, or if non-linear transforms are used to deform
/// the figure, you should set EndStacks to a higher value.
/// </remarks>
public int EndStacks
{
set { SetValue(EndStacksProperty, value); }
get { return (int)GetValue(EndStacksProperty); }
}
/// <summary>
/// Identifies the Fold dependency property.
/// </summary>
public static readonly DependencyProperty FoldProperty =
DependencyProperty.Register("Fold",
typeof(double),
typeof(CylinderMesh),
new PropertyMetadata(1.0 / 3, PropertyChanged),
ValidateFold);
// Validation callback for Fold.
static bool ValidateFold(object obj)
{
return (double)obj < 0.5;
}
/// <summary>
/// Gets or sets the fraction of the brush that appears on
/// the top and bottom ends of the cylinder.
/// </summary>
/// <value>
/// The fraction of the brush that folds over the top and
/// bottom ends of the cylinder. The default is 1/3. The
/// property cannot be greater than 1/2.
/// </value>
public double Fold
{
set { SetValue(FoldProperty, value); }
get { return (double)GetValue(FoldProperty); }
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <param name="vertices"></param>
/// <param name="normals"></param>
/// <param name="indices"></param>
/// <param name="textures"></param>
protected override void Triangulate(DependencyPropertyChangedEventArgs args,
Point3DCollection vertices,
Vector3DCollection normals,
Int32Collection indices,
PointCollection textures)
{
// Clear all four collections.
vertices.Clear();
normals.Clear();
indices.Clear();
textures.Clear();
// Begin at the top end. Fill the collections.
for (int stack = 0; stack <= EndStacks; stack++)
{
double y = Length;
double radius = stack * Radius / EndStacks;
int top = (stack + 0) * (Slices + 1);
int bot = (stack + 1) * (Slices + 1);
for (int slice = 0; slice <= Slices; slice++)
{
double theta = slice * 2 * Math.PI / Slices;
double x = -radius * Math.Sin(theta);
double z = -radius * Math.Cos(theta);
vertices.Add(new Point3D(x, y, z));
normals.Add(new Vector3D(0, 1, 0));
textures.Add(new Point((double)slice / Slices,
Fold * stack / EndStacks));
if (stack < EndStacks && slice < Slices)
{
if (stack != 0)
{
indices.Add(top + slice);
indices.Add(bot + slice);
indices.Add(top + slice + 1);
}
indices.Add(top + slice + 1);
indices.Add(bot + slice);
indices.Add(bot + slice + 1);
}
}
}
int offset = vertices.Count;
// Length of the cylinder: Fill in the collections.
for (int stack = 0; stack <= Stacks; stack++)
{
double y = Length - stack * Length / Stacks;
int top = offset + (stack + 0) * (Slices + 1);
int bot = offset + (stack + 1) * (Slices + 1);
for (int slice = 0; slice <= Slices; slice++)
{
double theta = slice * 2 * Math.PI / Slices;
double x = -Radius * Math.Sin(theta);
double z = -Radius * Math.Cos(theta);
vertices.Add(new Point3D(x, y, z));
normals.Add(new Vector3D(x, 0, z));
textures.Add(new Point((double)slice / Slices,
Fold + (1 - 2 * Fold) * stack / Stacks));
if (stack < Stacks && slice < Slices)
{
indices.Add(top + slice);
indices.Add(bot + slice);
indices.Add(top + slice + 1);
indices.Add(top + slice + 1);
indices.Add(bot + slice);
indices.Add(bot + slice + 1);
}
}
}
offset = vertices.Count;
// Finish with the bottom end. Fill the collections.
for (int stack = 0; stack <= EndStacks; stack++)
{
double y = 0;
double radius = (EndStacks - stack) * Radius / EndStacks;
int top = offset + (stack + 0) * (Slices + 1);
int bot = offset + (stack + 1) * (Slices + 1);
for (int slice = 0; slice <= Slices; slice++)
{
double theta = slice * 2 * Math.PI / Slices;
double x = -radius * Math.Sin(theta);
double z = -radius * Math.Cos(theta);
vertices.Add(new Point3D(x, y, z));
normals.Add(new Vector3D(0, -1, 0));
textures.Add(new Point((double)slice / Slices,
(1 - Fold) + Fold * stack / EndStacks));
if (stack < EndStacks && slice < Slices)
{
indices.Add(top + slice);
indices.Add(bot + slice);
indices.Add(top + slice + 1);
if (stack != EndStacks - 1)
{
indices.Add(top + slice + 1);
indices.Add(bot + slice);
indices.Add(bot + slice + 1);
}
}
}
}
}
/// <summary>
/// Creates a new instance of the CylinderMesh class.
/// </summary>
/// <returns>
/// A new instance of CylinderMesh.
/// </returns>
/// <remarks>
/// Overriding this method is required when deriving
/// from the Freezable class.
/// </remarks>
protected override Freezable CreateInstanceCore()
{
return new CylinderMesh();
}
}
}
| |
// 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.V9.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.V9.Services
{
/// <summary>Settings for <see cref="ClickViewServiceClient"/> instances.</summary>
public sealed partial class ClickViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ClickViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ClickViewServiceSettings"/>.</returns>
public static ClickViewServiceSettings GetDefault() => new ClickViewServiceSettings();
/// <summary>Constructs a new <see cref="ClickViewServiceSettings"/> object with default settings.</summary>
public ClickViewServiceSettings()
{
}
private ClickViewServiceSettings(ClickViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetClickViewSettings = existing.GetClickViewSettings;
OnCopy(existing);
}
partial void OnCopy(ClickViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClickViewServiceClient.GetClickView</c> and <c>ClickViewServiceClient.GetClickViewAsync</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 GetClickViewSettings { 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="ClickViewServiceSettings"/> object.</returns>
public ClickViewServiceSettings Clone() => new ClickViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ClickViewServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class ClickViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ClickViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ClickViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ClickViewServiceClientBuilder()
{
UseJwtAccessWithScopes = ClickViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ClickViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ClickViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ClickViewServiceClient Build()
{
ClickViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ClickViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ClickViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ClickViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ClickViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ClickViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ClickViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ClickViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ClickViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ClickViewServiceClient.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>ClickViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch click views.
/// </remarks>
public abstract partial class ClickViewServiceClient
{
/// <summary>
/// The default endpoint for the ClickViewService 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 ClickViewService scopes.</summary>
/// <remarks>
/// The default ClickViewService 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="ClickViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ClickViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ClickViewServiceClient"/>.</returns>
public static stt::Task<ClickViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ClickViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ClickViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ClickViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ClickViewServiceClient"/>.</returns>
public static ClickViewServiceClient Create() => new ClickViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ClickViewServiceClient"/> 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="ClickViewServiceSettings"/>.</param>
/// <returns>The created <see cref="ClickViewServiceClient"/>.</returns>
internal static ClickViewServiceClient Create(grpccore::CallInvoker callInvoker, ClickViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ClickViewService.ClickViewServiceClient grpcClient = new ClickViewService.ClickViewServiceClient(callInvoker);
return new ClickViewServiceClientImpl(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 ClickViewService client</summary>
public virtual ClickViewService.ClickViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ClickView GetClickView(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, st::CancellationToken cancellationToken) =>
GetClickViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ClickView GetClickView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetClickView(new GetClickViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetClickViewAsync(new GetClickViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetClickViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ClickView GetClickView(gagvr::ClickViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetClickView(new GetClickViewRequest
{
ResourceNameAsClickViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(gagvr::ClickViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetClickViewAsync(new GetClickViewRequest
{
ResourceNameAsClickViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the click view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(gagvr::ClickViewName resourceName, st::CancellationToken cancellationToken) =>
GetClickViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ClickViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch click views.
/// </remarks>
public sealed partial class ClickViewServiceClientImpl : ClickViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetClickViewRequest, gagvr::ClickView> _callGetClickView;
/// <summary>
/// Constructs a client wrapper for the ClickViewService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ClickViewServiceSettings"/> used within this client.</param>
public ClickViewServiceClientImpl(ClickViewService.ClickViewServiceClient grpcClient, ClickViewServiceSettings settings)
{
GrpcClient = grpcClient;
ClickViewServiceSettings effectiveSettings = settings ?? ClickViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetClickView = clientHelper.BuildApiCall<GetClickViewRequest, gagvr::ClickView>(grpcClient.GetClickViewAsync, grpcClient.GetClickView, effectiveSettings.GetClickViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetClickView);
Modify_GetClickViewApiCall(ref _callGetClickView);
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_GetClickViewApiCall(ref gaxgrpc::ApiCall<GetClickViewRequest, gagvr::ClickView> call);
partial void OnConstruction(ClickViewService.ClickViewServiceClient grpcClient, ClickViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ClickViewService client</summary>
public override ClickViewService.ClickViewServiceClient GrpcClient { get; }
partial void Modify_GetClickViewRequest(ref GetClickViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::ClickView GetClickView(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetClickViewRequest(ref request, ref callSettings);
return _callGetClickView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested click view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetClickViewRequest(ref request, ref callSettings);
return _callGetClickView.Async(request, callSettings);
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// EmailDomain
/// </summary>
[DataContract]
public partial class EmailDomain : IEquatable<EmailDomain>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EmailDomain" /> class.
/// </summary>
/// <param name="comment">comment.</param>
/// <param name="dkim">dkim.</param>
/// <param name="dkimStatus">dkimStatus.</param>
/// <param name="domain">domain.</param>
/// <param name="espDomainUuid">espDomainUuid.</param>
/// <param name="identityStatus">identityStatus.</param>
/// <param name="merchantId">merchantId.</param>
/// <param name="provider">provider.</param>
/// <param name="startDkimDts">startDkimDts.</param>
/// <param name="startIdentityDts">startIdentityDts.</param>
/// <param name="verification">verification.</param>
public EmailDomain(string comment = default(string), List<VerificationRecord> dkim = default(List<VerificationRecord>), string dkimStatus = default(string), string domain = default(string), string espDomainUuid = default(string), string identityStatus = default(string), string merchantId = default(string), string provider = default(string), string startDkimDts = default(string), string startIdentityDts = default(string), VerificationRecord verification = default(VerificationRecord))
{
this.Comment = comment;
this.Dkim = dkim;
this.DkimStatus = dkimStatus;
this.Domain = domain;
this.EspDomainUuid = espDomainUuid;
this.IdentityStatus = identityStatus;
this.MerchantId = merchantId;
this.Provider = provider;
this.StartDkimDts = startDkimDts;
this.StartIdentityDts = startIdentityDts;
this.Verification = verification;
}
/// <summary>
/// Gets or Sets Comment
/// </summary>
[DataMember(Name="comment", EmitDefaultValue=false)]
public string Comment { get; set; }
/// <summary>
/// Gets or Sets Dkim
/// </summary>
[DataMember(Name="dkim", EmitDefaultValue=false)]
public List<VerificationRecord> Dkim { get; set; }
/// <summary>
/// Gets or Sets DkimStatus
/// </summary>
[DataMember(Name="dkim_status", EmitDefaultValue=false)]
public string DkimStatus { get; set; }
/// <summary>
/// Gets or Sets Domain
/// </summary>
[DataMember(Name="domain", EmitDefaultValue=false)]
public string Domain { get; set; }
/// <summary>
/// Gets or Sets EspDomainUuid
/// </summary>
[DataMember(Name="esp_domain_uuid", EmitDefaultValue=false)]
public string EspDomainUuid { get; set; }
/// <summary>
/// Gets or Sets IdentityStatus
/// </summary>
[DataMember(Name="identity_status", EmitDefaultValue=false)]
public string IdentityStatus { get; set; }
/// <summary>
/// Gets or Sets MerchantId
/// </summary>
[DataMember(Name="merchant_id", EmitDefaultValue=false)]
public string MerchantId { get; set; }
/// <summary>
/// Gets or Sets Provider
/// </summary>
[DataMember(Name="provider", EmitDefaultValue=false)]
public string Provider { get; set; }
/// <summary>
/// Gets or Sets StartDkimDts
/// </summary>
[DataMember(Name="start_dkim_dts", EmitDefaultValue=false)]
public string StartDkimDts { get; set; }
/// <summary>
/// Gets or Sets StartIdentityDts
/// </summary>
[DataMember(Name="start_identity_dts", EmitDefaultValue=false)]
public string StartIdentityDts { get; set; }
/// <summary>
/// Gets or Sets Verification
/// </summary>
[DataMember(Name="verification", EmitDefaultValue=false)]
public VerificationRecord Verification { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EmailDomain {\n");
sb.Append(" Comment: ").Append(Comment).Append("\n");
sb.Append(" Dkim: ").Append(Dkim).Append("\n");
sb.Append(" DkimStatus: ").Append(DkimStatus).Append("\n");
sb.Append(" Domain: ").Append(Domain).Append("\n");
sb.Append(" EspDomainUuid: ").Append(EspDomainUuid).Append("\n");
sb.Append(" IdentityStatus: ").Append(IdentityStatus).Append("\n");
sb.Append(" MerchantId: ").Append(MerchantId).Append("\n");
sb.Append(" Provider: ").Append(Provider).Append("\n");
sb.Append(" StartDkimDts: ").Append(StartDkimDts).Append("\n");
sb.Append(" StartIdentityDts: ").Append(StartIdentityDts).Append("\n");
sb.Append(" Verification: ").Append(Verification).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EmailDomain);
}
/// <summary>
/// Returns true if EmailDomain instances are equal
/// </summary>
/// <param name="input">Instance of EmailDomain to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EmailDomain input)
{
if (input == null)
return false;
return
(
this.Comment == input.Comment ||
(this.Comment != null &&
this.Comment.Equals(input.Comment))
) &&
(
this.Dkim == input.Dkim ||
this.Dkim != null &&
this.Dkim.SequenceEqual(input.Dkim)
) &&
(
this.DkimStatus == input.DkimStatus ||
(this.DkimStatus != null &&
this.DkimStatus.Equals(input.DkimStatus))
) &&
(
this.Domain == input.Domain ||
(this.Domain != null &&
this.Domain.Equals(input.Domain))
) &&
(
this.EspDomainUuid == input.EspDomainUuid ||
(this.EspDomainUuid != null &&
this.EspDomainUuid.Equals(input.EspDomainUuid))
) &&
(
this.IdentityStatus == input.IdentityStatus ||
(this.IdentityStatus != null &&
this.IdentityStatus.Equals(input.IdentityStatus))
) &&
(
this.MerchantId == input.MerchantId ||
(this.MerchantId != null &&
this.MerchantId.Equals(input.MerchantId))
) &&
(
this.Provider == input.Provider ||
(this.Provider != null &&
this.Provider.Equals(input.Provider))
) &&
(
this.StartDkimDts == input.StartDkimDts ||
(this.StartDkimDts != null &&
this.StartDkimDts.Equals(input.StartDkimDts))
) &&
(
this.StartIdentityDts == input.StartIdentityDts ||
(this.StartIdentityDts != null &&
this.StartIdentityDts.Equals(input.StartIdentityDts))
) &&
(
this.Verification == input.Verification ||
(this.Verification != null &&
this.Verification.Equals(input.Verification))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Comment != null)
hashCode = hashCode * 59 + this.Comment.GetHashCode();
if (this.Dkim != null)
hashCode = hashCode * 59 + this.Dkim.GetHashCode();
if (this.DkimStatus != null)
hashCode = hashCode * 59 + this.DkimStatus.GetHashCode();
if (this.Domain != null)
hashCode = hashCode * 59 + this.Domain.GetHashCode();
if (this.EspDomainUuid != null)
hashCode = hashCode * 59 + this.EspDomainUuid.GetHashCode();
if (this.IdentityStatus != null)
hashCode = hashCode * 59 + this.IdentityStatus.GetHashCode();
if (this.MerchantId != null)
hashCode = hashCode * 59 + this.MerchantId.GetHashCode();
if (this.Provider != null)
hashCode = hashCode * 59 + this.Provider.GetHashCode();
if (this.StartDkimDts != null)
hashCode = hashCode * 59 + this.StartDkimDts.GetHashCode();
if (this.StartIdentityDts != null)
hashCode = hashCode * 59 + this.StartIdentityDts.GetHashCode();
if (this.Verification != null)
hashCode = hashCode * 59 + this.Verification.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements New-PSSessionOption cmdlet.
/// Spec: TBD.
/// </summary>
[Cmdlet(VerbsCommon.New, "PSSessionOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096488", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(PSSessionOption))]
public sealed class NewPSSessionOptionCommand : PSCmdlet
{
#region Parameters (specific to PSSessionOption)
#if !UNIX
/// <summary>
/// The MaximumRedirection parameter enables the implicit redirection functionality
/// -1 = no limit
/// 0 = no redirection.
/// </summary>
[Parameter]
public int MaximumRedirection
{
get { return _maximumRedirection.Value; }
set { _maximumRedirection = value; }
}
private int? _maximumRedirection;
/// <summary>
/// If false, underlying WSMan infrastructure will compress data sent on the network.
/// If true, data will not be compressed. Compression improves performance by
/// reducing the amount of data sent on the network. Compression my require extra
/// memory consumption and CPU usage. In cases where available memory / CPU is less,
/// set this property to "true".
/// By default the value of this property is "false".
/// </summary>
[Parameter]
public SwitchParameter NoCompression { get; set; }
/// <summary>
/// If <see langword="true"/> then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server
/// which can result in a faster session creation time. This option won't have any effect if the remote machine has
/// already loaded the profile (i.e. in another session).
/// </summary>
[Parameter]
public SwitchParameter NoMachineProfile { get; set; }
/// <summary>
/// Culture that the remote session should use.
/// </summary>
[Parameter]
[ValidateNotNull]
public CultureInfo Culture { get; set; }
/// <summary>
/// UI culture that the remote session should use.
/// </summary>
[Parameter]
[ValidateNotNull]
public CultureInfo UICulture { get; set; }
/// <summary>
/// Total data (in bytes) that can be received from a remote machine
/// targeted towards a command. If null, then the size is unlimited.
/// Default is unlimited data.
/// </summary>
[Parameter]
public int MaximumReceivedDataSizePerCommand
{
get { return _maxRecvdDataSizePerCommand.Value; }
set { _maxRecvdDataSizePerCommand = value; }
}
private int? _maxRecvdDataSizePerCommand;
/// <summary>
/// Maximum size (in bytes) of a deserialized object received from a remote machine.
/// If null, then the size is unlimited. Default is unlimited object size.
/// </summary>
[Parameter]
public int MaximumReceivedObjectSize
{
get { return _maxRecvdObjectSize.Value; }
set { _maxRecvdObjectSize = value; }
}
private int? _maxRecvdObjectSize;
/// <summary>
/// Specifies the output mode on the server when it is in Disconnected mode
/// and its output data cache becomes full.
/// </summary>
[Parameter]
public OutputBufferingMode OutputBufferingMode { get; set; }
/// <summary>
/// Maximum number of times a connection will be re-attempted when a connection fails due to network
/// issues.
/// </summary>
[Parameter]
[ValidateRange(0, Int32.MaxValue)]
public int MaxConnectionRetryCount { get; set; }
/// <summary>
/// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public PSPrimitiveDictionary ApplicationArguments { get; set; }
/// <summary>
/// The duration for which PowerShell remoting waits (in milliseconds) before timing
/// out on a connection to a remote machine. Simply put, the timeout for a remote
/// runspace creation.
///
/// The user would like to tweak this timeout depending on whether
/// he/she is connecting to a machine in the data center or across a slow WAN.
/// </summary>
[Parameter]
[Alias("OpenTimeoutMSec")]
[ValidateRange(0, Int32.MaxValue)]
public int OpenTimeout
{
get
{
return _openTimeout ?? RunspaceConnectionInfo.DefaultOpenTimeout;
}
set
{
_openTimeout = value;
}
}
private int? _openTimeout;
/// <summary>
/// The duration for which PowerShell should wait (in milliseconds) before it
/// times out on cancel operations (close runspace or stop powershell). For
/// instance, when the user hits ctrl-C, New-PSSession cmdlet tries to call a
/// stop on all remote runspaces which are in the Opening state. The user
/// wouldn't mind waiting for 15 seconds, but this should be time bound and of a
/// shorter duration. A high timeout here like 3 minutes will give the user
/// a feeling that the PowerShell client is not responding.
/// </summary>
[Parameter]
[Alias("CancelTimeoutMSec")]
[ValidateRange(0, Int32.MaxValue)]
public int CancelTimeout
{
get
{
return _cancelTimeout ?? BaseTransportManager.ClientCloseTimeoutMs;
}
set
{
_cancelTimeout = value;
}
}
private int? _cancelTimeout;
/// <summary>
/// The duration for which a Runspace on server needs to wait (in milliseconds) before it
/// declares the client dead and closes itself down.
/// This is especially important as these values may have to be configured differently
/// for enterprise administration scenarios.
/// </summary>
[Parameter]
[ValidateRange(-1, Int32.MaxValue)]
[Alias("IdleTimeoutMSec")]
public int IdleTimeout
{
get
{
return _idleTimeout ?? RunspaceConnectionInfo.DefaultIdleTimeout;
}
set
{
_idleTimeout = value;
}
}
private int? _idleTimeout;
#endif
#endregion Parameters
#region Parameters copied from New-WSManSessionOption
#if !UNIX
/// <summary>
/// By default, ProxyAccessType is None, that means Proxy information (ProxyAccessType,
/// ProxyAuthenticationMechanism and ProxyCredential)is not passed to WSMan at all.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public ProxyAccessType ProxyAccessType { get; set; } = ProxyAccessType.None;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available options should be as follows:
/// - Negotiate: Use the default authentication (as defined by the underlying
/// protocol) for establishing a remote connection.
/// - Basic: Use basic authentication for establishing a remote connection
/// - Digest: Use Digest authentication for establishing a remote connection.
/// </summary>
[Parameter]
public AuthenticationMechanism ProxyAuthentication { get; set; } = AuthenticationMechanism.Negotiate;
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Credential]
public PSCredential ProxyCredential { get; set; }
#endif
/// <summary>
/// The following is the definition of the input parameter "SkipCACheck".
/// When connecting over HTTPS, the client does not validate that the server
/// certificate is signed by a trusted certificate authority (CA). Use only when
/// the remote computer is trusted by other means, for example, if the remote
/// computer is part of a network that is physically secure and isolated or the
/// remote computer is listed as a trusted host in WinRM configuration.
/// </summary>
[Parameter]
public SwitchParameter SkipCACheck
{
get { return _skipcacheck; }
set { _skipcacheck = value; }
}
private bool _skipcacheck;
/// <summary>
/// The following is the definition of the input parameter "SkipCNCheck".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
[Parameter]
public SwitchParameter SkipCNCheck
{
get { return _skipcncheck; }
set { _skipcncheck = value; }
}
private bool _skipcncheck;
#if !UNIX
/// <summary>
/// The following is the definition of the input parameter "SkipRevocation".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
[Parameter]
public SwitchParameter SkipRevocationCheck
{
get { return _skiprevocationcheck; }
set { _skiprevocationcheck = value; }
}
private bool _skiprevocationcheck;
/// <summary>
/// The following is the definition of the input parameter "Timeout".
/// Defines the timeout in milliseconds for the wsman operation.
/// </summary>
[Parameter]
[Alias("OperationTimeoutMSec")]
[ValidateRange(0, Int32.MaxValue)]
public int OperationTimeout
{
get
{
return _operationtimeout ?? BaseTransportManager.ClientDefaultOperationTimeoutMs;
}
set
{
_operationtimeout = value;
}
}
private int? _operationtimeout;
/// <summary>
/// The following is the definition of the input parameter "UnEncrypted".
/// Specifies that no encryption will be used when doing remote operations over
/// http. Unencrypted traffic is not allowed by default and must be enabled in
/// the local configuration.
/// </summary>
[Parameter]
public SwitchParameter NoEncryption
{
get
{
return _noencryption;
}
set
{
_noencryption = value;
}
}
private bool _noencryption;
/// <summary>
/// The following is the definition of the input parameter "UTF16".
/// Indicates the request is encoded in UTF16 format rather than UTF8 format;
/// UTF8 is the default.
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
public SwitchParameter UseUTF16
{
get
{
return _useutf16;
}
set
{
_useutf16 = value;
}
}
private bool _useutf16;
/// <summary>
/// Uses Service Principal Name (SPN) along with the Port number during authentication.
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
public SwitchParameter IncludePortInSPN
{
get { return _includePortInSPN; }
set { _includePortInSPN = value; }
}
private bool _includePortInSPN;
#endif
#endregion
#region Implementation
/// <summary>
/// Performs initialization of cmdlet execution.
/// </summary>
protected override void BeginProcessing()
{
PSSessionOption result = new PSSessionOption();
// Begin: WSMan specific options
#if !UNIX
result.ProxyAccessType = this.ProxyAccessType;
result.ProxyAuthentication = this.ProxyAuthentication;
result.ProxyCredential = this.ProxyCredential;
#endif
result.SkipCACheck = this.SkipCACheck;
result.SkipCNCheck = this.SkipCNCheck;
#if !UNIX
result.SkipRevocationCheck = this.SkipRevocationCheck;
if (_operationtimeout.HasValue)
{
result.OperationTimeout = TimeSpan.FromMilliseconds(_operationtimeout.Value);
}
result.NoEncryption = this.NoEncryption;
result.UseUTF16 = this.UseUTF16;
result.IncludePortInSPN = this.IncludePortInSPN;
// End: WSMan specific options
if (_maximumRedirection.HasValue)
{
result.MaximumConnectionRedirectionCount = this.MaximumRedirection;
}
result.NoCompression = this.NoCompression.IsPresent;
result.NoMachineProfile = this.NoMachineProfile.IsPresent;
result.MaximumReceivedDataSizePerCommand = _maxRecvdDataSizePerCommand;
result.MaximumReceivedObjectSize = _maxRecvdObjectSize;
if (this.Culture != null)
{
result.Culture = this.Culture;
}
if (this.UICulture != null)
{
result.UICulture = this.UICulture;
}
if (_openTimeout.HasValue)
{
result.OpenTimeout = TimeSpan.FromMilliseconds(_openTimeout.Value);
}
if (_cancelTimeout.HasValue)
{
result.CancelTimeout = TimeSpan.FromMilliseconds(_cancelTimeout.Value);
}
if (_idleTimeout.HasValue)
{
result.IdleTimeout = TimeSpan.FromMilliseconds(_idleTimeout.Value);
}
result.OutputBufferingMode = OutputBufferingMode;
result.MaxConnectionRetryCount = MaxConnectionRetryCount;
if (this.ApplicationArguments != null)
{
result.ApplicationArguments = this.ApplicationArguments;
}
#endif
this.WriteObject(result);
}
#endregion Methods
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using System.Diagnostics;
using System.Globalization;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
namespace Lucene.Net.Util
{
public abstract partial class LuceneTestCase
{
public static void assertTrue(bool condition)
{
Assert.IsTrue(condition);
}
public static void assertTrue(string message, bool condition)
{
Assert.IsTrue(condition, message);
}
public static void assertFalse(bool condition)
{
Assert.IsFalse(condition);
}
public static void assertFalse(string message, bool condition)
{
Assert.IsFalse(condition, message);
}
public static void assertEquals(object expected, object actual)
{
Assert.AreEqual(expected, actual);
}
public static void assertEquals(string message, object expected, object actual)
{
Assert.AreEqual(expected, actual, message);
}
public static void assertEquals(long expected, long actual)
{
Assert.AreEqual(expected, actual);
}
public static void assertEquals(string message, long expected, long actual)
{
Assert.AreEqual(expected, actual, message);
}
public static void assertEquals<T>(ISet<T> expected, ISet<T> actual)
{
Assert.True(expected.SetEquals(actual));
}
public static void assertEquals<T>(string message, ISet<T> expected, ISet<T> actual)
{
Assert.True(expected.SetEquals(actual), message);
}
public static void assertEquals<T, S>(IDictionary<T, S> expected, IDictionary<T, S> actual)
{
Assert.AreEqual(expected.Count, actual.Count);
foreach (var key in expected.Keys)
{
Assert.AreEqual(expected[key], actual[key]);
}
}
public static void assertNotSame(object unexpected, object actual)
{
Assert.AreNotSame(unexpected, actual);
}
public static void assertNotSame(string message, object unexpected, object actual)
{
Assert.AreNotSame(unexpected, actual, message);
}
protected static void assertEquals(double d1, double d2, double delta)
{
Assert.AreEqual(d1, d2, delta);
}
protected static void assertEquals(string msg, double d1, double d2, double delta)
{
Assert.AreEqual(d1, d2, delta, msg);
}
protected static void assertNotNull(object o)
{
Assert.NotNull(o);
}
protected static void assertNotNull(string msg, object o)
{
Assert.NotNull(o, msg);
}
protected static void assertNull(object o)
{
Assert.Null(o);
}
protected static void assertNull(string msg, object o)
{
Assert.Null(o, msg);
}
protected static void assertArrayEquals(IEnumerable a1, IEnumerable a2)
{
CollectionAssert.AreEqual(a1, a2);
}
protected static void assertSame(Object expected, Object actual)
{
Assert.AreSame(expected, actual);
}
protected static void assertSame(string message, Object expected, Object actual)
{
Assert.AreSame(expected, actual, message);
}
protected static void fail()
{
Assert.Fail();
}
protected static void fail(string message)
{
Assert.Fail(message);
}
protected static ISet<T> AsSet<T>(params T[] args)
{
return new HashSet<T>(args);
}
protected int randomInt(int max)
{
return randomIntBetween(0, max);
}
protected int randomIntBetween(int min, int max)
{
Debug.Assert(max >= min, "max must be >= min: " + min + ", " + max);
long range = (long)max - (long)min;
if (range < int.MaxValue)
{
return min + Random().nextInt(1 + (int)range);
}
else
{
return toIntExact(min + Random().Next(1 + (int)range));
}
}
private static int toIntExact(long value)
{
if (value > int.MaxValue)
{
throw new ArithmeticException("Overflow: " + value);
}
else
{
return (int)value;
}
}
private double nextNextGaussian;
private bool haveNextNextGaussian = false;
/**
* Returns the next pseudorandom, Gaussian ("normally") distributed
* <c>double</c> value with mean <c>0.0</c> and standard
* deviation <c>1.0</c> from this random number generator's sequence.
* <para/>
* The general contract of <c>nextGaussian</c> is that one
* <c>double</c> value, chosen from (approximately) the usual
* normal distribution with mean <c>0.0</c> and standard deviation
* <c>1.0</c>, is pseudorandomly generated and returned.
*
* <para/>The method <c>nextGaussian</c> is implemented by class
* <c>Random</c> as if by a threadsafe version of the following:
* <code>
* private double nextNextGaussian;
* private boolean haveNextNextGaussian = false;
*
* public double nextGaussian() {
* if (haveNextNextGaussian) {
* haveNextNextGaussian = false;
* return nextNextGaussian;
* } else {
* double v1, v2, s;
* do {
* v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
* v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
* s = v1 * v1 + v2 * v2;
* } while (s >= 1 || s == 0);
* double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
* nextNextGaussian = v2 * multiplier;
* haveNextNextGaussian = true;
* return v1 * multiplier;
* }
* }}</code>
* This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
* G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
* Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
* section 3.4.1, subsection C, algorithm P. Note that it generates two
* independent values at the cost of only one call to <c>StrictMath.log</c>
* and one call to <c>StrictMath.sqrt</c>.
*
* @return the next pseudorandom, Gaussian ("normally") distributed
* <c>double</c> value with mean <c>0.0</c> and
* standard deviation <c>1.0</c> from this random number
* generator's sequence
*/
public double randomGaussian()
{
// See Knuth, ACP, Section 3.4.1 Algorithm C.
if (haveNextNextGaussian)
{
haveNextNextGaussian = false;
return nextNextGaussian;
}
else
{
double v1, v2, s;
do
{
v1 = 2 * Random().NextDouble() - 1; // between -1 and 1
v2 = 2 * Random().NextDouble() - 1; // between -1 and 1
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = Math.Sqrt(-2 * Math.Log(s) / s);
nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
return v1 * multiplier;
}
}
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/////////////////////////////////////////////////////////////////////////////////
// Defines the structure used when binding types
// CheckConstraints options.
[Flags]
internal enum CheckConstraintsFlags
{
None = 0x00,
Outer = 0x01,
NoErrors = 0x04,
}
/////////////////////////////////////////////////////////////////////////////////
// TypeBind has static methods to accomplish most tasks.
//
// For some of these tasks there are also instance methods. The instance
// method versions don't report not found errors (they may report others) but
// instead record error information in the TypeBind instance. Call the
// ReportErrors method to report recorded errors.
internal static class TypeBind
{
// Check the constraints of any type arguments in the given Type.
public static bool CheckConstraints(CSemanticChecker checker, ErrorHandling errHandling, CType type, CheckConstraintsFlags flags)
{
type = type.GetNakedType(false);
if (!(type is AggregateType ats))
{
if (type is NullableType nub)
{
ats = nub.GetAts();
}
else
{
return true;
}
}
if (ats.TypeArgsAll.Count == 0)
{
// Common case: there are no type vars, so there are no constraints.
ats.ConstraintError = false;
return true;
}
// Already checked.
if (ats.ConstraintError.HasValue)
{
// No errors
if (!ats.ConstraintError.GetValueOrDefault())
{
return true;
}
// We want the result, not an exception.
if ((flags & CheckConstraintsFlags.NoErrors) != 0)
{
return false;
}
}
TypeArray typeVars = ats.OwningAggregate.GetTypeVars();
TypeArray typeArgsThis = ats.TypeArgsThis;
TypeArray typeArgsAll = ats.TypeArgsAll;
Debug.Assert(typeVars.Count == typeArgsThis.Count);
// Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the
// outer type has already been checked then don't bother checking it.
if (ats.OuterType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.OuterType.ConstraintError.HasValue))
{
if (!CheckConstraints(checker, errHandling, ats.OuterType, flags))
{
ats.ConstraintError = true;
return false;
}
}
if (typeVars.Count > 0)
{
if (!CheckConstraintsCore(checker, errHandling, ats.OwningAggregate, typeVars, typeArgsThis, typeArgsAll, null, flags & CheckConstraintsFlags.NoErrors))
{
ats.ConstraintError = true;
return false;
}
}
// Now check type args themselves.
for (int i = 0; i < typeArgsThis.Count; i++)
{
CType arg = typeArgsThis[i].GetNakedType(true);
if (arg is AggregateType atArg && !atArg.ConstraintError.HasValue)
{
CheckConstraints(checker, errHandling, atArg, flags | CheckConstraintsFlags.Outer);
if (atArg.ConstraintError.GetValueOrDefault())
{
ats.ConstraintError = true;
return false;
}
}
}
ats.ConstraintError = false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Check the constraints on the method instantiation.
public static void CheckMethConstraints(CSemanticChecker checker, ErrorHandling errCtx, MethWithInst mwi)
{
Debug.Assert(mwi.Meth() != null && mwi.GetType() != null && mwi.TypeArgs != null);
Debug.Assert(mwi.Meth().typeVars.Count == mwi.TypeArgs.Count);
Debug.Assert(mwi.GetType().OwningAggregate == mwi.Meth().getClass());
if (mwi.TypeArgs.Count > 0)
{
CheckConstraintsCore(checker, errCtx, mwi.Meth(), mwi.Meth().typeVars, mwi.TypeArgs, mwi.GetType().TypeArgsAll, mwi.TypeArgs, CheckConstraintsFlags.None);
}
}
////////////////////////////////////////////////////////////////////////////////
// Check whether typeArgs satisfies the constraints of typeVars. The
// typeArgsCls and typeArgsMeth are used for substitution on the bounds. The
// tree and symErr are used for error reporting.
private static bool CheckConstraintsCore(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeArray typeVars, TypeArray typeArgs, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
Debug.Assert(typeVars.Count == typeArgs.Count);
Debug.Assert(typeVars.Count > 0);
Debug.Assert(flags == CheckConstraintsFlags.None || flags == CheckConstraintsFlags.NoErrors);
for (int i = 0; i < typeVars.Count; i++)
{
// Empty bounds should be set to object.
TypeParameterType var = (TypeParameterType)typeVars[i];
CType arg = typeArgs[i];
if (!CheckSingleConstraint(checker, errHandling, symErr, var, arg, typeArgsCls, typeArgsMeth, flags))
{
return false;
}
}
return true;
}
private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
Debug.Assert(!(arg is PointerType));
Debug.Assert(!arg.IsStaticClass);
bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors);
if (var.HasRefConstraint && !arg.IsReferenceType)
{
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
TypeArray bnds = checker.SymbolLoader.GetTypeManager().SubstTypeArray(var.Bounds, typeArgsCls, typeArgsMeth);
int itypeMin = 0;
if (var.HasValConstraint)
{
// If we have a type variable that is constrained to a value type, then we
// want to check if its a nullable type, so that we can report the
// constraint error below. In order to do this however, we need to check
// that either the type arg is not a value type, or it is a nullable type.
//
// To check whether or not its a nullable type, we need to get the resolved
// bound from the type argument and check against that.
if (!arg.IsNonNullableValueType)
{
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
// Since FValCon() is set it is redundant to check System.ValueType as well.
if (bnds.Count != 0 && bnds[0].IsPredefType(PredefinedType.PT_VALUE))
{
itypeMin = 1;
}
}
for (int j = itypeMin; j < bnds.Count; j++)
{
CType typeBnd = bnds[j];
if (!SatisfiesBound(checker, arg, typeBnd))
{
if (fReportErrors)
{
// The bound isn't satisfied because of a constraint type. Explain to the user why not.
// There are 4 main cases, based on the type of the supplied type argument:
// - reference type, or type parameter known to be a reference type
// - nullable type, from which there is a boxing conversion to the constraint type(see below for details)
// - type variable
// - value type
// These cases are broken out because: a) The sets of conversions which can be used
// for constraint satisfaction is different based on the type argument supplied,
// and b) Nullable is one funky type, and user's can use all the help they can get
// when using it.
ErrorCode error;
if (arg.IsReferenceType)
{
// A reference type can only satisfy bounds to types
// to which they have an implicit reference conversion
error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType;
}
else if (arg is NullableType nubArg && checker.SymbolLoader.HasBaseConversion(nubArg.UnderlyingType, typeBnd)) // This is inlining FBoxingConv
{
// nullable types do not satisfy bounds to every type that they are boxable to
// They only satisfy bounds of object and ValueType
if (typeBnd.IsPredefType(PredefinedType.PT_ENUM) || nubArg.UnderlyingType == typeBnd)
{
// Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum
// even though the conversion from Nullable to these types is a boxing conversion
// This is a rare case, because these bounds can never be directly stated ...
// These bounds can only occur when one type paramter is constrained to a second type parameter
// and the second type parameter is instantiated with Enum or the underlying type of the first type
// parameter
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum;
}
else
{
// Nullable types don't satisfy the bounds of any interface type
// even when there is a boxing conversion from the Nullable type to
// the interface type. This will be a relatively common scenario
// so we cal it out separately from the previous case.
Debug.Assert(typeBnd.IsInterfaceType);
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface;
}
}
else
{
// Value types can only satisfy bounds through boxing conversions.
// Note that the exceptional case of Nullable types and boxing is handled above.
error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType;
}
throw errHandling.Error(error, new ErrArg(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArg(arg, ErrArgFlags.Unique));
}
return false;
}
}
// Check the newable constraint.
if (!var.HasNewConstraint || arg.IsValueType)
{
return true;
}
if (arg.IsClassType)
{
AggregateSymbol agg = ((AggregateType)arg).OwningAggregate;
// Due to late binding nature of IDE created symbols, the AggregateSymbol might not
// have all the information necessary yet, if it is not fully bound.
// by calling LookupAggMember, it will ensure that we will update all the
// information necessary at least for the given method.
checker.SymbolLoader.LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL);
if (agg.HasPubNoArgCtor() && !agg.IsAbstract())
{
return true;
}
}
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Determine whether the arg type satisfies the typeBnd constraint. Note that
// typeBnd could be just about any type (since we added naked type parameter
// constraints).
private static bool SatisfiesBound(CSemanticChecker checker, CType arg, CType typeBnd)
{
if (typeBnd == arg)
return true;
switch (typeBnd.TypeKind)
{
default:
Debug.Assert(false, "Unexpected type.");
return false;
case TypeKind.TK_VoidType:
case TypeKind.TK_PointerType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_TypeParameterType:
break;
case TypeKind.TK_NullableType:
typeBnd = ((NullableType)typeBnd).GetAts();
break;
case TypeKind.TK_AggregateType:
break;
}
Debug.Assert(typeBnd is AggregateType || typeBnd is TypeParameterType || typeBnd is ArrayType);
switch (arg.TypeKind)
{
default:
return false;
case TypeKind.TK_PointerType:
return false;
case TypeKind.TK_NullableType:
arg = ((NullableType)arg).GetAts();
// Fall through.
goto case TypeKind.TK_TypeParameterType;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_AggregateType:
return checker.SymbolLoader.HasBaseConversion(arg, typeBnd);
}
}
}
}
| |
// GZipStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-11 21:42:34>
//
// ------------------------------------------------------------------
//
// This module defines the GZipStream class, which can be used as a replacement for
// the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
// completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
// GZip header.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Ionic2.Zlib
{
/// <summary>
/// A class for compressing and decompressing GZIP streams.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>GZipStream</c> is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a
/// <see cref="Stream"/>. It adds GZIP compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the
/// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while
/// reading, but not vice versa. The compression method used is GZIP, which is
/// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC
/// 1952</see>, "GZIP file format specification version 4.3".</para>
///
/// <para>
/// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or
/// to compress data (through <c>Write()</c>), but not both.
/// </para>
///
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it
/// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the
/// data will be compressed into the GZIP format. If you want to decompress data,
/// you must wrap the <c>GZipStream</c> around a readable stream that contains an
/// IETF RFC 1952-compliant stream. The data will be decompressed as you call
/// <c>Read()</c> on the <c>GZipStream</c>.
/// </para>
///
/// <para>
/// Though the GZIP format allows data from multiple files to be concatenated
/// together, this stream handles only a single segment of GZIP format, typically
/// representing a single file.
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>.
/// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/>
/// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.
/// </para>
///
/// </remarks>
///
/// <seealso cref="DeflateStream" />
/// <seealso cref="ZlibStream" />
public class GZipStream : System.IO.Stream
{
// GZip format
// source: http://tools.ietf.org/html/rfc1952
//
// header id: 2 bytes 1F 8B
// compress method 1 byte 8= DEFLATE (none other supported)
// flag 1 byte bitfield (See below)
// mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file.
// xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored)
// OS 1 byte OS for originating archive. set to 0xFF in compression.
// extra field length 2 bytes optional - only if FEXTRA is set.
// extra field varies
// filename varies optional - if FNAME is set. zero terminated. ISO-8859-1.
// file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1.
// crc16 1 byte optional - present only if FHCRC bit is set
// compressed data varies
// CRC32 4 bytes
// isize 4 bytes data size modulo 2^32
//
// FLG (FLaGs)
// bit 0 FTEXT - indicates file is ASCII text (can be safely ignored)
// bit 1 FHCRC - there is a CRC16 for the header immediately following the header
// bit 2 FEXTRA - extra fields are present
// bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1.
// bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1
// bit 5 reserved
// bit 6 reserved
// bit 7 reserved
//
// On consumption:
// Extra field is a bunch of nonsense and can be safely ignored.
// Header CRC and OS, likewise.
//
// on generation:
// all optional fields get 0, except for the OS, which gets 255.
//
/// <summary>
/// The comment on the GZIP stream.
/// </summary>
///
/// <remarks>
/// <para>
/// The GZIP format allows for each file to optionally have an associated
/// comment stored with the file. The comment is encoded with the ISO-8859-1
/// code page. To include a comment in a GZIP stream you create, set this
/// property before calling <c>Write()</c> for the first time on the
/// <c>GZipStream</c>.
/// </para>
///
/// <para>
/// When using <c>GZipStream</c> to decompress, you can retrieve this property
/// after the first call to <c>Read()</c>. If no comment has been set in the
/// GZIP bytestream, the Comment property will return <c>null</c>
/// (<c>Nothing</c> in VB).
/// </para>
/// </remarks>
public String Comment
{
get
{
return _Comment;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_Comment = value;
}
}
/// <summary>
/// The FileName for the GZIP stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The GZIP format optionally allows each file to have an associated
/// filename. When compressing data (through <c>Write()</c>), set this
/// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>.
/// The actual filename is encoded into the GZIP bytestream with the
/// ISO-8859-1 code page, according to RFC 1952. It is the application's
/// responsibility to insure that the FileName can be encoded and decoded
/// correctly with this code page.
/// </para>
///
/// <para>
/// When decompressing (through <c>Read()</c>), you can retrieve this value
/// any time after the first <c>Read()</c>. In the case where there was no filename
/// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c>
/// in VB).
/// </para>
/// </remarks>
public String FileName
{
get { return _FileName; }
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_FileName = value;
if (_FileName == null) return;
if (_FileName.IndexOf("/") != -1)
{
_FileName = _FileName.Replace("/", "\\");
}
if (_FileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (_FileName.IndexOf("\\") != -1)
{
// trim any leading path
_FileName = Path.GetFileName(_FileName);
}
}
}
/// <summary>
/// The last modified time for the GZIP stream.
/// </summary>
///
/// <remarks>
/// GZIP allows the storage of a last modified time with each GZIP entry.
/// When compressing data, you can set this before the first call to
/// <c>Write()</c>. When decompressing, you can retrieve this value any time
/// after the first call to <c>Read()</c>.
/// </remarks>
public DateTime? LastModified;
/// <summary>
/// The CRC on the GZIP stream.
/// </summary>
/// <remarks>
/// This is used for internal error checking. You probably don't need to look at this property.
/// </remarks>
public int Crc32 { get { return _Crc32; } }
private int _headerByteCount;
internal ZlibBaseStream _baseStream;
bool _disposed;
bool _firstReadDone;
string _FileName;
string _Comment;
int _Crc32;
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the
/// default compression level.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with
/// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a GZipStream to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <example>
/// This example shows how to use a GZipStream to uncompress a file.
/// <code>
/// private void GunZipFile(string filename)
/// {
/// if (!filename.EndsWith(".gz))
/// throw new ArgumentException("filename");
/// var DecompressedFile = filename.Substring(0,filename.Length-3);
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// int n= 1;
/// using (System.IO.Stream input = System.IO.File.OpenRead(filename))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(DecompressedFile))
/// {
/// while (n !=0)
/// {
/// n= decompressor.Read(working, 0, working.Length);
/// if (n > 0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Private Sub GunZipFile(ByVal filename as String)
/// If Not (filename.EndsWith(".gz)) Then
/// Throw New ArgumentException("filename")
/// End If
/// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
/// Dim working(WORKING_BUFFER_SIZE) as Byte
/// Dim n As Integer = 1
/// Using input As Stream = File.OpenRead(filename)
/// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
/// Using output As Stream = File.Create(UncompressedFile)
/// Do
/// n= decompressor.Read(working, 0, working.Length)
/// If n > 0 Then
/// output.Write(working, 0, n)
/// End IF
/// Loop While (n > 0)
/// End Using
/// End Using
/// End Using
/// End Sub
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
public GZipStream(Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>CompressionMode</c> (Compress or Decompress) also establishes the
/// "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A
/// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
/// {
/// using (Stream compressor = new GZipStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".gz")
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the stream should be left open after Deflation
/// or Inflation.
/// </summary>
///
/// <remarks>
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave
/// the stream open.
/// </para>
///
/// <para>
/// The <see cref="CompressionMode"/> (Compress or Decompress) also
/// establishes the "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c>
/// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// <para>
/// The <c>GZipStream</c> will use the default compression level. If you want
/// to specify the compression level, see <see cref="GZipStream(Stream,
/// CompressionMode, CompressionLevel, bool)"/>.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the "captive"
/// stream in other places in this documentation.
/// </param>
///
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">
/// true if the application would like the base stream to remain open after
/// inflation/deflation.
/// </param>
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the
/// specified <c>CompressionLevel</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to
/// leave the stream open.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a <c>GZipStream</c> to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen);
}
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
virtual public FlushType FlushMode
{
get { return (_baseStream._flushMode); }
set {
if (_disposed) throw new ObjectDisposedException("GZipStream");
_baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return _baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (_baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
_baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return _baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return _baseStream._z.TotalBytesOut;
}
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (_baseStream != null))
{
_baseStream.Close();
_Crc32 = _baseStream.Crc32;
}
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Writer)
return _baseStream._z.TotalBytesOut + _headerByteCount;
if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Reader)
return _baseStream._z.TotalBytesIn + _baseStream._gzipHeaderByteCount;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read and decompress data from the source stream.
/// </summary>
///
/// <remarks>
/// With a <c>GZipStream</c>, decompression is done through reading.
/// </remarks>
///
/// <example>
/// <code>
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(_DecompressedFile))
/// {
/// int n;
/// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
/// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
int n = _baseStream.Read(buffer, offset, count);
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
if (!_firstReadDone)
{
_firstReadDone = true;
FileName = _baseStream._GzipFileName;
Comment = _baseStream._GzipComment;
}
return n;
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">irrelevant; it will always throw!</param>
/// <param name="origin">irrelevant; it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">irrelevant; this method will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data while writing,
/// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>,
/// providing uncompressed data as input. The data sent to the output stream
/// will be the compressed form of the data written.
/// </para>
///
/// <para>
/// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not
/// both. Writing implies compression. Reading implies decompression.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Undefined)
{
//Console.WriteLine("GZipStream: First write");
if (_baseStream._wantCompress)
{
// first write in compression, therefore, emit the GZIP header
_headerByteCount = EmitHeader();
}
else
{
throw new InvalidOperationException();
}
}
_baseStream.Write(buffer, offset, count);
}
internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static readonly System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1");
private int EmitHeader()
{
byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment);
byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName);
int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1;
int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1;
int bufferLength = 10 + cbLength + fnLength;
byte[] header = new byte[bufferLength];
int i = 0;
// ID
header[i++] = 0x1F;
header[i++] = 0x8B;
// compression method
header[i++] = 8;
byte flag = 0;
if (Comment != null)
flag ^= 0x10;
if (FileName != null)
flag ^= 0x8;
// flag
header[i++] = flag;
// mtime
if (!LastModified.HasValue) LastModified = DateTime.Now;
System.TimeSpan delta = LastModified.Value - _unixEpoch;
Int32 timet = (Int32)delta.TotalSeconds;
Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4);
i += 4;
// xflg
header[i++] = 0; // this field is totally useless
// OS
header[i++] = 0xFF; // 0xFF == unspecified
// extra field length - only if FEXTRA is set, which it is not.
//header[i++]= 0;
//header[i++]= 0;
// filename
if (fnLength != 0)
{
Array.Copy(filenameBytes, 0, header, i, fnLength - 1);
i += fnLength - 1;
header[i++] = 0; // terminate
}
// comment
if (cbLength != 0)
{
Array.Copy(commentBytes, 0, header, i, cbLength - 1);
i += cbLength - 1;
header[i++] = 0; // terminate
}
_baseStream._stream.Write(header, 0, header.Length);
return header.Length; // bytes written
}
/// <summary>
/// Compress a string into a byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.CompressString(string)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a single string.
/// </summary>
///
/// <seealso cref="GZipStream.CompressString(String)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing GZIP-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor = new GZipStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a byte array.
/// </summary>
///
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with GZip.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new GZipStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Resources;
using System.Runtime.Serialization;
using System.Globalization;
using System.Diagnostics;
namespace System.Xml.Schema
{
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException"]/*' />
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class XmlSchemaException : SystemException
{
private string _res;
private string[] _args;
private string _sourceUri;
private int _lineNumber;
private int _linePosition;
private XmlSchemaObject _sourceSchemaObject;
// message != null for V1 exceptions deserialized in Whidbey
// message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message)
private string _message;
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException5"]/*' />
protected XmlSchemaException(SerializationInfo info, StreamingContext context) : base(info, context)
{
_res = (string)info.GetValue("res", typeof(string));
_args = (string[])info.GetValue("args", typeof(string[]));
_sourceUri = (string)info.GetValue("sourceUri", typeof(string));
_lineNumber = (int)info.GetValue("lineNumber", typeof(int));
_linePosition = (int)info.GetValue("linePosition", typeof(int));
// deserialize optional members
string version = null;
foreach (SerializationEntry e in info)
{
if (e.Name == "version")
{
version = (string)e.Value;
}
}
if (version == null)
{
// deserializing V1 exception
_message = CreateMessage(_res, _args);
}
else
{
// deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message)
_message = null;
}
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.GetObjectData"]/*' />
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("res", _res);
info.AddValue("args", _args);
info.AddValue("sourceUri", _sourceUri);
info.AddValue("lineNumber", _lineNumber);
info.AddValue("linePosition", _linePosition);
info.AddValue("version", "2.0");
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException1"]/*' />
public XmlSchemaException() : this(null)
{
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException2"]/*' />
public XmlSchemaException(String message) : this(message, ((Exception)null), 0, 0)
{
#if DEBUG
Debug.Assert(message == null || !message.StartsWith("Sch_", StringComparison.Ordinal), "Do not pass a resource here!");
#endif
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException0"]/*' />
public XmlSchemaException(String message, Exception innerException) : this(message, innerException, 0, 0)
{
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException3"]/*' />
public XmlSchemaException(String message, Exception innerException, int lineNumber, int linePosition) :
this((message == null ? SR.Sch_DefaultException : SR.Xml_UserException), new string[] { message }, innerException, null, lineNumber, linePosition, null)
{
}
internal XmlSchemaException(string res, string[] args) :
this(res, args, null, null, 0, 0, null)
{ }
internal XmlSchemaException(string res, string arg) :
this(res, new string[] { arg }, null, null, 0, 0, null)
{ }
internal XmlSchemaException(string res, string arg, string sourceUri, int lineNumber, int linePosition) :
this(res, new string[] { arg }, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, string sourceUri, int lineNumber, int linePosition) :
this(res, (string[])null, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, string[] args, string sourceUri, int lineNumber, int linePosition) :
this(res, args, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, XmlSchemaObject source) :
this(res, (string[])null, source)
{ }
internal XmlSchemaException(string res, string arg, XmlSchemaObject source) :
this(res, new string[] { arg }, source)
{ }
internal XmlSchemaException(string res, string[] args, XmlSchemaObject source) :
this(res, args, null, source.SourceUri, source.LineNumber, source.LinePosition, source)
{ }
internal XmlSchemaException(string res, string[] args, Exception innerException, string sourceUri, int lineNumber, int linePosition, XmlSchemaObject source) :
base(CreateMessage(res, args), innerException)
{
HResult = HResults.XmlSchema;
_res = res;
_args = args;
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
_sourceSchemaObject = source;
}
internal static string CreateMessage(string res, string[] args)
{
try
{
if (args == null)
{
return res;
}
return string.Format(res, args);
}
catch (MissingManifestResourceException)
{
return "UNKNOWN(" + res + ")";
}
}
internal string GetRes
{
get
{
return _res;
}
}
internal string[] Args
{
get
{
return _args;
}
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceUri"]/*' />
public string SourceUri
{
get { return _sourceUri; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LineNumber"]/*' />
public int LineNumber
{
get { return _lineNumber; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LinePosition"]/*' />
public int LinePosition
{
get { return _linePosition; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceObject"]/*' />
public XmlSchemaObject SourceSchemaObject
{
get { return _sourceSchemaObject; }
}
/*internal static XmlSchemaException Create(string res) { //Since internal overload with res string will clash with public constructor that takes in a message
return new XmlSchemaException(res, (string[])null, null, null, 0, 0, null);
}*/
internal void SetSource(string sourceUri, int lineNumber, int linePosition)
{
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
internal void SetSchemaObject(XmlSchemaObject source)
{
_sourceSchemaObject = source;
}
internal void SetSource(XmlSchemaObject source)
{
_sourceSchemaObject = source;
_sourceUri = source.SourceUri;
_lineNumber = source.LineNumber;
_linePosition = source.LinePosition;
}
public override string Message
{
get
{
return (_message == null) ? base.Message : _message;
}
}
};
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using Prism.Properties;
using Microsoft.Practices.ServiceLocation;
namespace Prism.Regions
{
/// <summary>
/// Implementation of <see cref="IRegion"/> that allows multiple active views.
/// </summary>
public class Region : IRegion
{
private ObservableCollection<ItemMetadata> itemMetadataCollection;
private string name;
private ViewsCollection views;
private ViewsCollection activeViews;
private object context;
private IRegionManager regionManager;
private IRegionNavigationService regionNavigationService;
private Comparison<object> sort;
/// <summary>
/// Initializes a new instance of <see cref="Region"/>.
/// </summary>
public Region()
{
this.Behaviors = new RegionBehaviorCollection(this);
this.sort = Region.DefaultSortComparison;
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the collection of <see cref="IRegionBehavior"/>s that can extend the behavior of regions.
/// </summary>
public IRegionBehaviorCollection Behaviors { get; private set; }
/// <summary>
/// Gets or sets a context for the region. This value can be used by the user to share context with the views.
/// </summary>
/// <value>The context value to be shared.</value>
public object Context
{
get
{
return this.context;
}
set
{
if (this.context != value)
{
this.context = value;
this.OnPropertyChanged("Context");
}
}
}
/// <summary>
/// Gets the name of the region that uniequely identifies the region within a <see cref="IRegionManager"/>.
/// </summary>
/// <value>The name of the region.</value>
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != null && this.name != value)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeRegionNameException, this.name));
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(Resources.RegionNameCannotBeEmptyException);
}
this.name = value;
this.OnPropertyChanged("Name");
}
}
/// <summary>
/// Gets a readonly view of the collection of views in the region.
/// </summary>
/// <value>An <see cref="IViewsCollection"/> of all the added views.</value>
public virtual IViewsCollection Views
{
get
{
if (this.views == null)
{
this.views = new ViewsCollection(ItemMetadataCollection, x => true);
this.views.SortComparison = this.sort;
}
return this.views;
}
}
/// <summary>
/// Gets a readonly view of the collection of all the active views in the region.
/// </summary>
/// <value>An <see cref="IViewsCollection"/> of all the active views.</value>
public virtual IViewsCollection ActiveViews
{
get
{
if (this.activeViews == null)
{
this.activeViews = new ViewsCollection(ItemMetadataCollection, x => x.IsActive);
this.activeViews.SortComparison = this.sort;
}
return this.activeViews;
}
}
/// <summary>
/// Gets or sets the comparison used to sort the views.
/// </summary>
/// <value>The comparison to use.</value>
public Comparison<object> SortComparison
{
get
{
return this.sort;
}
set
{
this.sort = value;
if (this.activeViews != null)
{
this.activeViews.SortComparison = this.sort;
}
if (this.views != null)
{
this.views.SortComparison = this.sort;
}
}
}
/// <summary>
/// Gets or sets the <see cref="IRegionManager"/> that will be passed to the views when adding them to the region, unless the view is added by specifying createRegionManagerScope as <see langword="true" />.
/// </summary>
/// <value>The <see cref="IRegionManager"/> where this <see cref="IRegion"/> is registered.</value>
/// <remarks>This is usually used by implementations of <see cref="IRegionManager"/> and should not be
/// used by the developer explicitely.</remarks>
public IRegionManager RegionManager
{
get
{
return this.regionManager;
}
set
{
if (this.regionManager != value)
{
this.regionManager = value;
this.OnPropertyChanged("RegionManager");
}
}
}
/// <summary>
/// Gets the navigation service.
/// </summary>
/// <value>The navigation service.</value>
public IRegionNavigationService NavigationService
{
get
{
if (this.regionNavigationService == null)
{
this.regionNavigationService = ServiceLocator.Current.GetInstance<IRegionNavigationService>();
this.regionNavigationService.Region = this;
}
return this.regionNavigationService;
}
set
{
this.regionNavigationService = value;
}
}
/// <summary>
/// Gets the collection with all the views along with their metadata.
/// </summary>
/// <value>An <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> with all the added views.</value>
protected virtual ObservableCollection<ItemMetadata> ItemMetadataCollection
{
get
{
if (this.itemMetadataCollection == null)
{
this.itemMetadataCollection = new ObservableCollection<ItemMetadata>();
}
return this.itemMetadataCollection;
}
}
/// <overloads>Adds a new view to the region.</overloads>
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns>
public IRegionManager Add(object view)
{
return this.Add(view, null, false);
}
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns>
public IRegionManager Add(object view, string viewName)
{
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName"));
}
return this.Add(view, viewName, false);
}
/// <summary>
/// Adds a new view to the region.
/// </summary>
/// <param name="view">The view to add.</param>
/// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param>
/// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param>
/// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns>
public virtual IRegionManager Add(object view, string viewName, bool createRegionManagerScope)
{
IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager;
this.InnerAdd(view, viewName, manager);
return manager;
}
/// <summary>
/// Removes the specified view from the region.
/// </summary>
/// <param name="view">The view to remove.</param>
public virtual void Remove(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
this.ItemMetadataCollection.Remove(itemMetadata);
DependencyObject dependencyObject = view as DependencyObject;
if (dependencyObject != null && Regions.RegionManager.GetRegionManager(dependencyObject) == this.RegionManager)
{
dependencyObject.ClearValue(Regions.RegionManager.RegionManagerProperty);
}
}
/// <summary>
/// Marks the specified view as active.
/// </summary>
/// <param name="view">The view to activate.</param>
public virtual void Activate(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
if (!itemMetadata.IsActive)
{
itemMetadata.IsActive = true;
}
}
/// <summary>
/// Marks the specified view as inactive.
/// </summary>
/// <param name="view">The view to deactivate.</param>
public virtual void Deactivate(object view)
{
ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view);
if (itemMetadata.IsActive)
{
itemMetadata.IsActive = false;
}
}
/// <summary>
/// Returns the view instance that was added to the region using a specific name.
/// </summary>
/// <param name="viewName">The name used when adding the view to the region.</param>
/// <returns>Returns the named view or <see langword="null"/> if the view with <paramref name="viewName"/> does not exist in the current region.</returns>
public virtual object GetView(string viewName)
{
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName"));
}
ItemMetadata metadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName);
if (metadata != null)
{
return metadata.Item;
}
return null;
}
/// <summary>
/// Initiates navigation to the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param>
public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback)
{
this.RequestNavigate(target, navigationCallback, null);
}
/// <summary>
/// Initiates navigation to the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param>
/// <param name="navigationParameters">The navigation parameters specific to the navigation request.</param>
public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
this.NavigationService.RequestNavigate(target, navigationCallback, navigationParameters);
}
private void InnerAdd(object view, string viewName, IRegionManager scopedRegionManager)
{
if (this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view) != null)
{
throw new InvalidOperationException(Resources.RegionViewExistsException);
}
ItemMetadata itemMetadata = new ItemMetadata(view);
if (!string.IsNullOrEmpty(viewName))
{
if (this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName) != null)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.RegionViewNameExistsException, viewName));
}
itemMetadata.Name = viewName;
}
DependencyObject dependencyObject = view as DependencyObject;
if (dependencyObject != null)
{
Regions.RegionManager.SetRegionManager(dependencyObject, scopedRegionManager);
}
this.ItemMetadataCollection.Add(itemMetadata);
}
private ItemMetadata GetItemMetadataOrThrow(object view)
{
if (view == null)
{
throw new ArgumentNullException("view");
}
ItemMetadata itemMetadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view);
if (itemMetadata == null)
{
throw new ArgumentException(Resources.ViewNotInRegionException, "view");
}
return itemMetadata;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// The default sort algorithm.
/// </summary>
/// <param name="x">The first view to compare.</param>
/// <param name="y">The second view to compare.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")]
public static int DefaultSortComparison(object x, object y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
Type xType = x.GetType();
Type yType = y.GetType();
ViewSortHintAttribute xAttribute = xType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute;
ViewSortHintAttribute yAttribute = yType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute;
return ViewSortHintAttributeComparison(xAttribute, yAttribute);
}
}
}
private static int ViewSortHintAttributeComparison(ViewSortHintAttribute x, ViewSortHintAttribute y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
return string.Compare(x.Hint, y.Hint, StringComparison.Ordinal);
}
}
}
}
}
| |
#region License
//
// PrimitiveList.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>PrimitiveList</c> object is used to convert an element
/// list to a collection of element entries. This in effect performs a
/// serialization and deserialization of primitive entry elements for
/// the collection object. On serialization each objects type must be
/// checked against the XML annotation entry so that it is serialized
/// in a form that can be deserialized.
/// </code>
/// <list>
/// <entry>example one</entry>
/// <entry>example two</entry>
/// <entry>example three</entry>
/// <entry>example four</entry>
/// </list>
/// </code>
/// For the above XML element list the element <c>entry</c> is
/// used to wrap the primitive string value. This wrapping XML element
/// is configurable and defaults to the lower case string for the name
/// of the class it represents. So, for example, if the primitive type
/// is an <c>int</c> the enclosing element will be called int.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Core.Primitive
/// </seealso>
/// <seealso>
/// SimpleFramework.Xml.ElementList
/// </seealso>
class PrimitiveList : Converter {
/// <summary>
/// This factory is used to create a suitable collection list.
/// </summary>
private readonly CollectionFactory factory;
/// <summary>
/// This performs the serialization of the primitive element.
/// </summary>
private readonly Primitive root;
/// <summary>
/// This is the name that each array element is wrapped with.
/// </summary>
private readonly String parent;
/// <summary>
/// This is the type of object that will be held within the list.
/// </summary>
private readonly Type entry;
/// <summary>
/// Constructor for the <c>PrimitiveList</c> object. This is
/// given the list type and entry type to be used. The list type is
/// the <c>Collection</c> implementation that deserialized
/// entry objects are inserted into.
/// </summary>
/// <param name="context">
/// this is the context object used for serialization
/// </param>
/// <param name="type">
/// this is the collection type for the list used
/// </param>
/// <param name="entry">
/// the primitive type to be stored within the list
/// </param>
/// <param name="parent">
/// this is the name to wrap the list element with
/// </param>
public PrimitiveList(Context context, Type type, Type entry, String parent) {
this.factory = new CollectionFactory(context, type);
this.root = new Primitive(context, entry);
this.parent = parent;
this.entry = entry;
}
/// <summary>
/// This <c>read</c> method will read the XML element list from
/// the provided node and deserialize its children as entry types.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node) {
Instance type = factory.GetInstance(node);
Object list = type.Instance;
if(!type.isReference()) {
return Populate(node, list);
}
return list;
}
/// <summary>
/// This <c>read</c> method will read the XML element map from
/// the provided node and deserialize its children as entry types.
/// Each entry type must contain a key and value so that the entry
/// can be inserted in to the map as a pair. If either the key or
/// value is composite it is read as a root object, which means its
/// <c>Root</c> annotation must be present and the name of the
/// object element must match that root element name.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <param name="result">
/// this is the map object that is to be populated
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node, Object result) {
Instance type = factory.GetInstance(node);
if(type.isReference()) {
return type.Instance;
}
type.setInstance(result);
if(result != null) {
return Populate(node, result);
}
return result;
}
/// <summary>
/// This <c>populate</c> method wll read the XML element list
/// from the provided node and deserialize its children as entry types.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <param name="result">
/// this is the collection that is to be populated
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Populate(InputNode node, Object result) {
Collection list = (Collection) result;
while(true) {
InputNode next = node.getNext();
if(next == null) {
return list;
}
list.add(root.Read(next));
}
}
/// <summary>
/// This <c>validate</c> method wll validate the XML element list
/// from the provided node and validate its children as entry types.
/// This will validate each entry type as a primitive value. In order
/// to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node) {
Instance value = factory.GetInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class expect = value.Type;
return Validate(node, expect);
}
return true;
}
/// <summary>
/// This <c>validate</c> method will validate the XML element list
/// from the provided node and validate its children as entry types.
/// This will validate each entry type as a primitive value. In order
/// to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <param name="type">
/// this is the type to validate against the input node
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node, Class type) {
while(true) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
root.Validate(next);
}
}
/// <summary>
/// This <c>write</c> method will write the specified object
/// to the given XML element as as list entries. Each entry within
/// the given list must be assignable to the given primitive type.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="source">
/// this is the source object array to be serialized
/// </param>
/// <param name="node">
/// this is the XML element container to be populated
/// </param>
public void Write(OutputNode node, Object source) {
Collection list = (Collection) source;
for(Object item : list) {
if(item != null) {
OutputNode child = node.getChild(parent);
if(!IsOverridden(child, item)) {
root.Write(child, item);
}
}
}
}
/// <summary>
/// This is used to determine whether the specified value has been
/// overridden by the strategy. If the item has been overridden
/// then no more serialization is require for that value, this is
/// effectively telling the serialization process to stop writing.
/// </summary>
/// <param name="node">
/// the node that a potential override is written to
/// </param>
/// <param name="value">
/// this is the object instance to be serialized
/// </param>
/// <returns>
/// returns true if the strategy overrides the object
/// </returns>
public bool IsOverridden(OutputNode node, Object value) {
return factory.setOverride(entry, value, node);
}
}
}
| |
// Copyright (C) 2014 Weekend Game Studio
//
// 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.
#region Using Statements
using System;
using WaveEngine.Common;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Components.Cameras;
using WaveEngine.Components.Graphics2D;
using WaveEngine.Components.Graphics3D;
using WaveEngine.Components.UI;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Resources;
using WaveEngine.Framework.Services;
using WaveEngine.Framework.UI;
#endregion
namespace ProgressBarSampleProject
{
public class MyScene : Scene
{
ProgressBar progressbar1, progressbar2, progressbar3, progressbar4;
TextBlock textblock1, textblock2, textblock3, textblock4, info1, info2;
Button button1, button2;
Image image;
protected override void CreateScene()
{
FixedCamera2D camera2d = new FixedCamera2D("camera");
camera2d.BackgroundColor = Color.Gray;
EntityManager.Add(camera2d);
// Progress 1
int progress1Top = 20;
int spacing = 40;
textblock1 = new TextBlock()
{
Margin = new Thickness(20, progress1Top, 0, 0),
Text = "Range: [0, 100] Value = 23",
};
EntityManager.Add(textblock1.Entity);
progressbar1 = new ProgressBar()
{
Margin = new Thickness(20, progress1Top + spacing, 0, 0),
Width = 360,
Value = 23,
};
EntityManager.Add(progressbar1.Entity);
// Progress 2
int progress2Top = 120;
textblock2 = new TextBlock()
{
Margin = new Thickness(20, progress2Top, 0, 0),
Text = "Range: [-21, 300] Value= -5",
};
EntityManager.Add(textblock2.Entity);
progressbar2 = new ProgressBar()
{
Margin = new Thickness(20, progress2Top + spacing, 0, 0),
Width = 360,
Minimum = -21,
Maximum = 300,
Value = -5,
Foreground = Color.OliveDrab,
Background = Color.LightGreen,
};
EntityManager.Add(progressbar2.Entity);
// Progress 3
int progress3Top = 220;
textblock3 = new TextBlock()
{
Margin = new Thickness(20, progress3Top, 0, 0),
Text = "Range: [400, 600] InitValue: 580",
};
EntityManager.Add(textblock3.Entity);
progressbar3 = new ProgressBar()
{
Margin = new Thickness(20, progress3Top + spacing, 0, 0),
Width = 360,
Minimum = 400,
Maximum = 600,
Value = 580,
Foreground = Color.Purple,
Background = Color.LightPink,
};
progressbar3.ValueChanged += progressbar3_ValueChanged;
EntityManager.Add(progressbar3.Entity);
button1 = new Button()
{
Margin = new Thickness(20, progress3Top + spacing * 2, 0, 0),
Text = "Down",
Foreground = Color.Gray,
BackgroundColor = Color.LightBlue,
BorderColor = Color.LightBlue,
};
button1.Click += button1_Click;
EntityManager.Add(button1.Entity);
info1 = new TextBlock()
{
Margin = new Thickness(20, progress3Top + spacing * 3, 0, 0),
Text = string.Empty,
Foreground = Color.Purple,
};
EntityManager.Add(info1.Entity);
// Progress 4
int progress4Top = 380;
textblock4 = new TextBlock()
{
Margin = new Thickness(20, progress4Top, 0, 0),
Text = "Range: [-300, -100] InitValue: -280",
};
EntityManager.Add(textblock4.Entity);
progressbar4 = new ProgressBar()
{
Margin = new Thickness(20, progress4Top + spacing, 0, 0),
Width = 360,
Minimum = -300,
Maximum = -100,
Value = -280,
Foreground = Color.Purple,
Background = Color.LightPink,
};
progressbar4.ValueChanged += progressbar4_ValueChanged;
EntityManager.Add(progressbar4.Entity);
button2 = new Button()
{
Margin = new Thickness(20, progress4Top + spacing * 2, 0, 0),
Text = "Up",
Foreground = Color.Gray,
BackgroundColor = Color.LightBlue,
BorderColor = Color.LightBlue,
};
button2.Click += button2_Click;
EntityManager.Add(button2.Entity);
info2 = new TextBlock()
{
Margin = new Thickness(20, progress4Top + spacing * 3, 0, 0),
Text = string.Empty,
Foreground = Color.Purple,
};
EntityManager.Add(info2.Entity);
// Image Check
AddCheckImage("Content/ProgressBarSample.wpk");
}
/// <summary>
/// Handles the Click event of the button2 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void button2_Click(object sender, EventArgs e)
{
int currentvalue = progressbar4.Value;
if (currentvalue + 20 <= progressbar4.Maximum)
{
progressbar4.Value += 20;
}
else
{
progressbar4.Value = progressbar4.Minimum;
}
}
/// <summary>
/// Handles the ValueChanged event of the progressbar4 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ChangedEventArgs" /> instance containing the event data.</param>
void progressbar4_ValueChanged(object sender, ChangedEventArgs e)
{
info2.Text = "NewValue: " + e.NewValue + " OldValue: " + e.OldValue;
}
/// <summary>
/// Handles the ValueChanged event of the progressbar3 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ChangedEventArgs" /> instance containing the event data.</param>
void progressbar3_ValueChanged(object sender, ChangedEventArgs e)
{
info1.Text = "NewValue: " + e.NewValue + " OldValue: " + e.OldValue;
}
/// <summary>
/// Handles the Click event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void button1_Click(object sender, EventArgs e)
{
int currentvalue = progressbar3.Value;
if (currentvalue - 20 >= progressbar3.Minimum)
{
progressbar3.Value -= 20;
}
else
{
progressbar3.Value = progressbar3.Maximum;
}
}
/// <summary>
/// Adds the check image.
/// </summary>
/// <param name="filename">The filename.</param>
private void AddCheckImage(string filename)
{
image = new Image(filename)
{
Margin = new Thickness(400, 0, 0, 0),
Width = 400,
Height = 600,
};
EntityManager.Add(image.Entity);
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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;
namespace Spine {
/// <summary>
/// Collects each BoundingBoxAttachment that is visible and computes the world vertices for its polygon.
/// The polygon vertices are provided along with convenience methods for doing hit detection.
/// </summary>
public class SkeletonBounds {
private ExposedList<Polygon> polygonPool = new ExposedList<Polygon>();
private float minX, minY, maxX, maxY;
public ExposedList<BoundingBoxAttachment> BoundingBoxes { get; private set; }
public ExposedList<Polygon> Polygons { get; private set; }
public float MinX { get { return minX; } set { minX = value; } }
public float MinY { get { return minY; } set { minY = value; } }
public float MaxX { get { return maxX; } set { maxX = value; } }
public float MaxY { get { return maxY; } set { maxY = value; } }
public float Width { get { return maxX - minX; } }
public float Height { get { return maxY - minY; } }
public SkeletonBounds () {
BoundingBoxes = new ExposedList<BoundingBoxAttachment>();
Polygons = new ExposedList<Polygon>();
}
/// <summary>
/// Clears any previous polygons, finds all visible bounding box attachments,
/// and computes the world vertices for each bounding box's polygon.</summary>
/// <param name="skeleton">The skeleton.</param>
/// <param name="updateAabb">
/// If true, the axis aligned bounding box containing all the polygons is computed.
/// If false, the SkeletonBounds AABB methods will always return true.
/// </param>
public void Update (Skeleton skeleton, bool updateAabb) {
ExposedList<BoundingBoxAttachment> boundingBoxes = BoundingBoxes;
ExposedList<Polygon> polygons = Polygons;
ExposedList<Slot> slots = skeleton.slots;
int slotCount = slots.Count;
boundingBoxes.Clear();
for (int i = 0, n = polygons.Count; i < n; i++)
polygonPool.Add(polygons.Items[i]);
polygons.Clear();
for (int i = 0; i < slotCount; i++) {
Slot slot = slots.Items[i];
BoundingBoxAttachment boundingBox = slot.attachment as BoundingBoxAttachment;
if (boundingBox == null) continue;
boundingBoxes.Add(boundingBox);
Polygon polygon = null;
int poolCount = polygonPool.Count;
if (poolCount > 0) {
polygon = polygonPool.Items[poolCount - 1];
polygonPool.RemoveAt(poolCount - 1);
} else
polygon = new Polygon();
polygons.Add(polygon);
int count = boundingBox.worldVerticesLength;
polygon.Count = count;
if (polygon.Vertices.Length < count) polygon.Vertices = new float[count];
boundingBox.ComputeWorldVertices(slot, polygon.Vertices);
}
if (updateAabb) {
AabbCompute();
} else {
minX = int.MinValue;
minY = int.MinValue;
maxX = int.MaxValue;
maxY = int.MaxValue;
}
}
private void AabbCompute () {
float minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
ExposedList<Polygon> polygons = Polygons;
for (int i = 0, n = polygons.Count; i < n; i++) {
Polygon polygon = polygons.Items[i];
float[] vertices = polygon.Vertices;
for (int ii = 0, nn = polygon.Count; ii < nn; ii += 2) {
float x = vertices[ii];
float y = vertices[ii + 1];
minX = Math.Min(minX, x);
minY = Math.Min(minY, y);
maxX = Math.Max(maxX, x);
maxY = Math.Max(maxY, y);
}
}
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
/// <summary>Returns true if the axis aligned bounding box contains the point.</summary>
public bool AabbContainsPoint (float x, float y) {
return x >= minX && x <= maxX && y >= minY && y <= maxY;
}
/// <summary>Returns true if the axis aligned bounding box intersects the line segment.</summary>
public bool AabbIntersectsSegment (float x1, float y1, float x2, float y2) {
float minX = this.minX;
float minY = this.minY;
float maxX = this.maxX;
float maxY = this.maxY;
if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
return false;
float m = (y2 - y1) / (x2 - x1);
float y = m * (minX - x1) + y1;
if (y > minY && y < maxY) return true;
y = m * (maxX - x1) + y1;
if (y > minY && y < maxY) return true;
float x = (minY - y1) / m + x1;
if (x > minX && x < maxX) return true;
x = (maxY - y1) / m + x1;
if (x > minX && x < maxX) return true;
return false;
}
/// <summary>Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds.</summary>
public bool AabbIntersectsSkeleton (SkeletonBounds bounds) {
return minX < bounds.maxX && maxX > bounds.minX && minY < bounds.maxY && maxY > bounds.minY;
}
/// <summary>Returns true if the polygon contains the point.</summary>
public bool ContainsPoint (Polygon polygon, float x, float y) {
float[] vertices = polygon.Vertices;
int nn = polygon.Count;
int prevIndex = nn - 2;
bool inside = false;
for (int ii = 0; ii < nn; ii += 2) {
float vertexY = vertices[ii + 1];
float prevY = vertices[prevIndex + 1];
if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) {
float vertexX = vertices[ii];
if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) inside = !inside;
}
prevIndex = ii;
}
return inside;
}
/// <summary>Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more
/// efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true.</summary>
public BoundingBoxAttachment ContainsPoint (float x, float y) {
ExposedList<Polygon> polygons = Polygons;
for (int i = 0, n = polygons.Count; i < n; i++)
if (ContainsPoint(polygons.Items[i], x, y)) return BoundingBoxes.Items[i];
return null;
}
/// <summary>Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually
/// more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true.</summary>
public BoundingBoxAttachment IntersectsSegment (float x1, float y1, float x2, float y2) {
ExposedList<Polygon> polygons = Polygons;
for (int i = 0, n = polygons.Count; i < n; i++)
if (IntersectsSegment(polygons.Items[i], x1, y1, x2, y2)) return BoundingBoxes.Items[i];
return null;
}
/// <summary>Returns true if the polygon contains the line segment.</summary>
public bool IntersectsSegment (Polygon polygon, float x1, float y1, float x2, float y2) {
float[] vertices = polygon.Vertices;
int nn = polygon.Count;
float width12 = x1 - x2, height12 = y1 - y2;
float det1 = x1 * y2 - y1 * x2;
float x3 = vertices[nn - 2], y3 = vertices[nn - 1];
for (int ii = 0; ii < nn; ii += 2) {
float x4 = vertices[ii], y4 = vertices[ii + 1];
float det2 = x3 * y4 - y3 * x4;
float width34 = x3 - x4, height34 = y3 - y4;
float det3 = width12 * height34 - height12 * width34;
float x = (det1 * width34 - width12 * det2) / det3;
if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) {
float y = (det1 * height34 - height12 * det2) / det3;
if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true;
}
x3 = x4;
y3 = y4;
}
return false;
}
public Polygon GetPolygon (BoundingBoxAttachment attachment) {
int index = BoundingBoxes.IndexOf(attachment);
return index == -1 ? null : Polygons.Items[index];
}
}
public class Polygon {
public float[] Vertices { get; set; }
public int Count { get; set; }
public Polygon () {
Vertices = new float[16];
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class AccountSharedAccess : IEquatable<AccountSharedAccess>
{
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response.</value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set.</value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.</value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The account ID associated with the envelope.
/// </summary>
/// <value>The account ID associated with the envelope.</value>
[DataMember(Name="accountId", EmitDefaultValue=false)]
public string AccountId { get; set; }
/// <summary>
/// A complex type containing the shared access information to an envelope for the users specified in the request.
/// </summary>
/// <value>A complex type containing the shared access information to an envelope for the users specified in the request.</value>
[DataMember(Name="sharedAccess", EmitDefaultValue=false)]
public List<MemberSharedItems> SharedAccess { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AccountSharedAccess {\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" AccountId: ").Append(AccountId).Append("\n");
sb.Append(" SharedAccess: ").Append(SharedAccess).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AccountSharedAccess);
}
/// <summary>
/// Returns true if AccountSharedAccess instances are equal
/// </summary>
/// <param name="other">Instance of AccountSharedAccess to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AccountSharedAccess other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.AccountId == other.AccountId ||
this.AccountId != null &&
this.AccountId.Equals(other.AccountId)
) &&
(
this.SharedAccess == other.SharedAccess ||
this.SharedAccess != null &&
this.SharedAccess.SequenceEqual(other.SharedAccess)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ResultSetSize != null)
hash = hash * 57 + this.ResultSetSize.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 57 + this.TotalSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 57 + this.StartPosition.GetHashCode();
if (this.EndPosition != null)
hash = hash * 57 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 57 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 57 + this.PreviousUri.GetHashCode();
if (this.AccountId != null)
hash = hash * 57 + this.AccountId.GetHashCode();
if (this.SharedAccess != null)
hash = hash * 57 + this.SharedAccess.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using OSGeo.GDAL;
using GdalBand = OSGeo.GDAL.Band;
using System;
namespace Landis.RasterIO.Gdal
{
public class GdalInputRaster<TPixel> : InputRaster, IInputRaster<TPixel>
where TPixel : Pixel, new()
{
private TPixel bufferPixel;
public TPixel BufferPixel {
get {
return bufferPixel;
}
}
private Dataset dataset;
private IInputBand[] rasterBands;
static GdalInputRaster()
{
GdalSystem.Initialize();
}
public GdalInputRaster(string path)
: base(path)
{
// This overload of the ctor uses the built-in GDAL method of trying all known drivers.
// Another overload would allow client code to specify the driver by its Short Name (code).
bufferPixel = new TPixel();
int nBands = bufferPixel.Count;
dataset = OSGeo.GDAL.Gdal.OpenShared(path, Access.GA_ReadOnly);
if (dataset == null)
throw new ApplicationException("Cannot open raster file for reading");
Dimensions = new Dimensions(dataset.RasterYSize, dataset.RasterXSize);
if (dataset.RasterCount != nBands)
throw new ApplicationException("Wrong # of bands in input raster");
rasterBands = new IInputBand[nBands];
for (int i = 0; i < nBands; ++i) {
int bandNum = i + 1;
// TO DO: catch exception that represents type mismatch (RasterBand dataType is too big for bufferPixel dataType)
rasterBands[i] = NewInputBand(dataset.GetRasterBand(bandNum), bufferPixel[bandNum]);
}
}
public void ReadBufferPixel()
{
foreach (IInputBand rasterBand in rasterBands) {
rasterBand.ReadValueIntoBufferPixel();
}
}
public static IInputBand NewInputBand(GdalBand gdalBand,
PixelBand pixelBand)
{
switch (gdalBand.DataType) {
case DataType.GDT_Byte:
return NewByteBand(gdalBand, pixelBand);
case DataType.GDT_Int16:
return NewShortBand(gdalBand, pixelBand);
case DataType.GDT_Int32:
return NewIntBand(gdalBand, pixelBand);
case DataType.GDT_Float32:
return NewFloatBand(gdalBand, pixelBand);
case DataType.GDT_Float64:
return NewDoubleBand(gdalBand, pixelBand);
default:
throw new ArgumentException("Raster band is not byte, short, int, float, double");
}
}
public static InputBand<byte> NewByteBand(GdalBand gdalBand,
PixelBand pixelBand)
{
RasterBandReader<byte> rasterBandReader = RasterBandReaders.NewByteReader(gdalBand);
switch (pixelBand.TypeCode) {
case TypeCode.Byte:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<byte, byte>(pixelBand, Convert.ToByte));
case TypeCode.SByte:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<sbyte, byte>(pixelBand, Convert.ToSByte));
case TypeCode.UInt16:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<ushort, byte>(pixelBand, Convert.ToUInt16));
case TypeCode.Int16:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<short, byte>(pixelBand, Convert.ToInt16));
case TypeCode.UInt32:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<uint, byte>(pixelBand, Convert.ToUInt32));
case TypeCode.Int32:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<int, byte>(pixelBand, Convert.ToInt32));
case TypeCode.Single:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<float, byte>(pixelBand, Convert.ToSingle));
case TypeCode.Double:
return new InputBand<byte>(rasterBandReader, new PixelBandSetter<double, byte>(pixelBand, Convert.ToDouble));
default:
throw new ArgumentException("pixelBand.TypeCode is not byte, sbyte, ushort, short, uint, int, float, double");
}
}
public static InputBand<short> NewShortBand(GdalBand gdalBand,
PixelBand pixelBand)
{
RasterBandReader<short> rasterBandReader = RasterBandReaders.NewShortReader(gdalBand);
switch (pixelBand.TypeCode) {
case TypeCode.UInt16:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<ushort, short>(pixelBand, Convert.ToUInt16));
case TypeCode.Int16:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<short, short>(pixelBand, Convert.ToInt16));
case TypeCode.UInt32:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<uint, short>(pixelBand, Convert.ToUInt32));
case TypeCode.Int32:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<int, short>(pixelBand, Convert.ToInt32));
case TypeCode.Single:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<float, short>(pixelBand, Convert.ToSingle));
case TypeCode.Double:
return new InputBand<short>(rasterBandReader, new PixelBandSetter<double, short>(pixelBand, Convert.ToDouble));
default:
throw new ArgumentException("pixelBand.TypeCode is not ushort, short, uint, int, float, double");
}
}
public static InputBand<int> NewIntBand(GdalBand gdalBand,
PixelBand pixelBand)
{
RasterBandReader<int> rasterBandReader = RasterBandReaders.NewIntReader(gdalBand);
switch (pixelBand.TypeCode) {
case TypeCode.UInt32:
return new InputBand<int>(rasterBandReader, new PixelBandSetter<uint, int>(pixelBand, Convert.ToUInt32));
case TypeCode.Int32:
return new InputBand<int>(rasterBandReader, new PixelBandSetter<int, int>(pixelBand, Convert.ToInt32));
case TypeCode.Single:
return new InputBand<int>(rasterBandReader, new PixelBandSetter<float, int>(pixelBand, Convert.ToSingle));
case TypeCode.Double:
return new InputBand<int>(rasterBandReader, new PixelBandSetter<double, int>(pixelBand, Convert.ToDouble));
default:
throw new ArgumentException("pixelBand.TypeCode is not uint, int, float, double");
}
}
public static InputBand<float> NewFloatBand(GdalBand gdalBand,
PixelBand pixelBand)
{
RasterBandReader<float> rasterBandReader = RasterBandReaders.NewFloatReader(gdalBand);
switch (pixelBand.TypeCode) {
case TypeCode.Single:
return new InputBand<float>(rasterBandReader, new PixelBandSetter<float, float>(pixelBand, Convert.ToSingle));
case TypeCode.Double:
return new InputBand<float>(rasterBandReader, new PixelBandSetter<double, float>(pixelBand, Convert.ToDouble));
default:
throw new ArgumentException("pixelBand.TypeCode is not float or double");
}
}
public static InputBand<double> NewDoubleBand(GdalBand gdalBand,
PixelBand pixelBand)
{
RasterBandReader<double> rasterBandReader = RasterBandReaders.NewDoubleReader(gdalBand);
switch (pixelBand.TypeCode) {
case TypeCode.Double:
return new InputBand<double>(rasterBandReader, new PixelBandSetter<double, double>(pixelBand, Convert.ToDouble));
default:
throw new ArgumentException("pixelBand.TypeCode is not double");
}
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using PlayFab.Json.Linq;
using PlayFab.Json.Utilities;
namespace PlayFab.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _token;
private object _value;
private Type _valueType;
private char _quoteChar;
private State _currentState;
private JTokenType _currentTypeContext;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
private int _top;
private readonly List<JTokenType> _stack;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Gets the type of the current Json token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _token; }
}
/// <summary>
/// Gets the text value of the current Json token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current Json token.
/// </summary>
public virtual Type ValueType
{
get { return _valueType; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _top - 1;
if (IsStartToken(TokenType))
return depth - 1;
else
return depth;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_stack = new List<JTokenType>();
CloseInput = true;
Push(JTokenType.None);
}
private void Push(JTokenType value)
{
_stack.Add(value);
_top++;
_currentTypeContext = value;
}
private JTokenType Pop()
{
JTokenType value = Peek();
_stack.RemoveAt(_stack.Count - 1);
_top--;
_currentTypeContext = _stack[_top - 1];
return value;
}
private JTokenType Peek()
{
return _currentTypeContext;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected virtual void SetToken(JsonToken newToken, object value)
{
_token = newToken;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JTokenType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JTokenType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JTokenType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
_currentState = State.PostValue;
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
_currentState = State.PostValue;
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
_currentState = State.PostValue;
break;
case JsonToken.PropertyName:
_currentState = State.Property;
Push(JTokenType.Property);
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
_currentState = State.PostValue;
break;
}
JTokenType current = Peek();
if (current == JTokenType.Property && _currentState == State.PostValue)
Pop();
if (value != null)
{
_value = value;
_valueType = value.GetType();
}
else
{
_value = null;
_valueType = null;
}
}
private void ValidateEnd(JsonToken endToken)
{
JTokenType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw new JsonReaderException("JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JTokenType currentObject = Peek();
switch (currentObject)
{
case JTokenType.Object:
_currentState = State.Object;
break;
case JTokenType.Array:
_currentState = State.Array;
break;
case JTokenType.Constructor:
_currentState = State.Constructor;
break;
case JTokenType.None:
_currentState = State.Finished;
break;
default:
throw new JsonReaderException("While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
case JsonToken.PropertyName:
return true;
case JsonToken.None:
case JsonToken.Comment:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
case JsonToken.Date:
case JsonToken.Raw:
case JsonToken.Bytes:
return false;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("token", token, "Unexpected JsonToken value.");
}
}
private JTokenType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JTokenType.Object;
case JsonToken.EndArray:
return JTokenType.Array;
case JsonToken.EndConstructor:
return JTokenType.Constructor;
default:
throw new JsonReaderException("Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_token = JsonToken.None;
_value = null;
_valueType = null;
}
}
}
#endif
| |
// 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 gax = Google.Api.Gax;
using gcfav = Google.Cloud.Firestore.Admin.V1;
using sys = System;
namespace Google.Cloud.Firestore.Admin.V1
{
/// <summary>Resource name for the <c>Field</c> resource.</summary>
public sealed partial class FieldName : gax::IResourceName, sys::IEquatable<FieldName>
{
/// <summary>The possible contents of <see cref="FieldName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </summary>
ProjectDatabaseCollectionField = 1,
}
private static gax::PathTemplate s_projectDatabaseCollectionField = new gax::PathTemplate("projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}");
/// <summary>Creates a <see cref="FieldName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="FieldName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static FieldName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new FieldName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="FieldName"/> with the pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FieldName"/> constructed from the provided ids.</returns>
public static FieldName FromProjectDatabaseCollectionField(string projectId, string databaseId, string collectionId, string fieldId) =>
new FieldName(ResourceNameType.ProjectDatabaseCollectionField, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), collectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId)), fieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FieldName"/> with pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FieldName"/> with pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </returns>
public static string Format(string projectId, string databaseId, string collectionId, string fieldId) =>
FormatProjectDatabaseCollectionField(projectId, databaseId, collectionId, fieldId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FieldName"/> with pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FieldName"/> with pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>.
/// </returns>
public static string FormatProjectDatabaseCollectionField(string projectId, string databaseId, string collectionId, string fieldId) =>
s_projectDatabaseCollectionField.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId)));
/// <summary>Parses the given resource name string into a new <see cref="FieldName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="fieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="FieldName"/> if successful.</returns>
public static FieldName Parse(string fieldName) => Parse(fieldName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="FieldName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="fieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="FieldName"/> if successful.</returns>
public static FieldName Parse(string fieldName, bool allowUnparsed) =>
TryParse(fieldName, allowUnparsed, out FieldName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FieldName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="fieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FieldName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string fieldName, out FieldName result) => TryParse(fieldName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FieldName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="fieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FieldName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string fieldName, bool allowUnparsed, out FieldName result)
{
gax::GaxPreconditions.CheckNotNull(fieldName, nameof(fieldName));
gax::TemplatedResourceName resourceName;
if (s_projectDatabaseCollectionField.TryParseName(fieldName, out resourceName))
{
result = FromProjectDatabaseCollectionField(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(fieldName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private FieldName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string collectionId = null, string databaseId = null, string fieldId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CollectionId = collectionId;
DatabaseId = databaseId;
FieldId = fieldId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="FieldName"/> class from the component parts of pattern
/// <c>projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param>
public FieldName(string projectId, string databaseId, string collectionId, string fieldId) : this(ResourceNameType.ProjectDatabaseCollectionField, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), collectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId)), fieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Collection</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CollectionId { get; }
/// <summary>
/// The <c>Database</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DatabaseId { get; }
/// <summary>
/// The <c>Field</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FieldId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectDatabaseCollectionField: return s_projectDatabaseCollectionField.Expand(ProjectId, DatabaseId, CollectionId, FieldId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as FieldName);
/// <inheritdoc/>
public bool Equals(FieldName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(FieldName a, FieldName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(FieldName a, FieldName b) => !(a == b);
}
public partial class Field
{
/// <summary>
/// <see cref="gcfav::FieldName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcfav::FieldName FieldName
{
get => string.IsNullOrEmpty(Name) ? null : gcfav::FieldName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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.
// Strings are the only ref class where there is built-in support for
// constant objects.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public static class ConstantArgsString
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Ints feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static string Ten = "Ten";
static string Five = "Five";
static string Id(string x)
{
return x;
}
static char F00(string x)
{
return x[0];
}
static bool Bench00p()
{
string t = "Ten";
char f = F00(t);
return (f == 'T');
}
static bool Bench00n()
{
string t = Ten;
char f = F00(t);
return (f == 'T');
}
static int F01(string x)
{
return x.Length;
}
static bool Bench01p()
{
string t = "Ten";
int f = F01(t);
return (f == 3);
}
static bool Bench01n()
{
string t = Ten;
int f = F01(t);
return (f == 3);
}
static bool Bench01p1()
{
return "Ten".Length == 3;
}
static bool Bench01n1()
{
return Ten.Length == 3;
}
static bool Bench02p()
{
return "Ten".Equals("Ten", StringComparison.Ordinal);
}
static bool Bench02n()
{
return "Ten".Equals(Ten, StringComparison.Ordinal);
}
static bool Bench02n1()
{
return Ten.Equals("Ten", StringComparison.Ordinal);
}
static bool Bench02n2()
{
return Ten.Equals(Ten, StringComparison.Ordinal);
}
static bool Bench03p()
{
return "Ten" == "Ten";
}
static bool Bench03n()
{
return "Ten" == Ten;
}
static bool Bench03n1()
{
return Ten == "Ten";
}
static bool Bench03n2()
{
return Ten == Ten;
}
static bool Bench04p()
{
return "Ten" != "Five";
}
static bool Bench04n()
{
return "Ten" != Five;
}
static bool Bench04n1()
{
return Ten != "Five";
}
static bool Bench04n2()
{
return Ten != Five;
}
static bool Bench05p()
{
string t = "Ten";
return (t == t);
}
static bool Bench05n()
{
string t = Ten;
return (t == t);
}
static bool Bench06p()
{
return "Ten" != null;
}
static bool Bench06n()
{
return Ten != null;
}
static bool Bench07p()
{
return !"Ten".Equals(null);
}
static bool Bench07n()
{
return !Ten.Equals(null);
}
static bool Bench08p()
{
return !"Ten".Equals("Five", StringComparison.Ordinal);
}
static bool Bench08n()
{
return !"Ten".Equals(Five, StringComparison.Ordinal);
}
static bool Bench08n1()
{
return !Ten.Equals("Five", StringComparison.Ordinal);
}
static bool Bench08n2()
{
return !Ten.Equals(Five, StringComparison.Ordinal);
}
static bool Bench09p()
{
return string.Equals("Ten", "Ten");
}
static bool Bench09n()
{
return string.Equals("Ten", Ten);
}
static bool Bench09n1()
{
return string.Equals(Ten, "Ten");
}
static bool Bench09n2()
{
return string.Equals(Ten, Ten);
}
static bool Bench10p()
{
return !string.Equals("Five", "Ten");
}
static bool Bench10n()
{
return !string.Equals(Five, "Ten");
}
static bool Bench10n1()
{
return !string.Equals("Five", Ten);
}
static bool Bench10n2()
{
return !string.Equals(Five, Ten);
}
static bool Bench11p()
{
return !string.Equals("Five", null);
}
static bool Bench11n()
{
return !string.Equals(Five, null);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench01p", "Bench01n",
"Bench01p1", "Bench01n1",
"Bench02p", "Bench02n",
"Bench02n1", "Bench02n2",
"Bench03p", "Bench03n",
"Bench03n1", "Bench03n2",
"Bench04p", "Bench04n",
"Bench04n1", "Bench04n2",
"Bench05p", "Bench05n",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench08p", "Bench08n",
"Bench08n1", "Bench08n2",
"Bench09p", "Bench09n",
"Bench09n1", "Bench09n2",
"Bench10p", "Bench10n",
"Bench10n1", "Bench10n2",
"Bench11p", "Bench11n"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsString).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;
using System.Xml.XPath;
using HtmlAgilityPack;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using Umbraco.Web.Templates;
using umbraco;
using System.Collections.Generic;
using umbraco.cms.businesslogic.web;
using umbraco.presentation.templateControls;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
/// <summary>
/// Methods used to render umbraco components as HTML in templates
/// </summary>
/// <remarks>
/// Used by UmbracoHelper
/// </remarks>
internal class UmbracoComponentRenderer : IUmbracoComponentRenderer
{
private readonly UmbracoContext _umbracoContext;
public UmbracoComponentRenderer(UmbracoContext umbracoContext)
{
_umbracoContext = umbracoContext;
}
/// <summary>
/// Renders the template for the specified pageId and an optional altTemplateId
/// </summary>
/// <param name="pageId"></param>
/// <param name="altTemplateId">If not specified, will use the template assigned to the node</param>
/// <returns></returns>
public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
{
var templateRenderer = new TemplateRenderer(_umbracoContext, pageId, altTemplateId);
using (var sw = new StringWriter())
{
try
{
templateRenderer.Render(sw);
}
catch (Exception ex)
{
sw.Write("<!-- Error rendering template with id {0}: '{1}' -->", pageId, ex);
}
return new HtmlString(sw.ToString());
}
}
/// <summary>
/// Renders the macro with the specified alias.
/// </summary>
/// <param name="alias">The alias.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias)
{
return RenderMacro(alias, new { });
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, object parameters)
{
return RenderMacro(alias, parameters.ToDictionary<object>());
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters)
{
if (_umbracoContext.PublishedContentRequest == null)
{
throw new InvalidOperationException("Cannot render a macro when there is no current PublishedContentRequest.");
}
return RenderMacro(alias, parameters, _umbracoContext.PublishedContentRequest.UmbracoPage);
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="umbracoPage">The legacy umbraco page object that is required for some macros</param>
/// <returns></returns>
internal IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters, page umbracoPage)
{
if (alias == null) throw new ArgumentNullException("alias");
if (umbracoPage == null) throw new ArgumentNullException("umbracoPage");
var m = macro.GetMacro(alias);
if (m == null)
{
throw new KeyNotFoundException("Could not find macro with alias " + alias);
}
return RenderMacro(m, parameters, umbracoPage);
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="m">The macro.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="umbracoPage">The legacy umbraco page object that is required for some macros</param>
/// <returns></returns>
internal IHtmlString RenderMacro(macro m, IDictionary<string, object> parameters, page umbracoPage)
{
if (umbracoPage == null) throw new ArgumentNullException("umbracoPage");
if (m == null) throw new ArgumentNullException("m");
if (_umbracoContext.PageId == null)
{
throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
}
var macroProps = new Hashtable();
foreach (var i in parameters)
{
//TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs
// looks for a lower case match. WTF. the whole macro concept needs to be rewritten.
//NOTE: the value could have html encoded values, so we need to deal with that
macroProps.Add(i.Key.ToLowerInvariant(), (i.Value is string) ? HttpUtility.HtmlDecode(i.Value.ToString()) : i.Value);
}
var macroControl = m.renderMacro(macroProps,
umbracoPage.Elements,
_umbracoContext.PageId.Value);
string html;
if (macroControl is LiteralControl)
{
// no need to execute, we already have text
html = (macroControl as LiteralControl).Text;
}
else
{
var containerPage = new FormlessPage();
containerPage.Controls.Add(macroControl);
using (var output = new StringWriter())
{
// .Execute() does a PushTraceContext/PopTraceContext and writes trace output straight into 'output'
// and I do not see how we could wire the trace context to the current context... so it creates dirty
// trace output right in the middle of the page.
//
// The only thing we can do is fully disable trace output while .Execute() runs and restore afterwards
// which means trace output is lost if the macro is a control (.ascx or user control) that is invoked
// from within Razor -- which makes sense anyway because the control can _not_ run correctly from
// within Razor since it will never be inserted into the page pipeline (which may even not exist at all
// if we're running MVC).
//
// I'm sure there's more things that will get lost with this context changing but I guess we'll figure
// those out as we go along. One thing we lose is the content type response output.
// http://issues.umbraco.org/issue/U4-1599 if it is setup during the macro execution. So
// here we'll save the content type response and reset it after execute is called.
var contentType = _umbracoContext.HttpContext.Response.ContentType;
var traceIsEnabled = containerPage.Trace.IsEnabled;
containerPage.Trace.IsEnabled = false;
_umbracoContext.HttpContext.Server.Execute(containerPage, output, true);
containerPage.Trace.IsEnabled = traceIsEnabled;
//reset the content type
_umbracoContext.HttpContext.Response.ContentType = contentType;
//Now, we need to ensure that local links are parsed
html = TemplateUtilities.ParseInternalLinks(output.ToString());
}
}
return new HtmlString(html);
}
/// <summary>
/// Renders an field to the template
/// </summary>
/// <param name="currentPage"></param>
/// <param name="fieldAlias"></param>
/// <param name="altFieldAlias"></param>
/// <param name="altText"></param>
/// <param name="insertBefore"></param>
/// <param name="insertAfter"></param>
/// <param name="recursive"></param>
/// <param name="convertLineBreaks"></param>
/// <param name="removeParagraphTags"></param>
/// <param name="casing"></param>
/// <param name="encoding"></param>
/// <param name="formatAsDate"></param>
/// <param name="formatAsDateWithTime"></param>
/// <param name="formatAsDateWithTimeSeparator"></param>
//// <param name="formatString"></param>
/// <returns></returns>
public IHtmlString Field(IPublishedContent currentPage, string fieldAlias,
string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged,
bool formatAsDate = false,
bool formatAsDateWithTime = false,
string formatAsDateWithTimeSeparator = "")
//TODO: commented out until as it is not implemented by umbraco:item yet
//,string formatString = "")
{
Mandate.ParameterNotNull(currentPage, "currentPage");
Mandate.ParameterNotNullOrEmpty(fieldAlias, "fieldAlias");
//TODO: This is real nasty and we should re-write the 'item' and 'ItemRenderer' class but si fine for now
var attributes = new Dictionary<string, string>
{
{"field", fieldAlias},
{"recursive", recursive.ToString().ToLowerInvariant()},
{"useifempty", altFieldAlias},
{"textifempty", altText},
{"stripparagraph", removeParagraphTags.ToString().ToLowerInvariant()},
{
"case", casing == RenderFieldCaseType.Lower ? "lower"
: casing == RenderFieldCaseType.Upper ? "upper"
: casing == RenderFieldCaseType.Title ? "title"
: string.Empty
},
{"inserttextbefore", insertBefore},
{"inserttextafter", insertAfter},
{"convertlinebreaks", convertLineBreaks.ToString().ToLowerInvariant()},
{"formatasdate", formatAsDate.ToString().ToLowerInvariant()},
{"formatasdatewithtime", formatAsDateWithTime.ToString().ToLowerInvariant()},
{"formatasdatewithtimeseparator", formatAsDateWithTimeSeparator}
};
switch (encoding)
{
case RenderFieldEncodingType.Url:
attributes.Add("urlencode", "true");
break;
case RenderFieldEncodingType.Html:
attributes.Add("htmlencode", "true");
break;
case RenderFieldEncodingType.Unchanged:
default:
break;
}
//need to convert our dictionary over to this weird dictionary type
var attributesForItem = new AttributeCollectionAdapter(
new AttributeCollection(
new StateBag()));
foreach (var i in attributes)
{
attributesForItem.Add(i.Key, i.Value);
}
var item = new Item(currentPage)
{
Field = fieldAlias,
TextIfEmpty = altText,
LegacyAttributes = attributesForItem
};
//here we are going to check if we are in the context of an Umbraco routed page, if we are we
//will leave the NodeId empty since the underlying ItemRenderer will work ever so slightly faster
//since it already knows about the current page. Otherwise, we'll assign the id based on our
//currently assigned node. The PublishedContentRequest will be null if:
// * we are rendering a partial view or child action
// * we are rendering a view from a custom route
if ((_umbracoContext.PublishedContentRequest == null
|| _umbracoContext.PublishedContentRequest.PublishedContent.Id != currentPage.Id)
&& currentPage.Id > 0) // in case we're rendering a detached content (id == 0)
{
item.NodeId = currentPage.Id.ToString(CultureInfo.InvariantCulture);
}
var containerPage = new FormlessPage();
containerPage.Controls.Add(item);
using (var output = new StringWriter())
using (var htmlWriter = new HtmlTextWriter(output))
{
ItemRenderer.Instance.Init(item);
ItemRenderer.Instance.Load(item);
ItemRenderer.Instance.Render(item, htmlWriter);
//because we are rendering the output through the legacy Item (webforms) stuff, the {localLinks} will already be replaced.
return new HtmlString(output.ToString());
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Input.Stylus.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Input
{
static public partial class Stylus
{
#region Methods and constructors
public static void AddGotStylusCaptureHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddLostStylusCaptureHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddPreviewStylusButtonDownHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void AddPreviewStylusButtonUpHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void AddPreviewStylusDownHandler(System.Windows.DependencyObject element, StylusDownEventHandler handler)
{
}
public static void AddPreviewStylusInAirMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddPreviewStylusInRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddPreviewStylusMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddPreviewStylusOutOfRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddPreviewStylusSystemGestureHandler(System.Windows.DependencyObject element, StylusSystemGestureEventHandler handler)
{
}
public static void AddPreviewStylusUpHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusButtonDownHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void AddStylusButtonUpHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void AddStylusDownHandler(System.Windows.DependencyObject element, StylusDownEventHandler handler)
{
}
public static void AddStylusEnterHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusInAirMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusInRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusLeaveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusOutOfRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void AddStylusSystemGestureHandler(System.Windows.DependencyObject element, StylusSystemGestureEventHandler handler)
{
}
public static void AddStylusUpHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static bool Capture(System.Windows.IInputElement element)
{
return default(bool);
}
public static bool Capture(System.Windows.IInputElement element, CaptureMode captureMode)
{
return default(bool);
}
public static bool GetIsFlicksEnabled(System.Windows.DependencyObject element)
{
return default(bool);
}
public static bool GetIsPressAndHoldEnabled(System.Windows.DependencyObject element)
{
return default(bool);
}
public static bool GetIsTapFeedbackEnabled(System.Windows.DependencyObject element)
{
return default(bool);
}
public static bool GetIsTouchFeedbackEnabled(System.Windows.DependencyObject element)
{
return default(bool);
}
public static void RemoveGotStylusCaptureHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveLostStylusCaptureHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemovePreviewStylusButtonDownHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void RemovePreviewStylusButtonUpHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void RemovePreviewStylusDownHandler(System.Windows.DependencyObject element, StylusDownEventHandler handler)
{
}
public static void RemovePreviewStylusInAirMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemovePreviewStylusInRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemovePreviewStylusMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemovePreviewStylusOutOfRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemovePreviewStylusSystemGestureHandler(System.Windows.DependencyObject element, StylusSystemGestureEventHandler handler)
{
}
public static void RemovePreviewStylusUpHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusButtonDownHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void RemoveStylusButtonUpHandler(System.Windows.DependencyObject element, StylusButtonEventHandler handler)
{
}
public static void RemoveStylusDownHandler(System.Windows.DependencyObject element, StylusDownEventHandler handler)
{
}
public static void RemoveStylusEnterHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusInAirMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusInRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusLeaveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusMoveHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusOutOfRangeHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void RemoveStylusSystemGestureHandler(System.Windows.DependencyObject element, StylusSystemGestureEventHandler handler)
{
}
public static void RemoveStylusUpHandler(System.Windows.DependencyObject element, StylusEventHandler handler)
{
}
public static void SetIsFlicksEnabled(System.Windows.DependencyObject element, bool enabled)
{
}
public static void SetIsPressAndHoldEnabled(System.Windows.DependencyObject element, bool enabled)
{
}
public static void SetIsTapFeedbackEnabled(System.Windows.DependencyObject element, bool enabled)
{
}
public static void SetIsTouchFeedbackEnabled(System.Windows.DependencyObject element, bool enabled)
{
}
public static void Synchronize()
{
}
#endregion
#region Properties and indexers
public static System.Windows.IInputElement Captured
{
get
{
return default(System.Windows.IInputElement);
}
}
public static StylusDevice CurrentStylusDevice
{
get
{
return default(StylusDevice);
}
}
public static System.Windows.IInputElement DirectlyOver
{
get
{
return default(System.Windows.IInputElement);
}
}
#endregion
#region Fields
public readonly static System.Windows.RoutedEvent GotStylusCaptureEvent;
public readonly static System.Windows.DependencyProperty IsFlicksEnabledProperty;
public readonly static System.Windows.DependencyProperty IsPressAndHoldEnabledProperty;
public readonly static System.Windows.DependencyProperty IsTapFeedbackEnabledProperty;
public readonly static System.Windows.DependencyProperty IsTouchFeedbackEnabledProperty;
public readonly static System.Windows.RoutedEvent LostStylusCaptureEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusButtonDownEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusButtonUpEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusDownEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusInAirMoveEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusInRangeEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusMoveEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusOutOfRangeEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusSystemGestureEvent;
public readonly static System.Windows.RoutedEvent PreviewStylusUpEvent;
public readonly static System.Windows.RoutedEvent StylusButtonDownEvent;
public readonly static System.Windows.RoutedEvent StylusButtonUpEvent;
public readonly static System.Windows.RoutedEvent StylusDownEvent;
public readonly static System.Windows.RoutedEvent StylusEnterEvent;
public readonly static System.Windows.RoutedEvent StylusInAirMoveEvent;
public readonly static System.Windows.RoutedEvent StylusInRangeEvent;
public readonly static System.Windows.RoutedEvent StylusLeaveEvent;
public readonly static System.Windows.RoutedEvent StylusMoveEvent;
public readonly static System.Windows.RoutedEvent StylusOutOfRangeEvent;
public readonly static System.Windows.RoutedEvent StylusSystemGestureEvent;
public readonly static System.Windows.RoutedEvent StylusUpEvent;
#endregion
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Net.NetworkInformation;
using NuGet.Resolver;
using NuGet.VisualStudio;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Interop;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
#endif
namespace NuGet.PowerShell.Commands
{
/// <summary>
/// This command installs the specified package into the specified project.
/// </summary>
[Cmdlet(VerbsLifecycle.Install, "Package")]
public class InstallPackageCommand : ProcessPackageBaseCommand
{
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly IPackageRepositoryFactory _repositoryFactory;
private readonly IProductUpdateService _productUpdateService;
private bool _hasConnectedToHttpSource;
private bool _isNetworkAvailable;
public InstallPackageCommand()
: this(ServiceLocator.GetInstance<ISolutionManager>(),
ServiceLocator.GetInstance<IVsPackageManagerFactory>(),
ServiceLocator.GetInstance<IPackageRepositoryFactory>(),
ServiceLocator.GetInstance<IVsPackageSourceProvider>(),
ServiceLocator.GetInstance<IHttpClientEvents>(),
ServiceLocator.GetInstance<IProductUpdateService>(),
ServiceLocator.GetInstance<IVsCommonOperations>(),
ServiceLocator.GetInstance<IDeleteOnRestartManager>(),
isNetworkAvailable())
{
}
internal InstallPackageCommand(
ISolutionManager solutionManager,
IVsPackageManagerFactory packageManagerFactory,
IPackageRepositoryFactory repositoryFactory,
IVsPackageSourceProvider packageSourceProvider,
IHttpClientEvents httpClientEvents,
IProductUpdateService productUpdateService,
IVsCommonOperations vsCommonOperations,
IDeleteOnRestartManager deleteOnRestartManager,
bool networkAvailable)
: base(solutionManager, packageManagerFactory, httpClientEvents, vsCommonOperations, deleteOnRestartManager)
{
_productUpdateService = productUpdateService;
_repositoryFactory = repositoryFactory;
_packageSourceProvider = packageSourceProvider;
if (networkAvailable)
{
_isNetworkAvailable = isNetworkAvailable();
}
else
{
_isNetworkAvailable = false;
}
}
private static bool isNetworkAvailable()
{
return NetworkInterface.GetIsNetworkAvailable();
}
[Parameter(Position = 2)]
[ValidateNotNull]
public SemanticVersion Version { get; set; }
[Parameter(Position = 3)]
[ValidateNotNullOrEmpty]
public string Source { get; set; }
[Parameter]
public SwitchParameter IgnoreDependencies { get; set; }
[Parameter, Alias("Prerelease")]
public SwitchParameter IncludePrerelease { get; set; }
[Parameter]
public FileConflictAction FileConflictAction { get; set; }
[Parameter]
public SwitchParameter WhatIf { get; set; }
[Parameter]
public DependencyVersion? DependencyVersion { get; set; }
private string _fallbackToLocalCacheMessge = Resources.Cmdlet_FallbackToCache;
private string _localCacheFailureMessage = Resources.Cmdlet_LocalCacheFailure;
private string _cacheStatusMessage = String.Empty;
// Type for _currentSource can be either string (actual path to the Source), or PackageSource.
private object _currentSource = String.Empty;
protected override IVsPackageManager CreatePackageManager()
{
if (!SolutionManager.IsSolutionOpen)
{
return null;
}
if (_packageSourceProvider != null && _packageSourceProvider.ActivePackageSource != null && String.IsNullOrEmpty(Source))
{
FallbackToCacheIfNeccessary();
}
if (!String.IsNullOrEmpty(Source))
{
var repository = CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, Source);
return repository == null ? null : PackageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: true);
}
return base.CreatePackageManager();
}
private void FallbackToCacheIfNeccessary()
{
/**** Fallback to Cache logic***/
//1. Check if there is any http source (in active sources or Source switch)
//2. Check if any one of the UNC or local sources is available (in active sources)
//3. If none of the above is true, fallback to cache
//Check if any of the active package source is available. This function will return true if there is any http source in active sources
//For http sources, we will continue and fallback to cache at a later point if the resource is unavailable
if (String.IsNullOrEmpty(Source))
{
bool isAnySourceAvailable = false;
_currentSource = _packageSourceProvider.ActivePackageSource;
isAnySourceAvailable = UriHelper.IsAnySourceAvailable(_packageSourceProvider, _isNetworkAvailable);
//if no local or UNC source is available or no source is http, fallback to local cache
if (!isAnySourceAvailable)
{
Source = NuGet.MachineCache.Default.Source;
CacheStatusMessage(_currentSource, Source);
}
}
//At this point, Source might be value from -Source switch or NuGet Local Cache
/**** End of Fallback to Cache logic ***/
}
protected override void ProcessRecordCore()
{
if (!SolutionManager.IsSolutionOpen)
{
ErrorHandler.ThrowSolutionNotOpenTerminatingError();
}
try
{
SubscribeToProgressEvents();
if (PackageManager == null)
{
return;
}
if (DependencyVersion.HasValue)
{
PackageManager.DependencyVersion = DependencyVersion.Value;
}
if (!String.IsNullOrEmpty(_cacheStatusMessage))
{
this.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, _cacheStatusMessage, _packageSourceProvider.ActivePackageSource, Source));
}
InstallPackage(PackageManager);
_hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source, _packageSourceProvider);
}
//If the http source is not available, we fallback to NuGet Local Cache
//Skip if Source flag has been set (Fix for bug http://nuget.codeplex.com/workitem/3776)
catch (Exception ex)
{
if (((ex is System.Net.WebException) ||
(ex.InnerException is System.Net.WebException) ||
(ex.InnerException is System.InvalidOperationException))
&& (String.IsNullOrEmpty(Source)))
{
string cache = NuGet.MachineCache.Default.Source;
if (!String.IsNullOrEmpty(cache))
{
this.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, _fallbackToLocalCacheMessge, _currentSource, cache));
var repository = CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, cache);
IVsPackageManager packageManager = (repository == null ? null : PackageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: true));
InstallPackage(packageManager);
}
}
else
{
throw;
}
}
finally
{
UnsubscribeFromProgressEvents();
}
}
public override FileConflictResolution ResolveFileConflict(string message)
{
if (FileConflictAction == FileConflictAction.Overwrite)
{
return FileConflictResolution.Overwrite;
}
if (FileConflictAction == FileConflictAction.Ignore)
{
return FileConflictResolution.Ignore;
}
return base.ResolveFileConflict(message);
}
protected override void EndProcessing()
{
base.EndProcessing();
CheckForNuGetUpdate();
}
private void CheckForNuGetUpdate()
{
if (_productUpdateService != null && _hasConnectedToHttpSource)
{
_productUpdateService.CheckForAvailableUpdateAsync();
}
}
private void CacheStatusMessage(object currentSource, string cacheSource)
{
if (!String.IsNullOrEmpty(cacheSource))
{
_cacheStatusMessage = String.Format(CultureInfo.CurrentCulture, _fallbackToLocalCacheMessge, currentSource, Source);
}
else
{
_cacheStatusMessage = String.Format(CultureInfo.CurrentCulture, _localCacheFailureMessage, currentSource);
}
}
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private void InstallPackage(IVsPackageManager packageManager)
{
if (packageManager == null)
{
return;
}
// Locate the package to install
IPackage package = PackageRepositoryHelper.ResolvePackage(
packageManager.SourceRepository,
packageManager.LocalRepository,
Id,
Version,
IncludePrerelease.IsPresent);
#if VS14
var nugetAwareProject = ProjectManager.Project as INuGetPackageManager;
if (nugetAwareProject != null)
{
var args = new Dictionary<string, object>();
args["DependencyVersion"] = DependencyVersion;
args["IgnoreDependencies"] = IgnoreDependencies;
args["WhatIf"] = WhatIf;
using (var cts = new CancellationTokenSource())
{
var packageSupportedFrameworks = package.GetSupportedFrameworks();
var projectFrameworks = nugetAwareProject.GetSupportedFrameworksAsync(cts.Token).Result;
args["Frameworks"] = projectFrameworks.Where(
projectFramework =>
NuGet.VersionUtility.IsCompatible(
projectFramework,
packageSupportedFrameworks)).ToArray();
var task = nugetAwareProject.InstallPackageAsync(
new NuGetPackageMoniker
{
Id = package.Id,
Version = package.Version.ToString()
},
args,
logger: null,
progress: null,
cancellationToken: cts.Token);
task.Wait();
return;
}
}
#endif
// Resolve actions
var resolver = new ActionResolver()
{
Logger = this,
IgnoreDependencies = IgnoreDependencies,
DependencyVersion = packageManager.DependencyVersion,
AllowPrereleaseVersions = IncludePrerelease.IsPresent
};
resolver.AddOperation(PackageAction.Install, package, ProjectManager);
var actions = resolver.ResolveActions();
if (WhatIf)
{
foreach (var action in actions)
{
Log(MessageLevel.Info, Resources.Log_OperationWhatIf, action);
}
return;
}
var executor = new ActionExecutor()
{
Logger = this
};
executor.Execute(actions);
}
}
}
| |
using System;
namespace MessagingToolkit.QRCode.Codec.Ecc
{
public class ReedSolomon
{
virtual public bool CorrectionSucceeded
{
get
{
return correctionSucceeded;
}
}
virtual public int NumCorrectedErrors
{
get
{
return NErrors;
}
}
//G(x)=a^8+a^4+a^3+a^2+1
internal int[] y;
internal int[] gexp = new int[512];
internal int[] glog = new int[256];
internal int NPAR;
//final int NPAR = 15;
internal int MAXDEG;
internal int[] synBytes;
/* The Error Locator Polynomial, also known as Lambda or Sigma. Lambda[0] == 1 */
internal int[] Lambda;
/* The Error Evaluator Polynomial */
internal int[] Omega;
/* local ANSI declarations */
/* error locations found using Chien's search*/
internal int[] ErrorLocs = new int[256];
internal int NErrors;
/* erasure flags */
internal int[] ErasureLocs = new int[256];
internal int NErasures = 0;
internal bool correctionSucceeded = true;
public ReedSolomon(int[] source, int NPAR)
{
initializeGaloisTables();
y = source;
this.NPAR = NPAR;
MAXDEG = NPAR * 2;
synBytes = new int[MAXDEG];
Lambda = new int[MAXDEG];
Omega = new int[MAXDEG];
}
internal virtual void initializeGaloisTables()
{
int i, z;
int pinit, p1, p2, p3, p4, p5, p6, p7, p8;
pinit = p2 = p3 = p4 = p5 = p6 = p7 = p8 = 0;
p1 = 1;
gexp[0] = 1;
gexp[255] = gexp[0];
glog[0] = 0; /* shouldn't log[0] be an error? */
for (i = 1; i < 256; i++)
{
pinit = p8;
p8 = p7;
p7 = p6;
p6 = p5;
p5 = p4 ^ pinit;
p4 = p3 ^ pinit;
p3 = p2 ^ pinit;
p2 = p1;
p1 = pinit;
gexp[i] = p1 + p2 * 2 + p3 * 4 + p4 * 8 + p5 * 16 + p6 * 32 + p7 * 64 + p8 * 128;
gexp[i + 255] = gexp[i];
}
for (i = 1; i < 256; i++)
{
for (z = 0; z < 256; z++)
{
if (gexp[z] == i)
{
glog[i] = z;
break;
}
}
}
}
/* multiplication using logarithms */
internal virtual int gmult(int a, int b)
{
int i, j;
if (a == 0 || b == 0)
return (0);
i = glog[a];
j = glog[b];
return (gexp[i + j]);
}
internal virtual int ginv(int elt)
{
return (gexp[255 - glog[elt]]);
}
internal virtual void decode_data(int[] data)
{
int i, j, sum;
for (j = 0; j < MAXDEG; j++)
{
sum = 0;
for (i = 0; i < data.Length; i++)
{
sum = data[i] ^ gmult(gexp[j + 1], sum);
}
synBytes[j] = sum;
}
}
public virtual void correct()
{
//
decode_data(y);
correctionSucceeded = true;
bool hasError = false;
for (int i = 0; i < synBytes.Length; i++)
{
//Console.out.println("SyndromeS"+String.valueOf(i) + " = " + synBytes[i]);
if (synBytes[i] != 0)
hasError = true;
}
if (hasError)
correctionSucceeded = correct_errors_erasures(y, y.Length, 0, new int[1]);
}
internal virtual void Modified_Berlekamp_Massey()
{
int n, L, L2, k, d, i;
int[] psi = new int[MAXDEG];
int[] psi2 = new int[MAXDEG];
int[] D = new int[MAXDEG];
int[] gamma = new int[MAXDEG];
/* initialize Gamma, the erasure locator polynomial */
init_gamma(gamma);
/* initialize to z */
copy_poly(D, gamma);
mul_z_poly(D);
copy_poly(psi, gamma);
k = - 1; L = NErasures;
for (n = NErasures; n < 8; n++)
{
d = compute_discrepancy(psi, synBytes, L, n);
if (d != 0)
{
/* psi2 = psi - d*D */
for (i = 0; i < MAXDEG; i++)
psi2[i] = psi[i] ^ gmult(d, D[i]);
if (L < (n - k))
{
L2 = n - k;
k = n - L;
/* D = scale_poly(ginv(d), psi); */
for (i = 0; i < MAXDEG; i++)
D[i] = gmult(psi[i], ginv(d));
L = L2;
}
/* psi = psi2 */
for (i = 0; i < MAXDEG; i++)
psi[i] = psi2[i];
}
mul_z_poly(D);
}
for (i = 0; i < MAXDEG; i++)
Lambda[i] = psi[i];
compute_modified_omega();
}
/* given Psi (called Lambda in Modified_Berlekamp_Massey) and synBytes,
compute the combined erasure/error evaluator polynomial as
Psi*S mod z^4
*/
internal virtual void compute_modified_omega()
{
int i;
int[] product = new int[MAXDEG * 2];
mult_polys(product, Lambda, synBytes);
zero_poly(Omega);
for (i = 0; i < NPAR; i++)
Omega[i] = product[i];
}
/* polynomial multiplication */
internal virtual void mult_polys(int[] dst, int[] p1, int[] p2)
{
int i, j;
int[] tmp1 = new int[MAXDEG * 2];
for (i = 0; i < (MAXDEG * 2); i++)
dst[i] = 0;
for (i = 0; i < MAXDEG; i++)
{
for (j = MAXDEG; j < (MAXDEG * 2); j++)
tmp1[j] = 0;
/* scale tmp1 by p1[i] */
for (j = 0; j < MAXDEG; j++)
tmp1[j] = gmult(p2[j], p1[i]);
/* and mult (shift) tmp1 right by i */
for (j = (MAXDEG * 2) - 1; j >= i; j--)
tmp1[j] = tmp1[j - i];
for (j = 0; j < i; j++)
tmp1[j] = 0;
/* add into partial product */
for (j = 0; j < (MAXDEG * 2); j++)
dst[j] ^= tmp1[j];
}
}
/* gamma = product (1-z*a^Ij) for erasure locs Ij */
internal virtual void init_gamma(int[] gamma)
{
int e;
int[] tmp = new int[MAXDEG];
zero_poly(gamma);
zero_poly(tmp);
gamma[0] = 1;
for (e = 0; e < NErasures; e++)
{
copy_poly(tmp, gamma);
scale_poly(gexp[ErasureLocs[e]], tmp);
mul_z_poly(tmp);
add_polys(gamma, tmp);
}
}
internal virtual void compute_next_omega(int d, int[] A, int[] dst, int[] src)
{
int i;
for (i = 0; i < MAXDEG; i++)
{
dst[i] = src[i] ^ gmult(d, A[i]);
}
}
internal virtual int compute_discrepancy(int[] lambda, int[] S, int L, int n)
{
int i, sum = 0;
for (i = 0; i <= L; i++)
sum ^= gmult(lambda[i], S[n - i]);
return (sum);
}
/// <summary>******* polynomial arithmetic ******************</summary>
internal virtual void add_polys(int[] dst, int[] src)
{
int i;
for (i = 0; i < MAXDEG; i++)
dst[i] ^= src[i];
}
internal virtual void copy_poly(int[] dst, int[] src)
{
int i;
for (i = 0; i < MAXDEG; i++)
dst[i] = src[i];
}
internal virtual void scale_poly(int k, int[] poly)
{
int i;
for (i = 0; i < MAXDEG; i++)
poly[i] = gmult(k, poly[i]);
}
internal virtual void zero_poly(int[] poly)
{
int i;
for (i = 0; i < MAXDEG; i++)
poly[i] = 0;
}
/* multiply by z, i.e., shift right by 1 */
internal virtual void mul_z_poly(int[] src)
{
int i;
for (i = MAXDEG - 1; i > 0; i--)
src[i] = src[i - 1];
src[0] = 0;
}
/* Finds all the roots of an error-locator polynomial with coefficients
* Lambda[j] by evaluating Lambda at successive values of alpha.
*
* This can be tested with the decoder's equations case.
*/
internal virtual void Find_Roots()
{
int sum, r, k;
NErrors = 0;
for (r = 1; r < 256; r++)
{
sum = 0;
/* evaluate lambda at r */
for (k = 0; k < NPAR + 1; k++)
{
sum ^= gmult(gexp[(k * r) % 255], Lambda[k]);
}
if (sum == 0)
{
ErrorLocs[NErrors] = (255 - r); NErrors++;
//if (DEBUG) fprintf(stderr, "Root found at r = %d, (255-r) = %d\n", r, (255-r));
}
}
}
/* Combined Erasure And Error Magnitude Computation
*
* Pass in the codeword, its size in bytes, as well as
* an array of any known erasure locations, along the number
* of these erasures.
*
* Evaluate Omega(actually Psi)/Lambda' at the roots
* alpha^(-i) for error locs i.
*
* Returns 1 if everything ok, or 0 if an out-of-bounds error is found
*
*/
internal virtual bool correct_errors_erasures(int[] codeword, int csize, int nerasures, int[] erasures)
{
int r, i, j, err;
/* If you want to take advantage of erasure correction, be sure to
set NErasures and ErasureLocs[] with the locations of erasures.
*/
NErasures = nerasures;
for (i = 0; i < NErasures; i++)
ErasureLocs[i] = erasures[i];
Modified_Berlekamp_Massey();
Find_Roots();
if ((NErrors <= NPAR) || NErrors > 0)
{
/* first check for illegal error locs */
for (r = 0; r < NErrors; r++)
{
if (ErrorLocs[r] >= csize)
{
//if (DEBUG) fprintf(stderr, "Error loc i=%d outside of codeword length %d\n", i, csize);
//Console.out.println("Error loc i="+ErrorLocs[r]+" outside of codeword length"+csize);
return false;
}
}
for (r = 0; r < NErrors; r++)
{
int num, denom;
i = ErrorLocs[r];
/* evaluate Omega at alpha^(-i) */
num = 0;
for (j = 0; j < MAXDEG; j++)
num ^= gmult(Omega[j], gexp[((255 - i) * j) % 255]);
/* evaluate Lambda' (derivative) at alpha^(-i) ; all odd powers disappear */
denom = 0;
for (j = 1; j < MAXDEG; j += 2)
{
denom ^= gmult(Lambda[j], gexp[((255 - i) * (j - 1)) % 255]);
}
err = gmult(num, ginv(denom));
//if (DEBUG) fprintf(stderr, "Error magnitude %#x at loc %d\n", err, csize-i);
codeword[csize - i - 1] ^= err;
}
//for (int p = 0; p < codeword.length; p++)
// Console.out.println(codeword[p]);
//Console.out.println("correction succeeded");
return true;
}
else
{
//if (DEBUG && NErrors) fprintf(stderr, "Uncorrectable codeword\n");
//Console.out.println("Uncorrectable codeword");
return false;
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.Targets
{
using System;
using System.IO;
using NLog.Targets;
using System.Collections.Generic;
using Xunit;
using System.Threading.Tasks;
public class ConsoleTargetTests : NLogTestBase
{
[Fact]
public void ConsoleOutWriteLineTest()
{
ConsoleOutTest(false);
}
[Fact]
public void ConsoleOutWriteBufferTest()
{
ConsoleOutTest(true);
}
private void ConsoleOutTest(bool writeBuffer)
{
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
WriteBuffer = writeBuffer,
};
var consoleOutWriter = new StringWriter();
TextWriter oldConsoleOutWriter = Console.Out;
Console.SetOut(consoleOutWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add));
Assert.Equal(6, exceptions.Count);
target.Flush((ex) => { });
target.Close();
}
finally
{
Console.SetOut(oldConsoleOutWriter);
}
var actual = consoleOutWriter.ToString();
Assert.True(actual.IndexOf("-- header --") != -1);
Assert.True(actual.IndexOf("Logger1 message1") != -1);
Assert.True(actual.IndexOf("Logger1 message2") != -1);
Assert.True(actual.IndexOf("Logger1 message3") != -1);
Assert.True(actual.IndexOf("Logger2 message4") != -1);
Assert.True(actual.IndexOf("Logger2 message5") != -1);
Assert.True(actual.IndexOf("Logger1 message6") != -1);
Assert.True(actual.IndexOf("-- footer --") != -1);
}
[Fact]
public void ConsoleErrorTest()
{
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
Error = true,
};
var consoleErrorWriter = new StringWriter();
TextWriter oldConsoleErrorWriter = Console.Error;
Console.SetError(consoleErrorWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add));
Assert.Equal(6, exceptions.Count);
target.Flush((ex) => { });
target.Close();
}
finally
{
Console.SetError(oldConsoleErrorWriter);
}
string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}Logger1 message3{0}Logger2 message4{0}Logger2 message5{0}Logger1 message6{0}-- footer --{0}", Environment.NewLine);
Assert.Equal(expectedResult, consoleErrorWriter.ToString());
}
#if !MONO
[Fact]
public void ConsoleEncodingTest()
{
var consoleOutputEncoding = Console.OutputEncoding;
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
Encoding = System.Text.Encoding.UTF8
};
Assert.Equal(System.Text.Encoding.UTF8, target.Encoding);
var consoleOutWriter = new StringWriter();
TextWriter oldConsoleOutWriter = Console.Out;
Console.SetOut(consoleOutWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
// Not really testing whether Console.OutputEncoding works, but just that it is configured without breaking ConsoleTarget
Assert.Equal(System.Text.Encoding.UTF8, Console.OutputEncoding);
Assert.Equal(System.Text.Encoding.UTF8, target.Encoding);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
Assert.Equal(2, exceptions.Count);
target.Encoding = consoleOutputEncoding;
Assert.Equal(consoleOutputEncoding, Console.OutputEncoding);
target.Close();
}
finally
{
Console.OutputEncoding = consoleOutputEncoding;
Console.SetOut(oldConsoleOutWriter);
}
string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}-- footer --{0}", Environment.NewLine);
Assert.Equal(expectedResult, consoleOutWriter.ToString());
}
#endif
#if !NET3_5 && !MONO
[Fact]
public void ConsoleRaceCondtionIgnoreTest()
{
var configXml = @"
<nlog throwExceptions='true'>
<targets>
<target name='console' type='console' layout='${message}' />
<target name='consoleError' type='console' layout='${message}' error='true' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='console,consoleError' />
</rules>
</nlog>";
ConsoleRaceCondtionIgnoreInnerTest(configXml);
}
internal static void ConsoleRaceCondtionIgnoreInnerTest(string configXml)
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml);
// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug.
// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written
// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service
//
// Full error:
// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory.
// The I/ O package is not thread safe by default.In multithreaded applications,
// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or
// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader.
var oldOut = Console.Out;
var oldError = Console.Error;
try
{
Console.SetOut(StreamWriter.Null);
Console.SetError(StreamWriter.Null);
LogManager.ThrowExceptions = true;
var logger = LogManager.GetCurrentClassLogger();
Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, (_) =>
{
for (int i = 0; i < 100; i++)
{
logger.Trace("test message to the out and error stream");
}
});
}
finally
{
Console.SetOut(oldOut);
Console.SetError(oldError);
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Nop.Core.Domain.Orders;
namespace Nop.Services.Orders
{
/// <summary>
/// Checkout attribute parser
/// </summary>
public partial class CheckoutAttributeParser : ICheckoutAttributeParser
{
private readonly ICheckoutAttributeService _checkoutAttributeService;
public CheckoutAttributeParser(ICheckoutAttributeService checkoutAttributeService)
{
this._checkoutAttributeService = checkoutAttributeService;
}
/// <summary>
/// Gets selected checkout attribute identifiers
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Selected checkout attribute identifiers</returns>
protected virtual IList<int> ParseCheckoutAttributeIds(string attributesXml)
{
var ids = new List<int>();
if (String.IsNullOrEmpty(attributesXml))
return ids;
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(attributesXml);
foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute"))
{
if (node.Attributes != null && node.Attributes["ID"] != null)
{
string str1 = node.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
ids.Add(id);
}
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return ids;
}
/// <summary>
/// Gets selected checkout attributes
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Selected checkout attributes</returns>
public virtual IList<CheckoutAttribute> ParseCheckoutAttributes(string attributesXml)
{
var result = new List<CheckoutAttribute>();
if (String.IsNullOrEmpty(attributesXml))
return result;
var ids = ParseCheckoutAttributeIds(attributesXml);
foreach (int id in ids)
{
var attribute = _checkoutAttributeService.GetCheckoutAttributeById(id);
if (attribute != null)
{
result.Add(attribute);
}
}
return result;
}
/// <summary>
/// Get checkout attribute values
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Checkout attribute values</returns>
public virtual IList<CheckoutAttributeValue> ParseCheckoutAttributeValues(string attributesXml)
{
var values = new List<CheckoutAttributeValue>();
if (String.IsNullOrEmpty(attributesXml))
return values;
var attributes = ParseCheckoutAttributes(attributesXml);
foreach (var attribute in attributes)
{
if (!attribute.ShouldHaveValues())
continue;
var valuesStr = ParseValues(attributesXml, attribute.Id);
foreach (string valueStr in valuesStr)
{
if (!String.IsNullOrEmpty(valueStr))
{
int id;
if (int.TryParse(valueStr, out id))
{
var value = _checkoutAttributeService.GetCheckoutAttributeValueById(id);
if (value != null)
values.Add(value);
}
}
}
}
return values;
}
/// <summary>
/// Gets selected checkout attribute value
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="checkoutAttributeId">Checkout attribute identifier</param>
/// <returns>Checkout attribute value</returns>
public virtual IList<string> ParseValues(string attributesXml, int checkoutAttributeId)
{
var selectedCheckoutAttributeValues = new List<string>();
if (String.IsNullOrEmpty(attributesXml))
return selectedCheckoutAttributeValues;
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(attributesXml);
var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["ID"] != null)
{
string str1 = node1.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (id == checkoutAttributeId)
{
var nodeList2 = node1.SelectNodes(@"CheckoutAttributeValue/Value");
foreach (XmlNode node2 in nodeList2)
{
string value = node2.InnerText.Trim();
selectedCheckoutAttributeValues.Add(value);
}
}
}
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return selectedCheckoutAttributeValues;
}
/// <summary>
/// Adds an attribute
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="ca">Checkout attribute</param>
/// <param name="value">Value</param>
/// <returns>Attributes</returns>
public virtual string AddCheckoutAttribute(string attributesXml, CheckoutAttribute ca, string value)
{
string result = string.Empty;
try
{
var xmlDoc = new XmlDocument();
if (String.IsNullOrEmpty(attributesXml))
{
var element1 = xmlDoc.CreateElement("Attributes");
xmlDoc.AppendChild(element1);
}
else
{
xmlDoc.LoadXml(attributesXml);
}
var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes");
XmlElement attributeElement = null;
//find existing
var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["ID"] != null)
{
string str1 = node1.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (id == ca.Id)
{
attributeElement = (XmlElement)node1;
break;
}
}
}
}
//create new one if not found
if (attributeElement == null)
{
attributeElement = xmlDoc.CreateElement("CheckoutAttribute");
attributeElement.SetAttribute("ID", ca.Id.ToString());
rootElement.AppendChild(attributeElement);
}
var attributeValueElement = xmlDoc.CreateElement("CheckoutAttributeValue");
attributeElement.AppendChild(attributeValueElement);
var attributeValueValueElement = xmlDoc.CreateElement("Value");
attributeValueValueElement.InnerText = value;
attributeValueElement.AppendChild(attributeValueValueElement);
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return result;
}
/// <summary>
/// Removes checkout attributes which cannot be applied to the current cart and returns an update attributes in XML format
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="cart">Shopping cart items</param>
/// <returns>Updated attributes in XML format</returns>
public virtual string EnsureOnlyActiveAttributes(string attributesXml, IList<ShoppingCartItem> cart)
{
if (String.IsNullOrEmpty(attributesXml))
return attributesXml;
var result = attributesXml;
//removing "shippable" checkout attributes if there's no any shippable products in the cart
if (!cart.RequiresShipping())
{
//find attribute IDs to remove
var checkoutAttributeIdsToRemove = new List<int>();
var attributes = ParseCheckoutAttributes(attributesXml);
foreach (var ca in attributes)
if (ca.ShippableProductRequired)
checkoutAttributeIdsToRemove.Add(ca.Id);
//remove them from XML
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(attributesXml);
var nodesToRemove = new List<XmlNode>();
foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute"))
{
if (node.Attributes != null && node.Attributes["ID"] != null)
{
string str1 = node.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (checkoutAttributeIdsToRemove.Contains(id))
{
nodesToRemove.Add(node);
}
}
}
}
foreach(var node in nodesToRemove)
{
node.ParentNode.RemoveChild(node);
}
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
}
return result;
}
/// <summary>
/// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified
/// </summary>
/// <param name="attribute">Checkout attribute</param>
/// <param name="selectedAttributesXml">Selected attributes (XML format)</param>
/// <returns>Result</returns>
public virtual bool? IsConditionMet(CheckoutAttribute attribute, string selectedAttributesXml)
{
if (attribute == null)
throw new ArgumentNullException("attribute");
var conditionAttributeXml = attribute.ConditionAttributeXml;
if (String.IsNullOrEmpty(conditionAttributeXml))
//no condition
return null;
//load an attribute this one depends on
var dependOnAttribute = ParseCheckoutAttributes(conditionAttributeXml).FirstOrDefault();
if (dependOnAttribute == null)
return true;
var valuesThatShouldBeSelected = ParseValues(conditionAttributeXml, dependOnAttribute.Id)
//a workaround here:
//ConditionAttributeXml can contain "empty" values (nothing is selected)
//but in other cases (like below) we do not store empty values
//that's why we remove empty values here
.Where(x => !String.IsNullOrEmpty(x))
.ToList();
var selectedValues = ParseValues(selectedAttributesXml, dependOnAttribute.Id);
if (valuesThatShouldBeSelected.Count != selectedValues.Count)
return false;
//compare values
var allFound = true;
foreach (var t1 in valuesThatShouldBeSelected)
{
bool found = false;
foreach (var t2 in selectedValues)
if (t1 == t2)
found = true;
if (!found)
allFound = false;
}
return allFound;
}
/// <summary>
/// Remove an attribute
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="attribute">Checkout attribute</param>
/// <returns>Updated result (XML format)</returns>
public virtual string RemoveCheckoutAttribute(string attributesXml, CheckoutAttribute attribute)
{
string result = string.Empty;
try
{
var xmlDoc = new XmlDocument();
if (String.IsNullOrEmpty(attributesXml))
{
var element1 = xmlDoc.CreateElement("Attributes");
xmlDoc.AppendChild(element1);
}
else
{
xmlDoc.LoadXml(attributesXml);
}
var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes");
XmlElement attributeElement = null;
//find existing
var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["ID"] != null)
{
string str1 = node1.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (id == attribute.Id)
{
attributeElement = (XmlElement)node1;
break;
}
}
}
}
//found
if (attributeElement != null)
{
rootElement.RemoveChild(attributeElement);
}
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#if IOS
using Foundation;
using UIKit;
#endif
#if ANDROID
using Android.Views;
using Android.App;
using Android.Content.Res;
#endif
#if WINDOWS_PHONE
using MonoGame.Framework.WindowsPhone;
using Microsoft.Phone.Controls;
#endif
#if WINDOWS_PHONE81
using Windows.Graphics.Display;
#endif
#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Activation;
#endif
namespace CocosSharp
{
[Flags]
public enum CCDisplayOrientation
{
Default = 0,
LandscapeLeft = 1,
LandscapeRight = 2,
Portrait = 4,
PortraitDown = 8,
Unknown = 16
}
public static class CCOrientationExtension
{
public static bool IsPortrait(this CCDisplayOrientation orientation)
{
orientation = orientation & (CCDisplayOrientation.Portrait | CCDisplayOrientation.PortraitDown);
return orientation != CCDisplayOrientation.Default;
}
public static bool IsLandscape(this CCDisplayOrientation orientation)
{
orientation = orientation & (CCDisplayOrientation.LandscapeLeft | CCDisplayOrientation.LandscapeRight);
return orientation != CCDisplayOrientation.Default;
}
}
public class CCGameTime
{
#region Properties
public bool IsRunningSlowly { get; set; }
public TimeSpan TotalGameTime { get; set; }
public TimeSpan ElapsedGameTime { get; set; }
#endregion Properties
#region Constructors
public CCGameTime()
{
TotalGameTime = TimeSpan.Zero;
ElapsedGameTime = TimeSpan.Zero;
IsRunningSlowly = false;
}
public CCGameTime(TimeSpan totalGameTime, TimeSpan elapsedGameTime)
{
TotalGameTime = totalGameTime;
ElapsedGameTime = elapsedGameTime;
IsRunningSlowly = false;
}
public CCGameTime(TimeSpan totalRealTime, TimeSpan elapsedRealTime, bool isRunningSlowly)
{
TotalGameTime = totalRealTime;
ElapsedGameTime = elapsedRealTime;
IsRunningSlowly = isRunningSlowly;
}
#endregion Constructors
}
public class CCGame : Game
{
public CCGame()
{
#if WINDOWS_PHONE || NETFX_CORE
// This is needed for Windows Phone 8 to initialize correctly
var graphics = new GraphicsDeviceManager(this);
#endif
#if WINDOWS || WINDOWSGL || MACOS || (NETFX_CORE && !WINDOWS_PHONE81)
this.IsMouseVisible = true;
#endif
#if NETFX_CORE
TouchPanel.EnableMouseTouchPoint = true;
TouchPanel.EnableMouseGestures = true;
// Since there is no entry point for Windows8 XAML that allows us to add the CCApplication after initialization
// of the CCGame we have to load it here. Later on when we add the delegate it will need to be initialized
// separately. Please see ApplicationDelegate property of CCApplication.
new CCApplication(this);
#endif
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void Draw(GameTime gameTime)
{
#if NETFX_CORE
// Windows8 XAML needs to have it's graphics device cleared. This seems to be the
// only platform that needs this. Unfortunately we need to do the same for all
// Windows8 platforms.
GraphicsDevice.Clear(Color.CornflowerBlue);
#endif
base.Draw(gameTime);
#if OUYA
// We will comment this out until Director and DrawManager are sorted out.
// Director.DrawManager.SpriteBatch.Begin();
// float y = 15;
// for (int i = 0; i < 4; ++i)
// {
// GamePadState gs = GamePad.GetState((PlayerIndex)i, GamePadDeadZone.Circular);
// string textToDraw = string.Format(
// "Pad: {0} Connected: {1} LS: ({2:F2}, {3:F2}) RS: ({4:F2}, {5:F2}) LT: {6:F2} RT: {7:F2}",
// i, gs.IsConnected,
// gs.ThumbSticks.Left.X, gs.ThumbSticks.Left.Y,
// gs.ThumbSticks.Right.X, gs.ThumbSticks.Right.Y,
// gs.Triggers.Left, gs.Triggers.Right);
//
// Director.DrawManager.SpriteBatch.DrawString(CCSpriteFontCache.SharedInstance["arial-20"], textToDraw, new Vector2(16, y), Color.White);
// y += 25;
// }
// Director.DrawManager.SpriteBatch.End();
#endif
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
// Allows the game to exit
#if (WINDOWS && !NETFX_CORE) || WINDOWSGL || WINDOWSDX// || MACOS
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
#endif
}
}
public class CCApplicationDelegate
{
public virtual void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { }
// Called when the game enters the background. This happens when the 'windows' button is pressed
// on a WP phone. On Android, it happens when the device is ide or the power button is pressed.
public virtual void ApplicationDidEnterBackground(CCApplication application) { }
// Called when the game returns to the foreground, such as when the game is launched after
// being paused.
public virtual void ApplicationWillEnterForeground(CCApplication application) { }
}
public class CCApplication : DrawableGameComponent
{
readonly List<CCTouch> endedTouches = new List<CCTouch>();
readonly Dictionary<int, LinkedListNode<CCTouch>> touchMap = new Dictionary<int, LinkedListNode<CCTouch>>();
readonly LinkedList<CCTouch> touches = new LinkedList<CCTouch>();
readonly List<CCTouch> movedTouches = new List<CCTouch>();
readonly List<CCTouch> newTouches = new List<CCTouch>();
internal GameTime XnaGameTime;
bool paused;
bool initialized;
bool isNextDeltaTimeZero;
float deltaTime;
#if WINDOWS || WINDOWSGL || MACOS || WINDOWSGL
int lastMouseId;
MouseState lastMouseState;
MouseState prevMouseState;
#endif
#if WINDOWS_PHONE
PhoneApplicationPage windowsPhonePage;
#endif
MouseState priorMouseState;
KeyboardState priorKeyboardState;
Dictionary<PlayerIndex, GamePadState> priorGamePadState;
CCEventGamePadConnection gamePadConnection;
CCEventGamePadButton gamePadButton;
CCEventGamePadDPad gamePadDPad;
CCEventGamePadStick gamePadStick;
CCEventGamePadTrigger gamePadTrigger;
GraphicsDeviceManager xnaDeviceManager;
CCGame xnaGame;
CCGameTime GameTime;
CCWindow mainWindow;
List<CCWindow> gameWindows;
CCApplicationDelegate applicationDelegate;
#region Properties
#if NETFX_CORE && !WINDOWS_PHONE81
public static void Create(CCApplicationDelegate appDelegate)
{
Action<CCGame, Windows.ApplicationModel.Activation.IActivatedEventArgs> initAction =
delegate(CCGame game, Windows.ApplicationModel.Activation.IActivatedEventArgs args)
{
foreach (var component in game.Components)
{
if (component is CCApplication)
{
var instance = component as CCApplication;
instance.ApplicationDelegate = appDelegate;
}
}
};
var factory = new MonoGame.Framework.GameFrameworkViewSource<CCGame>(initAction);
Windows.ApplicationModel.Core.CoreApplication.Run(factory);
}
public static void Create(CCApplicationDelegate appDelegate, LaunchActivatedEventArgs args, Windows.UI.Core.CoreWindow coreWindow, SwapChainBackgroundPanel swapChainBackgroundPanel)
{
var game = MonoGame.Framework.XamlGame<CCGame>.Create(args, coreWindow, swapChainBackgroundPanel);
foreach (var component in game.Components)
{
if (component is CCApplication)
{
var instance = component as CCApplication;
instance.ApplicationDelegate = appDelegate;
}
}
}
#endif
#if WINDOWS_PHONE81
public static void Create(CCApplicationDelegate appDelegate, string launchArguments, Windows.UI.Core.CoreWindow coreWindow, SwapChainBackgroundPanel swapChainBackgroundPanel)
{
var game = MonoGame.Framework.XamlGame<CCGame>.Create(launchArguments, coreWindow, swapChainBackgroundPanel);
foreach (var component in game.Components)
{
if (component is CCApplication)
{
var instance = component as CCApplication;
instance.ApplicationDelegate = appDelegate;
}
}
}
#endif
#if WINDOWS_PHONE
public static void Create(CCApplicationDelegate appDelegate, string launchParameters, PhoneApplicationPage page)
{
var game = XamlGame<CCGame>.Create(launchParameters, page);
var instance = new CCApplication(game, page);
instance.ApplicationDelegate = appDelegate;
}
#endif
public static float DefaultTexelToContentSizeRatio
{
set { DefaultTexelToContentSizeRatios = new CCSize(value, value); }
}
public static CCSize DefaultTexelToContentSizeRatios
{
set
{
CCSprite.DefaultTexelToContentSizeRatios = value;
CCTileMapLayer.DefaultTexelToContentSizeRatios = value;
CCLabel.DefaultTexelToContentSizeRatios = value;
}
}
// Instance properties
public bool HandleMediaStateAutomatically { get; set; }
public CCDisplayOrientation CurrentOrientation { get; private set; }
public CCActionManager ActionManager { get; private set; }
public CCScheduler Scheduler { get; private set; }
public CCApplicationDelegate ApplicationDelegate
{
get { return applicationDelegate; }
set
{
applicationDelegate = value;
// If the CCApplication has already been initilized then we need to call the delegates
// ApplicationDidFinishLaunching method so that initialization can take place.
// This only happens on Windows 8 XAML applications but because of the changes
// that were needed to incorporate Windows 8 in general it will happen on all
// Windows 8 platforms.
if (initialized)
applicationDelegate.ApplicationDidFinishLaunching(this, MainWindow);
}
}
public bool Paused
{
get { return paused; }
set
{
if (paused != value)
{
paused = value;
if (!paused)
deltaTime = 0;
}
}
}
public bool PreferMultiSampling
{
get
{
var service = Game.Services.GetService(typeof(IGraphicsDeviceService));
var manager = service as GraphicsDeviceManager;
Debug.Assert(manager != null, "CCApplication: GraphicsManager is not setup");
if (manager != null)
return manager.PreferMultiSampling;
return false;
}
set
{
var service = Game.Services.GetService(typeof(IGraphicsDeviceService));
var manager = service as GraphicsDeviceManager;
Debug.Assert(manager != null, "CCApplication: GraphicsManager is not setup");
if (manager != null)
{
manager.PreferMultiSampling = value;
}
}
}
// The time, which expressed in seconds, between current frame and next
public virtual double AnimationInterval
{
get { return Game.TargetElapsedTime.Milliseconds / 10000000f; }
set { Game.TargetElapsedTime = TimeSpan.FromTicks((int)(value * 10000000)); }
}
public string ContentRootDirectory
{
get { return CCContentManager.SharedContentManager.RootDirectory; }
set { CCContentManager.SharedContentManager.RootDirectory = value; }
}
public List<string> ContentSearchPaths
{
get { return CCContentManager.SharedContentManager.SearchPaths; }
set { CCContentManager.SharedContentManager.SearchPaths = value; }
}
public List<string> ContentSearchResolutionOrder
{
get { return CCContentManager.SharedContentManager.SearchResolutionsOrder; }
set { CCContentManager.SharedContentManager.SearchResolutionsOrder = value; }
}
// Remove once multiple window support added
public CCWindow MainWindow
{
get
{
if (mainWindow == null)
{
CCSize windowSize
= new CCSize(xnaDeviceManager.PreferredBackBufferWidth, xnaDeviceManager.PreferredBackBufferHeight);
mainWindow = AddWindow(windowSize);
}
return mainWindow;
}
}
ContentManager Content
{
get { return (CCContentManager.SharedContentManager); }
set { }
}
#if ANDROID
public View AndroidContentView
{
get
{
View androidView = null;
if (xnaGame != null)
androidView = (View)xnaGame.Services.GetService(typeof(View));
return androidView;
}
}
#endif
#if WINDOWS_PHONE
public PhoneApplicationPage WindowsPhonePage
{
get; private set;
}
#endif
internal GraphicsDeviceManager GraphicsDeviceManager
{
get { return Game.Services.GetService(typeof(IGraphicsDeviceService)) as GraphicsDeviceManager; }
}
#endregion Properties
#region Constructors
public CCApplication(bool isFullScreen = true, CCSize? mainWindowSizeInPixels = null)
: this(new CCGame(), isFullScreen, mainWindowSizeInPixels)
{
}
#if WINDOWS_PHONE
internal CCApplication(CCGame game, PhoneApplicationPage wpPage, bool isFullScreen = true, CCSize? mainWindowSizeInPixels = null)
: this(game, isFullScreen, mainWindowSizeInPixels)
{
WindowsPhonePage = wpPage;
// Setting up the window correctly requires knowledge of the phone app page which needs to be set first
InitializeMainWindow((mainWindowSizeInPixels.HasValue) ? mainWindowSizeInPixels.Value : CCSize.Zero, isFullScreen);
}
#endif
internal CCApplication(CCGame game, bool isFullScreen = true, CCSize? mainWindowSizeInPixels = null)
: base(game)
{
GameTime = new CCGameTime();
xnaGame = game;
Scheduler = new CCScheduler();
ActionManager = new CCActionManager();
Scheduler.Schedule(ActionManager, CCSchedulePriority.System, false);
priorGamePadState = new Dictionary<PlayerIndex, GamePadState>();
gamePadConnection = new CCEventGamePadConnection();
gamePadButton = new CCEventGamePadButton();
gamePadDPad = new CCEventGamePadDPad();
gamePadStick = new CCEventGamePadStick();
gamePadTrigger = new CCEventGamePadTrigger();
IGraphicsDeviceService service = (IGraphicsDeviceService)Game.Services.GetService(typeof(IGraphicsDeviceService));
if (service == null)
{
service = new GraphicsDeviceManager(game);
// if we still do not have a service after creating the GraphicsDeviceManager
// we need to stop somewhere and issue a warning.
if (Game.Services.GetService(typeof(IGraphicsDeviceService)) == null)
{
Game.Services.AddService(typeof(IGraphicsDeviceService), service);
}
}
xnaDeviceManager = (GraphicsDeviceManager)service;
Content = game.Content;
HandleMediaStateAutomatically = true;
game.IsFixedTimeStep = true;
TouchPanel.EnabledGestures = GestureType.Tap;
game.Activated += GameActivated;
game.Deactivated += GameDeactivated;
game.Exiting += GameExiting;
game.Window.OrientationChanged += OrientationChanged;
game.Components.Add(this);
gameWindows = new List<CCWindow>();
// Setting up the window correctly requires knowledge of the phone app page which needs to be set first
#if !WINDOWS_PHONE
InitializeMainWindow((mainWindowSizeInPixels.HasValue) ? mainWindowSizeInPixels.Value : new CCSize(800,480), isFullScreen);
#endif
}
#endregion Constructors
#region Game window management
void InitializeMainWindow(CCSize windowSizeInPixels, bool isFullscreen = false)
{
if (isFullscreen)
{
#if NETFX_CORE
// GraphicsAdapter values are not set correctly when it gets to here so we used the
// DeviceManager values.
//if (xnaDeviceManager.GraphicsDevice.DisplayMode.)
if (xnaGame.Window.CurrentOrientation == DisplayOrientation.Portrait
|| xnaGame.Window.CurrentOrientation == DisplayOrientation.PortraitDown)
{
windowSizeInPixels.Width = xnaDeviceManager.PreferredBackBufferHeight;
windowSizeInPixels.Height = xnaDeviceManager.PreferredBackBufferWidth;
}
else
{
windowSizeInPixels.Width = xnaDeviceManager.PreferredBackBufferWidth;
windowSizeInPixels.Height = xnaDeviceManager.PreferredBackBufferHeight;
}
#else
windowSizeInPixels.Width = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
windowSizeInPixels.Height = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
#endif
}
xnaDeviceManager.IsFullScreen = isFullscreen;
if (CCDrawManager.SharedDrawManager == null)
{
CCDrawManager.SharedDrawManager
= new CCDrawManager(xnaDeviceManager, windowSizeInPixels, PlatformSupportedOrientations());
}
}
CCDisplayOrientation PlatformSupportedOrientations()
{
CCDisplayOrientation supportedOrientations = CCDisplayOrientation.Default;
#if IOS
UIApplication sharedApp = UIApplication.SharedApplication;
UIInterfaceOrientationMask iOSSupportedOrientations
= sharedApp.SupportedInterfaceOrientationsForWindow(sharedApp.Windows[0]);
if((iOSSupportedOrientations & UIInterfaceOrientationMask.Portrait) != 0)
supportedOrientations |= CCDisplayOrientation.Portrait;
if((iOSSupportedOrientations & UIInterfaceOrientationMask.PortraitUpsideDown) != 0)
supportedOrientations |= CCDisplayOrientation.PortraitDown;
if((iOSSupportedOrientations & UIInterfaceOrientationMask.LandscapeLeft) != 0)
supportedOrientations |= CCDisplayOrientation.LandscapeLeft;
if((iOSSupportedOrientations & UIInterfaceOrientationMask.LandscapeRight) != 0)
supportedOrientations |= CCDisplayOrientation.LandscapeRight;
#elif ANDROID
View androidView = this.AndroidContentView;
Orientation androidSuppOrientation = androidView.Resources.Configuration.Orientation;
if((androidSuppOrientation & Orientation.Portrait) != Orientation.Undefined)
supportedOrientations |= CCDisplayOrientation.Portrait | CCDisplayOrientation.PortraitDown;
if((androidSuppOrientation & Orientation.Landscape) != Orientation.Undefined)
supportedOrientations |= CCDisplayOrientation.LandscapeLeft | CCDisplayOrientation.LandscapeRight;
#elif WINDOWS_PHONE
switch(WindowsPhonePage.SupportedOrientations)
{
case SupportedPageOrientation.Landscape:
supportedOrientations = CCDisplayOrientation.LandscapeLeft | CCDisplayOrientation.LandscapeRight;
break;
case SupportedPageOrientation.Portrait:
supportedOrientations = CCDisplayOrientation.Portrait | CCDisplayOrientation.PortraitDown;
break;
default:
supportedOrientations = CCDisplayOrientation.LandscapeLeft | CCDisplayOrientation.LandscapeRight |
CCDisplayOrientation.Portrait | CCDisplayOrientation.PortraitDown;
break;
}
#elif WINDOWS_PHONE81
var preferences = DisplayInformation.AutoRotationPreferences;
supportedOrientations = CCDisplayOrientation.Default;
if ((preferences & DisplayOrientations.Portrait) == DisplayOrientations.Portrait)
{
supportedOrientations |= CCDisplayOrientation.Portrait;
}
if ((preferences & DisplayOrientations.Landscape) == DisplayOrientations.Landscape)
{
supportedOrientations |= CCDisplayOrientation.LandscapeLeft;
}
if ((preferences & DisplayOrientations.LandscapeFlipped) == DisplayOrientations.LandscapeFlipped)
{
supportedOrientations |= CCDisplayOrientation.LandscapeRight;
}
if ((preferences & DisplayOrientations.PortraitFlipped) == DisplayOrientations.PortraitFlipped)
{
supportedOrientations |= CCDisplayOrientation.PortraitDown;
}
#else
supportedOrientations = CCDisplayOrientation.LandscapeLeft;
#endif
return supportedOrientations;
}
// Make public once multiple window support added
CCWindow AddWindow(CCSize screenSizeInPixels)
{
CCWindow window = new CCWindow(this, screenSizeInPixels, xnaGame.Window, xnaDeviceManager);
// We need to reset the device so internal variables are setup correctly when
// we need to draw primitives or visit nodes outside of the Scene Graph. Example is
// when drawing to a render texture in a class. If the device is not initialized correctly before
// the first application Draw() in the application occurs then drawing with primitives results in weird behaviour.
window.DrawManager.ResetDevice ();
gameWindows.Add(window);
return window;
}
void RemoveWindow(CCWindow window)
{
// TBA once multiple window support added
}
#endregion Game window management
#region Cleaning up
public void PurgeAllCachedData()
{
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
CCDrawManager.SharedDrawManager = null;
}
base.Dispose(disposing);
}
#endregion Cleaning up
#region Game state
public void StartGame()
{
if (xnaGame != null)
{
#if !NETFX_CORE
xnaGame.Run();
#endif
}
}
public void ExitGame()
{
foreach (CCWindow window in gameWindows)
{
window.EndAllSceneDirectors();
}
#if (WINDOWS && !NETFX_CORE) || WINDOWSGL || WINDOWSDX || MACOS
xnaGame.Exit();
#endif
}
#endregion Game state
// Implement for initialize OpenGL instance, set source path, etc...
public virtual bool InitInstance()
{
return true;
}
void OrientationChanged(object sender, EventArgs e)
{
CurrentOrientation = (CCDisplayOrientation)Game.Window.CurrentOrientation;
}
void GameActivated(object sender, EventArgs e)
{
// Clear out the prior gamepad state because we don't want it anymore.
priorGamePadState.Clear();
#if !IOS
if (HandleMediaStateAutomatically)
{
CocosDenshion.CCSimpleAudioEngine.SharedEngine.SaveMediaState();
}
#endif
if (ApplicationDelegate != null)
ApplicationDelegate.ApplicationWillEnterForeground(this);
}
void GameDeactivated(object sender, EventArgs e)
{
if (ApplicationDelegate != null)
ApplicationDelegate.ApplicationDidEnterBackground(this);
#if !IOS
if (HandleMediaStateAutomatically)
{
CocosDenshion.CCSimpleAudioEngine.SharedEngine.RestoreMediaState();
}
#endif
}
void GameExiting(object sender, EventArgs e)
{
// Explicitly dispose of graphics device which will in turn dispose of all graphics resources
// This allows us to delete things in a deterministic manner without relying on finalizers
xnaGame.GraphicsDevice.Dispose();
foreach (CCWindow window in gameWindows)
{
window.EndAllSceneDirectors();
}
}
public void ClearTouches()
{
touches.Clear();
touchMap.Clear();
}
protected override void LoadContent()
{
if (!initialized)
{
CCContentManager.Initialize(Game.Content.ServiceProvider, Game.Content.RootDirectory);
base.LoadContent();
if (ApplicationDelegate != null)
ApplicationDelegate.ApplicationDidFinishLaunching(this, this.MainWindow);
initialized = true;
}
else
{
base.LoadContent();
}
}
public override void Initialize()
{
InitInstance();
base.Initialize();
}
public override void Update(GameTime gameTime)
{
XnaGameTime = gameTime;
GameTime.ElapsedGameTime = gameTime.ElapsedGameTime;
GameTime.IsRunningSlowly = gameTime.IsRunningSlowly;
GameTime.TotalGameTime = gameTime.TotalGameTime;
#if !NETFX_CORE
foreach(CCWindow window in gameWindows)
{
if (window.Accelerometer != null
&& window.Accelerometer.Enabled
&& window.EventDispatcher.IsEventListenersFor(CCEventListenerAccelerometer.LISTENER_ID))
{
window.Accelerometer.Update();
}
}
#endif
foreach (CCWindow window in gameWindows)
{
ProcessTouch(window);
if (window.GamePadEnabled)
{
ProcessGamePad(window);
}
ProcessKeyboard(window);
ProcessMouse(window);
if (!paused)
{
if (isNextDeltaTimeZero)
{
deltaTime = 0;
isNextDeltaTimeZero = false;
}
else
{
deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
}
Scheduler.Update(deltaTime);
window.Update(deltaTime);
}
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
XnaGameTime = gameTime;
GameTime.ElapsedGameTime = gameTime.ElapsedGameTime;
GameTime.IsRunningSlowly = gameTime.IsRunningSlowly;
GameTime.TotalGameTime = gameTime.TotalGameTime;
foreach (CCWindow window in gameWindows)
{
window.DrawManager.BeginDraw();
window.MainLoop(GameTime);
window.DrawManager.EndDraw();
}
base.Draw(gameTime);
}
public void ToggleFullScreen()
{
var service = Game.Services.GetService(typeof(IGraphicsDeviceService));
var manager = service as GraphicsDeviceManager;
Debug.Assert(manager != null, "CCApplication: GraphicsManager is not setup");
if (manager != null)
{
manager.ToggleFullScreen();
}
}
internal virtual void HandleGesture(GestureSample gesture)
{
//TODO: Create CCGesture and convert the coordinates into the local coordinates.
}
#region GamePad Support
void ProcessGamePad(CCWindow window, GamePadState gps, PlayerIndex player)
{
var dispatcher = window.EventDispatcher;
var lastState = new GamePadState();
if (!priorGamePadState.ContainsKey(player) && gps.IsConnected)
{
gamePadConnection.IsConnected = true;
gamePadConnection.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadConnection);
}
if (priorGamePadState.ContainsKey(player))
{
lastState = priorGamePadState[player];
// Notify listeners when the gamepad is connected/disconnected.
if ((lastState.IsConnected != gps.IsConnected))
{
gamePadConnection.IsConnected = false;
gamePadConnection.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadConnection);
}
// TODO: Check button pressed/released status for button tap events.
}
if (gps.IsConnected)
{
var caps = GamePad.GetCapabilities(player);
if (caps.HasBackButton ||
caps.HasStartButton ||
caps.HasBigButton ||
caps.HasAButton ||
caps.HasBButton ||
caps.HasXButton ||
caps.HasYButton ||
caps.HasLeftShoulderButton ||
caps.HasRightShoulderButton)
{
var back = CCGamePadButtonStatus.NotApplicable;
var start = CCGamePadButtonStatus.NotApplicable;
var system = CCGamePadButtonStatus.NotApplicable;
var a = CCGamePadButtonStatus.NotApplicable;
var b = CCGamePadButtonStatus.NotApplicable;
var x = CCGamePadButtonStatus.NotApplicable;
var y = CCGamePadButtonStatus.NotApplicable;
var leftShoulder = CCGamePadButtonStatus.NotApplicable;
var rightShoulder = CCGamePadButtonStatus.NotApplicable;
if (caps.HasBackButton)
{
back = (gps.Buttons.Back == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasStartButton)
{
start = (gps.Buttons.Start == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasBigButton)
{
system = (gps.Buttons.BigButton == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasAButton)
{
a = (gps.Buttons.A == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasBButton)
{
b = (gps.Buttons.B == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasXButton)
{
x = (gps.Buttons.X == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasYButton)
{
y = (gps.Buttons.Y == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasLeftShoulderButton)
{
leftShoulder = (gps.Buttons.LeftShoulder == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasRightShoulderButton)
{
rightShoulder = (gps.Buttons.RightShoulder == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
gamePadButton.Back = back;
gamePadButton.Start = start;
gamePadButton.System = system;
gamePadButton.A = a;
gamePadButton.B = b;
gamePadButton.X = x;
gamePadButton.Y = y;
gamePadButton.LeftShoulder = leftShoulder;
gamePadButton.RightShoulder = rightShoulder;
gamePadButton.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadButton);
}
// Process the game sticks
if ((caps.HasLeftXThumbStick ||
caps.HasLeftYThumbStick ||
caps.HasRightXThumbStick ||
caps.HasRightYThumbStick ||
caps.HasLeftStickButton ||
caps.HasRightStickButton))
{
CCPoint vecLeft;
if (caps.HasLeftXThumbStick || caps.HasLeftYThumbStick)
{
vecLeft = new CCPoint(gps.ThumbSticks.Left);
vecLeft.Normalize();
}
else
{
vecLeft = CCPoint.Zero;
}
CCPoint vecRight;
if (caps.HasRightXThumbStick || caps.HasRightYThumbStick)
{
vecRight = new CCPoint(gps.ThumbSticks.Right);
vecRight.Normalize();
}
else
{
vecRight = CCPoint.Zero;
}
var left = new CCGameStickStatus();
left.Direction = vecLeft;
left.Magnitude = ((caps.HasLeftXThumbStick || caps.HasLeftYThumbStick) ? gps.ThumbSticks.Left.Length() : 0f);
left.IsDown = ((caps.HasLeftStickButton) ? gps.IsButtonDown(Buttons.LeftStick) : false);
var right = new CCGameStickStatus();
right.Direction = vecRight;
right.Magnitude = ((caps.HasRightXThumbStick || caps.HasRightYThumbStick) ? gps.ThumbSticks.Right.Length() : 0f);
right.IsDown = ((caps.HasLeftStickButton) ? gps.IsButtonDown(Buttons.RightStick) : false);
gamePadStick.Left = left;
gamePadStick.Right = right;
gamePadStick.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadStick);
}
// Process the game triggers
if (caps.HasLeftTrigger || caps.HasRightTrigger)
{
//GamePadTriggerUpdate (caps.HasLeftTrigger ? gps.Triggers.Left : 0f, caps.HasRightTrigger ? gps.Triggers.Right : 0f, player);
gamePadTrigger.Left = caps.HasLeftTrigger ? gps.Triggers.Left : 0f;
gamePadTrigger.Right = caps.HasRightTrigger ? gps.Triggers.Right : 0f;
gamePadTrigger.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadTrigger);
}
// Process the D-Pad
if (caps.HasDPadDownButton ||
caps.HasDPadUpButton ||
caps.HasDPadLeftButton ||
caps.HasDPadRightButton)
{
var leftButton = CCGamePadButtonStatus.NotApplicable;
var rightButton = CCGamePadButtonStatus.NotApplicable;
var upButton = CCGamePadButtonStatus.NotApplicable;
var downButton = CCGamePadButtonStatus.NotApplicable;
if (caps.HasDPadDownButton)
{
downButton = (gps.DPad.Down == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasDPadUpButton)
{
upButton = (gps.DPad.Up == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasDPadLeftButton)
{
leftButton = (gps.DPad.Left == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
if (caps.HasDPadRightButton)
{
rightButton = (gps.DPad.Right == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
}
gamePadDPad.Down = downButton;
gamePadDPad.Up = upButton;
gamePadDPad.Left = leftButton;
gamePadDPad.Right = rightButton;
gamePadDPad.Player = (CCPlayerIndex)player;
dispatcher.DispatchEvent(gamePadDPad);
}
}
priorGamePadState[player] = gps;
}
void ProcessGamePad(CCWindow window)
{
if (window.GamePadEnabled &&
window.EventDispatcher.IsEventListenersFor(CCEventListenerGamePad.LISTENER_ID))
{
// On Android, the gamepad is always connected.
GamePadState gps1 = GamePad.GetState(PlayerIndex.One);
GamePadState gps2 = GamePad.GetState(PlayerIndex.Two);
GamePadState gps3 = GamePad.GetState(PlayerIndex.Three);
GamePadState gps4 = GamePad.GetState(PlayerIndex.Four);
ProcessGamePad(window, gps1, PlayerIndex.One);
ProcessGamePad(window, gps2, PlayerIndex.Two);
ProcessGamePad(window, gps3, PlayerIndex.Three);
ProcessGamePad(window, gps4, PlayerIndex.Four);
}
}
#endregion Gamepad support
#region Keyboard support
void ProcessKeyboard(CCWindow window)
{
// Read the current keyboard state
KeyboardState currentKeyboardState = Keyboard.GetState();
var dispatcher = window.EventDispatcher;
if (currentKeyboardState == priorKeyboardState || !dispatcher.IsEventListenersFor(CCEventListenerKeyboard.LISTENER_ID))
{
priorKeyboardState = currentKeyboardState;
return;
}
var keyboardEvent = new CCEventKeyboard(CCKeyboardEventType.KEYBOARD_PRESS);
var keyboardState = new CCKeyboardState() { KeyboardState = currentKeyboardState };
keyboardEvent.KeyboardState = keyboardState;
// Check for pressed/released keys.
// Loop for each possible pressed key (those that are pressed this update)
Keys[] keys = currentKeyboardState.GetPressedKeys();
for (int k = 0; k < keys.Length; k++)
{
// Was this key up during the last update?
if (priorKeyboardState.IsKeyUp(keys[k]))
{
// Yes, so this key has been pressed
//CCLog.Log("Pressed: " + keys[i].ToString());
keyboardEvent.Keys = (CCKeys)keys[k];
dispatcher.DispatchEvent(keyboardEvent);
}
}
// Loop for each possible released key (those that were pressed last update)
keys = priorKeyboardState.GetPressedKeys();
keyboardEvent.KeyboardEventType = CCKeyboardEventType.KEYBOARD_RELEASE;
for (int k = 0; k < keys.Length; k++)
{
// Is this key now up?
if (currentKeyboardState.IsKeyUp(keys[k]))
{
// Yes, so this key has been released
//CCLog.Log("Released: " + keys[i].ToString());
keyboardEvent.Keys = (CCKeys)keys[k];
dispatcher.DispatchEvent(keyboardEvent);
}
}
// Store the state for the next loop
priorKeyboardState = currentKeyboardState;
}
#endregion Keyboard support
#region Mouse support
void ProcessMouse(CCWindow window)
{
// Read the current Mouse state
MouseState currentMouseState = Mouse.GetState();
var dispatcher = window.EventDispatcher;
if (currentMouseState == priorMouseState || !dispatcher.IsEventListenersFor(CCEventListenerMouse.LISTENER_ID))
{
priorMouseState = currentMouseState;
return;
}
CCPoint pos;
#if NETFX_CORE
//Because MonoGame and CocosSharp uses different Y axis, we need to convert the coordinate here
pos = TransformPoint(priorMouseState.X, Game.Window.ClientBounds.Height - priorMouseState.Y);
#else
//Because MonoGame and CocosSharp uses different Y axis, we need to convert the coordinate here
//No need to convert Y-Axis
pos = new CCPoint(priorMouseState.X, priorMouseState.Y);
#endif
var mouseEvent = new CCEventMouse(CCMouseEventType.MOUSE_MOVE);
mouseEvent.CursorX = pos.X;
mouseEvent.CursorY = pos.Y;
dispatcher.DispatchEvent(mouseEvent);
CCMouseButton mouseButton = CCMouseButton.None;
if (priorMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
mouseButton |= CCMouseButton.LeftButton;
}
if (priorMouseState.RightButton == ButtonState.Released && currentMouseState.RightButton == ButtonState.Pressed)
{
mouseButton |= CCMouseButton.RightButton;
}
if (priorMouseState.MiddleButton == ButtonState.Released && currentMouseState.MiddleButton == ButtonState.Pressed)
{
mouseButton |= CCMouseButton.MiddleButton;
}
if (priorMouseState.XButton1 == ButtonState.Released && currentMouseState.XButton1 == ButtonState.Pressed)
{
mouseButton |= CCMouseButton.ExtraButton1;
}
if (priorMouseState.XButton2 == ButtonState.Released && currentMouseState.XButton2 == ButtonState.Pressed)
{
mouseButton |= CCMouseButton.ExtraButton1;
}
if (mouseButton > 0)
{
mouseEvent.MouseEventType = CCMouseEventType.MOUSE_DOWN;
mouseEvent.MouseButton = mouseButton;
dispatcher.DispatchEvent(mouseEvent);
}
mouseButton = CCMouseButton.None;
if (priorMouseState.LeftButton == ButtonState.Pressed && currentMouseState.LeftButton == ButtonState.Released)
{
mouseButton |= CCMouseButton.LeftButton;
}
if (priorMouseState.RightButton == ButtonState.Pressed && currentMouseState.RightButton == ButtonState.Released)
{
mouseButton |= CCMouseButton.RightButton;
}
if (priorMouseState.MiddleButton == ButtonState.Pressed && currentMouseState.MiddleButton == ButtonState.Released)
{
mouseButton |= CCMouseButton.MiddleButton;
}
if (priorMouseState.XButton1 == ButtonState.Pressed && currentMouseState.XButton1 == ButtonState.Released)
{
mouseButton |= CCMouseButton.ExtraButton1;
}
if (priorMouseState.XButton2 == ButtonState.Pressed && currentMouseState.XButton2 == ButtonState.Released)
{
mouseButton |= CCMouseButton.ExtraButton1;
}
if (mouseButton > 0)
{
mouseEvent.MouseEventType = CCMouseEventType.MOUSE_UP;
mouseEvent.MouseButton = mouseButton;
dispatcher.DispatchEvent(mouseEvent);
}
if (priorMouseState.ScrollWheelValue != currentMouseState.ScrollWheelValue)
{
var delta = priorMouseState.ScrollWheelValue - currentMouseState.ScrollWheelValue;
if (delta != 0)
{
mouseEvent.MouseEventType = CCMouseEventType.MOUSE_SCROLL;
mouseEvent.ScrollX = 0;
mouseEvent.ScrollY = delta;
dispatcher.DispatchEvent(mouseEvent);
//Console.WriteLine ("mouse scroll: " + mouseEvent.ScrollY);
}
}
// Store the state for the next loop
priorMouseState = currentMouseState;
}
#endregion Mouse support
CCPoint TransformPoint(float x, float y)
{
CCPoint newPoint;
newPoint.X = x * TouchPanel.DisplayWidth / Game.Window.ClientBounds.Width;
newPoint.Y = y * TouchPanel.DisplayHeight / Game.Window.ClientBounds.Height;
return newPoint;
}
void ProcessTouch(CCWindow window)
{
if (window.EventDispatcher.IsEventListenersFor(CCEventListenerTouchOneByOne.LISTENER_ID)
|| window.EventDispatcher.IsEventListenersFor(CCEventListenerTouchAllAtOnce.LISTENER_ID))
{
newTouches.Clear();
movedTouches.Clear();
endedTouches.Clear();
CCPoint pos = CCPoint.Zero;
// TODO: allow configuration to treat the game pad as a touch device.
#if WINDOWS || WINDOWSGL || MACOS
pos = new CCPoint(lastMouseState.X, lastMouseState.Y);
prevMouseState = lastMouseState;
lastMouseState = Mouse.GetState();
if (prevMouseState.LeftButton == ButtonState.Released && lastMouseState.LeftButton == ButtonState.Pressed)
{
lastMouseId++;
touches.AddLast(new CCTouch(lastMouseId, pos.X, pos.Y));
touchMap.Add(lastMouseId, touches.Last);
newTouches.Add(touches.Last.Value);
}
else if (prevMouseState.LeftButton == ButtonState.Pressed && lastMouseState.LeftButton == ButtonState.Pressed)
{
if (touchMap.ContainsKey(lastMouseId))
{
if (prevMouseState.X != lastMouseState.X || prevMouseState.Y != lastMouseState.Y)
{
movedTouches.Add(touchMap[lastMouseId].Value);
touchMap[lastMouseId].Value.SetTouchInfo(lastMouseId, pos.X, pos.Y);
}
}
}
else if (prevMouseState.LeftButton == ButtonState.Pressed && lastMouseState.LeftButton == ButtonState.Released)
{
if (touchMap.ContainsKey(lastMouseId))
{
endedTouches.Add(touchMap[lastMouseId].Value);
touches.Remove(touchMap[lastMouseId]);
touchMap.Remove(lastMouseId);
}
}
#endif
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation touch in touchCollection)
{
switch (touch.State)
{
case TouchLocationState.Pressed:
if (touchMap.ContainsKey(touch.Id))
{
break;
}
pos = new CCPoint(touch.Position.X, touch.Position.Y);
touches.AddLast(new CCTouch(touch.Id, pos.X, pos.Y));
touchMap.Add(touch.Id, touches.Last);
newTouches.Add(touches.Last.Value);
break;
case TouchLocationState.Moved:
LinkedListNode<CCTouch> existingTouch;
if (touchMap.TryGetValue(touch.Id, out existingTouch))
{
pos = new CCPoint(touch.Position.X, touch.Position.Y);
var delta = existingTouch.Value.LocationOnScreen - pos;
if (delta.LengthSquared > 1.0f)
{
movedTouches.Add(existingTouch.Value);
existingTouch.Value.SetTouchInfo(touch.Id, pos.X, pos.Y);
}
}
break;
case TouchLocationState.Released:
if (touchMap.TryGetValue(touch.Id, out existingTouch))
{
endedTouches.Add(existingTouch.Value);
touches.Remove(existingTouch);
touchMap.Remove(touch.Id);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
var touchEvent = new CCEventTouch(CCEventCode.BEGAN);
if (newTouches.Count > 0)
{
touchEvent.Touches = newTouches;
//m_pDelegate.TouchesBegan(newTouches);
window.EventDispatcher.DispatchEvent(touchEvent);
}
if (movedTouches.Count > 0)
{
touchEvent.EventCode = CCEventCode.MOVED;
touchEvent.Touches = movedTouches;
window.EventDispatcher.DispatchEvent(touchEvent);
}
if (endedTouches.Count > 0)
{
touchEvent.EventCode = CCEventCode.ENDED;
touchEvent.Touches = endedTouches;
window.EventDispatcher.DispatchEvent(touchEvent);
}
}
}
CCTouch GetTouchBasedOnId(int nID)
{
if (touchMap.ContainsKey(nID))
{
LinkedListNode<CCTouch> curTouch = touchMap[nID];
//If ID's match...
if (curTouch.Value.Id == nID)
{
//return the corresponding touch
return curTouch.Value;
}
}
//If we reached here, we found no touches
//matching the specified id.
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System
{
public abstract partial class Type : MemberInfo, IReflect
{
protected Type() { }
public override MemberTypes MemberType => MemberTypes.TypeInfo;
public new Type GetType() => base.GetType();
public abstract string Namespace { get; }
public abstract string AssemblyQualifiedName { get; }
public abstract string FullName { get; }
public abstract Assembly Assembly { get; }
public abstract new Module Module { get; }
public bool IsNested => DeclaringType != null;
public override Type DeclaringType => null;
public virtual MethodBase DeclaringMethod => null;
public override Type ReflectedType => null;
public abstract Type UnderlyingSystemType { get; }
public virtual bool IsTypeDefinition { get { throw NotImplemented.ByDesign; } }
public bool IsArray => IsArrayImpl();
protected abstract bool IsArrayImpl();
public bool IsByRef => IsByRefImpl();
protected abstract bool IsByRefImpl();
public bool IsPointer => IsPointerImpl();
protected abstract bool IsPointerImpl();
public virtual bool IsConstructedGenericType { get { throw NotImplemented.ByDesign; } }
public virtual bool IsGenericParameter => false;
public virtual bool IsGenericType => false;
public virtual bool IsGenericTypeDefinition => false;
public virtual bool IsSZArray { get { throw NotImplemented.ByDesign; } }
public virtual bool IsVariableBoundArray => IsArray && !IsSZArray;
public virtual bool IsByRefLike => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public bool HasElementType => HasElementTypeImpl();
protected abstract bool HasElementTypeImpl();
public abstract Type GetElementType();
public virtual int GetArrayRank() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type GetGenericTypeDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type[] GenericTypeArguments => (IsGenericType && !IsGenericTypeDefinition) ? GetGenericArguments() : Array.Empty<Type>();
public virtual Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual int GenericParameterPosition { get { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } }
public virtual GenericParameterAttributes GenericParameterAttributes { get { throw new NotSupportedException(); } }
public virtual Type[] GetGenericParameterConstraints()
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
throw new InvalidOperationException();
}
public TypeAttributes Attributes => GetAttributeFlagsImpl();
protected abstract TypeAttributes GetAttributeFlagsImpl();
public bool IsAbstract => (GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0;
public bool IsImport => (GetAttributeFlagsImpl() & TypeAttributes.Import) != 0;
public bool IsSealed => (GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0;
public bool IsSpecialName => (GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0;
public bool IsClass => (GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType;
public bool IsNestedAssembly => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly;
public bool IsNestedFamANDAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem;
public bool IsNestedFamily => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily;
public bool IsNestedFamORAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem;
public bool IsNestedPrivate => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate;
public bool IsNestedPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic;
public bool IsNotPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic;
public bool IsPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public;
public bool IsAutoLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout;
public bool IsExplicitLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout;
public bool IsLayoutSequential => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout;
public bool IsAnsiClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass;
public bool IsAutoClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass;
public bool IsUnicodeClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass;
public bool IsCOMObject => IsCOMObjectImpl();
protected abstract bool IsCOMObjectImpl();
public bool IsContextful => IsContextfulImpl();
protected virtual bool IsContextfulImpl() => false;
public virtual bool IsEnum => IsSubclassOf(typeof(Enum));
public bool IsMarshalByRef => IsMarshalByRefImpl();
protected virtual bool IsMarshalByRefImpl() => false;
public bool IsPrimitive => IsPrimitiveImpl();
protected abstract bool IsPrimitiveImpl();
public bool IsValueType => IsValueTypeImpl();
protected virtual bool IsValueTypeImpl() => IsSubclassOf(typeof(ValueType));
public virtual bool IsSecurityCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } }
public virtual StructLayoutAttribute StructLayoutAttribute { get { throw new NotSupportedException(); } }
public ConstructorInfo TypeInitializer => GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, Type.EmptyTypes, null);
public ConstructorInfo GetConstructor(Type[] types) => GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null);
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers);
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
public ConstructorInfo[] GetConstructors() => GetConstructors(BindingFlags.Public | BindingFlags.Instance);
public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
public EventInfo GetEvent(string name) => GetEvent(name, Type.DefaultLookup);
public abstract EventInfo GetEvent(string name, BindingFlags bindingAttr);
public virtual EventInfo[] GetEvents() => GetEvents(Type.DefaultLookup);
public abstract EventInfo[] GetEvents(BindingFlags bindingAttr);
public FieldInfo GetField(string name) => GetField(name, Type.DefaultLookup);
public abstract FieldInfo GetField(string name, BindingFlags bindingAttr);
public FieldInfo[] GetFields() => GetFields(Type.DefaultLookup);
public abstract FieldInfo[] GetFields(BindingFlags bindingAttr);
public MemberInfo[] GetMember(string name) => GetMember(name, Type.DefaultLookup);
public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr) => GetMember(name, MemberTypes.All, bindingAttr);
public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public MemberInfo[] GetMembers() => GetMembers(Type.DefaultLookup);
public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr);
public MethodInfo GetMethod(string name) => GetMethod(name, Type.DefaultLookup);
public MethodInfo GetMethod(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null);
}
public MethodInfo GetMethod(string name, Type[] types) => GetMethod(name, types, null);
public MethodInfo GetMethod(string name, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, Type.DefaultLookup, null, types, modifiers);
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers);
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
public MethodInfo[] GetMethods() => GetMethods(Type.DefaultLookup);
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr);
public Type GetNestedType(string name) => GetNestedType(name, Type.DefaultLookup);
public abstract Type GetNestedType(string name, BindingFlags bindingAttr);
public Type[] GetNestedTypes() => GetNestedTypes(Type.DefaultLookup);
public abstract Type[] GetNestedTypes(BindingFlags bindingAttr);
public PropertyInfo GetProperty(string name) => GetProperty(name, Type.DefaultLookup);
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetPropertyImpl(name, bindingAttr, null, null, null, null);
}
public PropertyInfo GetProperty(string name, Type returnType)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (returnType == null)
throw new ArgumentNullException(nameof(returnType));
return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null);
}
public PropertyInfo GetProperty(string name, Type[] types) => GetProperty(name, null, types);
public PropertyInfo GetProperty(string name, Type returnType, Type[] types) => GetProperty(name, returnType, types, null);
public PropertyInfo GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers);
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers);
}
protected abstract PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers);
public PropertyInfo[] GetProperties() => GetProperties(Type.DefaultLookup);
public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr);
public virtual MemberInfo[] GetDefaultMembers() { throw NotImplemented.ByDesign; }
public virtual RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public static RuntimeTypeHandle GetTypeHandle(object o)
{
if (o == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
Type type = o.GetType();
return type.TypeHandle;
}
public static Type[] GetTypeArray(object[] args)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
Type[] cls = new Type[args.Length];
for (int i = 0; i < cls.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException();
cls[i] = args[i].GetType();
}
return cls;
}
public static TypeCode GetTypeCode(Type type)
{
if (type == null)
return TypeCode.Empty;
return type.GetTypeCodeImpl();
}
protected virtual TypeCode GetTypeCodeImpl()
{
if (this != UnderlyingSystemType && UnderlyingSystemType != null)
return Type.GetTypeCode(UnderlyingSystemType);
return TypeCode.Object;
}
public abstract Guid GUID { get; }
public static Type GetTypeFromCLSID(Guid clsid) => GetTypeFromCLSID(clsid, null, throwOnError: false);
public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError) => GetTypeFromCLSID(clsid, null, throwOnError: throwOnError);
public static Type GetTypeFromCLSID(Guid clsid, string server) => GetTypeFromCLSID(clsid, server, throwOnError: false);
public static Type GetTypeFromProgID(string progID) => GetTypeFromProgID(progID, null, throwOnError: false);
public static Type GetTypeFromProgID(string progID, bool throwOnError) => GetTypeFromProgID(progID, null, throwOnError: throwOnError);
public static Type GetTypeFromProgID(string progID, string server) => GetTypeFromProgID(progID, server, throwOnError: false);
public abstract Type BaseType { get; }
[DebuggerHidden]
[DebuggerStepThrough]
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args) => InvokeMember(name, invokeAttr, binder, target, args, null, null, null);
[DebuggerHidden]
[DebuggerStepThrough]
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture) => InvokeMember(name, invokeAttr, binder, target, args, null, culture, null);
public abstract object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters);
public Type GetInterface(string name) => GetInterface(name, ignoreCase: false);
public abstract Type GetInterface(string name, bool ignoreCase);
public abstract Type[] GetInterfaces();
public virtual InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual bool IsInstanceOfType(object o) => o == null ? false : IsAssignableFrom(o.GetType());
public virtual bool IsEquivalentTo(Type other) => this == other;
public virtual Type GetEnumUnderlyingType()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
FieldInfo[] fields = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (fields == null || fields.Length != 1)
throw new ArgumentException(SR.Argument_InvalidEnum, "enumType");
return fields[0].FieldType;
}
public virtual Array GetEnumValues()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
// We don't support GetEnumValues in the default implementation because we cannot create an array of
// a non-runtime type. If there is strong need we can consider returning an object or int64 array.
throw NotImplemented.ByDesign;
}
public virtual Type MakeArrayType() { throw new NotSupportedException(); }
public virtual Type MakeArrayType(int rank) { throw new NotSupportedException(); }
public virtual Type MakeByRefType() { throw new NotSupportedException(); }
public virtual Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type MakePointerType() { throw new NotSupportedException(); }
public override string ToString() => "Type: " + Name; // Why do we add the "Type: " prefix?
public override bool Equals(object o) => o == null ? false : Equals(o as Type);
public override int GetHashCode()
{
Type systemType = UnderlyingSystemType;
if (!object.ReferenceEquals(systemType, this))
return systemType.GetHashCode();
return base.GetHashCode();
}
public virtual bool Equals(Type o) => o == null ? false : object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType);
public static Type ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public static Binder DefaultBinder
{
get
{
if (s_defaultBinder == null)
{
DefaultBinder binder = new DefaultBinder();
Interlocked.CompareExchange<Binder>(ref s_defaultBinder, binder, null);
}
return s_defaultBinder;
}
}
private static volatile Binder s_defaultBinder;
public static readonly char Delimiter = '.';
public static readonly Type[] EmptyTypes = Array.Empty<Type>();
public static readonly object Missing = System.Reflection.Missing.Value;
public static readonly MemberFilter FilterAttribute = FilterAttributeImpl;
public static readonly MemberFilter FilterName = FilterNameImpl;
public static readonly MemberFilter FilterNameIgnoreCase = FilterNameIgnoreCaseImpl;
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using QuantConnect.Data.Market;
namespace QuantConnect.Data.Consolidators
{
/// <summary>
/// Provides a base class for consolidators that emit data based on the passing of a period of time
/// or after seeing a max count of data points.
/// </summary>
/// <typeparam name="T">The input type of the consolidator</typeparam>
/// <typeparam name="TConsolidated">The output type of the consolidator</typeparam>
public abstract class PeriodCountConsolidatorBase<T, TConsolidated> : DataConsolidator<T>
where T : class, IBaseData
where TConsolidated : BaseData
{
//The minimum timespan between creating new bars.
private readonly TimeSpan? _period;
//The number of data updates between creating new bars.
private readonly int? _maxCount;
//The number of pieces of data we've accumulated since our last emit
private int _currentCount;
//The working bar used for aggregating the data
private TConsolidated _workingBar;
//The last time we emitted a consolidated bar
private DateTime? _lastEmit;
/// <summary>
/// Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the period
/// </summary>
/// <param name="period">The minimum span of time before emitting a consolidated bar</param>
protected PeriodCountConsolidatorBase(TimeSpan period)
{
_period = period;
}
/// <summary>
/// Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the last count pieces of data
/// </summary>
/// <param name="maxCount">The number of pieces to accept before emiting a consolidated bar</param>
protected PeriodCountConsolidatorBase(int maxCount)
{
_maxCount = maxCount;
}
/// <summary>
/// Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the last count pieces of data or the period, whichever comes first
/// </summary>
/// <param name="maxCount">The number of pieces to accept before emiting a consolidated bar</param>
/// <param name="period">The minimum span of time before emitting a consolidated bar</param>
protected PeriodCountConsolidatorBase(int maxCount, TimeSpan period)
{
_maxCount = maxCount;
_period = period;
}
/// <summary>
/// Gets the type produced by this consolidator
/// </summary>
public override Type OutputType
{
get { return typeof(TConsolidated); }
}
/// <summary>
/// Gets a clone of the data being currently consolidated
/// </summary>
public override BaseData WorkingData
{
get { return _workingBar != null ? _workingBar.Clone() : null; }
}
/// <summary>
/// Event handler that fires when a new piece of data is produced. We define this as a 'new'
/// event so we can expose it as a <typeparamref name="TConsolidated"/> instead of a <see cref="BaseData"/> instance
/// </summary>
public new event EventHandler<TConsolidated> DataConsolidated;
/// <summary>
/// Updates this consolidator with the specified data. This method is
/// responsible for raising the DataConsolidated event
/// In time span mode, the bar range is closed on the left and open on the right: [T, T+TimeSpan).
/// For example, if time span is 1 minute, we have [10:00, 10:01): so data at 10:01 is not
/// included in the bar starting at 10:00.
/// </summary>
/// <param name="data">The new data for the consolidator</param>
public override void Update(T data)
{
if (!ShouldProcess(data))
{
// first allow the base class a chance to filter out data it doesn't want
// before we start incrementing counts and what not
return;
}
//Decide to fire the event
var fireDataConsolidated = false;
// decide to aggregate data before or after firing OnDataConsolidated event
// always aggregate before firing in counting mode
bool aggregateBeforeFire = _maxCount.HasValue;
if (_maxCount.HasValue)
{
// we're in count mode
_currentCount++;
if (_currentCount >= _maxCount.Value)
{
_currentCount = 0;
fireDataConsolidated = true;
}
}
if (!_lastEmit.HasValue)
{
// initialize this value for period computations
_lastEmit = data.Time;
}
if (_period.HasValue)
{
// we're in time span mode and initialized
if (_workingBar != null && data.Time - _workingBar.Time >= _period.Value)
{
fireDataConsolidated = true;
}
// special case: always aggregate before event trigger when TimeSpan is zero
if (_period.Value == TimeSpan.Zero)
{
fireDataConsolidated = true;
aggregateBeforeFire = true;
}
}
if (aggregateBeforeFire)
{
AggregateBar(ref _workingBar, data);
}
//Fire the event
if (fireDataConsolidated)
{
var workingTradeBar = _workingBar as TradeBar;
if (workingTradeBar != null)
{
// we kind of are cheating here...
if (_period.HasValue)
{
workingTradeBar.Period = _period.Value;
}
// since trade bar has period it aggregates this properly
else if (!(data is TradeBar))
{
workingTradeBar.Period = data.Time - _lastEmit.Value;
}
}
OnDataConsolidated(_workingBar);
_lastEmit = data.Time;
_workingBar = null;
}
if (!aggregateBeforeFire)
{
AggregateBar(ref _workingBar, data);
}
}
/// <summary>
/// Scans this consolidator to see if it should emit a bar due to time passing
/// </summary>
/// <param name="currentLocalTime">The current time in the local time zone (same as <see cref="BaseData.Time"/>)</param>
public override void Scan(DateTime currentLocalTime)
{
if (_period.HasValue)
{
if (_workingBar != null)
{
var fireDataConsolidated = _period.Value == TimeSpan.Zero;
if (!fireDataConsolidated && currentLocalTime - _workingBar.Time >= _period.Value)
{
fireDataConsolidated = true;
}
if (fireDataConsolidated)
{
OnDataConsolidated(_workingBar);
_lastEmit = currentLocalTime;
_workingBar = null;
}
}
}
}
/// <summary>
/// Determines whether or not the specified data should be processd
/// </summary>
/// <param name="data">The data to check</param>
/// <returns>True if the consolidator should process this data, false otherwise</returns>
protected virtual bool ShouldProcess(T data)
{
return true;
}
/// <summary>
/// Aggregates the new 'data' into the 'workingBar'. The 'workingBar' will be
/// null following the event firing
/// </summary>
/// <param name="workingBar">The bar we're building, null if the event was just fired and we're starting a new consolidated bar</param>
/// <param name="data">The new data</param>
protected abstract void AggregateBar(ref TConsolidated workingBar, T data);
/// <summary>
/// Gets a rounded-down bar time. Called by AggregateBar in derived classes.
/// </summary>
/// <param name="time">The bar time to be rounded down</param>
/// <returns>The rounded bar time</returns>
protected DateTime GetRoundedBarTime(DateTime time)
{
// rounding is performed only in time span mode
return _period.HasValue && !_maxCount.HasValue ? time.RoundDown((TimeSpan)_period) : time;
}
/// <summary>
/// Event invocator for the <see cref="DataConsolidated"/> event
/// </summary>
/// <param name="e">The consolidated data</param>
protected virtual void OnDataConsolidated(TConsolidated e)
{
var handler = DataConsolidated;
if (handler != null) handler(this, e);
base.OnDataConsolidated(e);
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H10_City (editable child object).<br/>
/// This is a generated base class of <see cref="H10_City"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H11_CityRoadObjects"/> of type <see cref="H11_CityRoadColl"/> (1:M relation to <see cref="H12_CityRoad"/>)<br/>
/// This class is an item of <see cref="H09_CityColl"/> collection.
/// </remarks>
[Serializable]
public partial class H10_City : BusinessBase<H10_City>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID");
/// <summary>
/// Gets the Cities ID.
/// </summary>
/// <value>The Cities ID.</value>
public int City_ID
{
get { return GetProperty(City_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="City_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name");
/// <summary>
/// Gets or sets the Cities Name.
/// </summary>
/// <value>The Cities Name.</value>
public string City_Name
{
get { return GetProperty(City_NameProperty); }
set { SetProperty(City_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11_City_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H11_City_Child> H11_City_SingleObjectProperty = RegisterProperty<H11_City_Child>(p => p.H11_City_SingleObject, "H11 City Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 City Single Object ("self load" child property).
/// </summary>
/// <value>The H11 City Single Object.</value>
public H11_City_Child H11_City_SingleObject
{
get { return GetProperty(H11_City_SingleObjectProperty); }
private set { LoadProperty(H11_City_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11_City_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H11_City_ReChild> H11_City_ASingleObjectProperty = RegisterProperty<H11_City_ReChild>(p => p.H11_City_ASingleObject, "H11 City ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 City ASingle Object ("self load" child property).
/// </summary>
/// <value>The H11 City ASingle Object.</value>
public H11_City_ReChild H11_City_ASingleObject
{
get { return GetProperty(H11_City_ASingleObjectProperty); }
private set { LoadProperty(H11_City_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11_CityRoadObjects"/> property.
/// </summary>
public static readonly PropertyInfo<H11_CityRoadColl> H11_CityRoadObjectsProperty = RegisterProperty<H11_CityRoadColl>(p => p.H11_CityRoadObjects, "H11 CityRoad Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 City Road Objects ("self load" child property).
/// </summary>
/// <value>The H11 City Road Objects.</value>
public H11_CityRoadColl H11_CityRoadObjects
{
get { return GetProperty(H11_CityRoadObjectsProperty); }
private set { LoadProperty(H11_CityRoadObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H10_City"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H10_City"/> object.</returns>
internal static H10_City NewH10_City()
{
return DataPortal.CreateChild<H10_City>();
}
/// <summary>
/// Factory method. Loads a <see cref="H10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="H10_City"/> object.</returns>
internal static H10_City GetH10_City(SafeDataReader dr)
{
H10_City obj = new H10_City();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H10_City"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H10_City()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H10_City"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H11_City_SingleObjectProperty, DataPortal.CreateChild<H11_City_Child>());
LoadProperty(H11_City_ASingleObjectProperty, DataPortal.CreateChild<H11_City_ReChild>());
LoadProperty(H11_CityRoadObjectsProperty, DataPortal.CreateChild<H11_CityRoadColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_IDProperty, dr.GetInt32("City_ID"));
LoadProperty(City_NameProperty, dr.GetString("City_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H11_City_SingleObjectProperty, H11_City_Child.GetH11_City_Child(City_ID));
LoadProperty(H11_City_ASingleObjectProperty, H11_City_ReChild.GetH11_City_ReChild(City_ID));
LoadProperty(H11_CityRoadObjectsProperty, H11_CityRoadColl.GetH11_CityRoadColl(City_ID));
}
/// <summary>
/// Inserts a new <see cref="H10_City"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IH10_CityDal>();
using (BypassPropertyChecks)
{
int city_ID = -1;
dal.Insert(
parent.Region_ID,
out city_ID,
City_Name
);
LoadProperty(City_IDProperty, city_ID);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H10_City"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH10_CityDal>();
using (BypassPropertyChecks)
{
dal.Update(
City_ID,
City_Name
);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H10_City"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IH10_CityDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(City_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
namespace System.Reflection.TypeLoading
{
internal static class Helpers
{
public static T[] CloneArray<T>(this T[] original)
{
if (original == null)
return null;
if (original.Length == 0)
return Array.Empty<T>();
// We want to return the exact type of T[] even if "original" is a type of T2[] (due to array variance.)
// The arrays produced by this helper are usually passed directly to app code.
T[] copy = new T[original.Length];
Array.Copy(sourceArray: original, sourceIndex: 0, destinationArray: copy, destinationIndex: 0, length: original.Length);
return copy;
}
public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumeration)
{
// todo: use IEnumerable<T> extension: return new ReadOnlyCollection<T>(enumeration.ToArray());
List<T> list = new List<T>(enumeration);
return new ReadOnlyCollection<T>(list.ToArray());
}
public static int GetTokenRowNumber(this int token) => token & 0x00ffffff;
public static RoMethod FilterInheritedAccessor(this RoMethod accessor)
{
if (accessor.ReflectedType == accessor.DeclaringType)
return accessor;
if (accessor.IsPrivate)
return null;
// If the accessor is virtual, NETFX tries to look for a overriding member starting from ReflectedType - a situation
// which probably isn't expressible in any known language. Detecting overrides veers into vtable-building business which
// is something this library tries to avoid. If anyone ever cares about this, welcome to fix.
return accessor;
}
public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic)
{
if (nonPublic)
return accessor;
if (accessor.IsPublic)
return accessor;
return null;
}
public static string ComputeArraySuffix(int rank, bool multiDim)
{
Debug.Assert(rank == 1 || multiDim);
if (!multiDim)
return "[]";
if (rank == 1)
return "[*]";
return "[" + new string(',', rank - 1) + "]";
}
// Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn.
// Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx
public static string EscapeTypeNameIdentifier(this string identifier)
{
// Some characters in a type name need to be escaped
if (identifier.IndexOfAny(s_charsToEscape) != -1)
{
StringBuilder sbEscapedName = new StringBuilder(identifier.Length);
foreach (char c in identifier)
{
if (c.NeedsEscapingInTypeName())
sbEscapedName.Append('\\');
sbEscapedName.Append(c);
}
identifier = sbEscapedName.ToString();
}
return identifier;
}
public static bool TypeNameContainsTypeParserMetacharacters(this string identifier)
{
return identifier.IndexOfAny(s_charsToEscape) != -1;
}
public static bool NeedsEscapingInTypeName(this char c)
{
return Array.IndexOf(s_charsToEscape, c) >= 0;
}
public static string UnescapeTypeNameIdentifier(this string identifier)
{
if (identifier.IndexOf('\\') != -1)
{
StringBuilder sbUnescapedName = new StringBuilder(identifier.Length);
for (int i = 0; i < identifier.Length; i++)
{
if (identifier[i] == '\\')
{
// If we have a trailing '\\', the framework somehow messed up escaping the original identifier. Since that's
// unlikely to happen and unactionable, we'll just let the next line IndexOutOfRange if that happens.
i++;
}
sbUnescapedName.Append(identifier[i]);
}
identifier = sbUnescapedName.ToString();
}
return identifier;
}
private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' };
/// <summary>
/// For AssemblyReferences, convert "unspecified" components from the ECMA format (0xffff) to the in-memory System.Version format (0xffffffff).
/// </summary>
public static Version AdjustForUnspecifiedVersionComponents(this Version v)
{
int mask =
((v.Revision == ushort.MaxValue) ? 0b0001 : 0) |
((v.Build == ushort.MaxValue) ? 0b0010 : 0) |
((v.Minor == ushort.MaxValue) ? 0b0100 : 0) |
((v.Major == ushort.MaxValue) ? 0b1000 : 0);
return mask switch
{
0b0000 => v,
0b0001 => new Version(v.Major, v.Minor, v.Build),
0b0010 => new Version(v.Major, v.Minor),
0b0011 => new Version(v.Major, v.Minor),
_ => null,
};
}
public static byte[] ComputePublicKeyToken(this byte[] pkt)
{
// @TODO - https://github.com/dotnet/corefxlab/issues/2447 - This is not the best way to compute the PKT as AssemblyName
// throws if the PK isn't a valid PK blob. That's not something we should block a metadata inspection tool for so we
// should compute the PKT ourselves as soon as we can convince the CoreFx analyzers to let us use SHA1.
AssemblyName an = new AssemblyName();
an.SetPublicKey(pkt);
return an.GetPublicKeyToken();
}
public static AssemblyNameFlags ConvertAssemblyFlagsToAssemblyNameFlags(AssemblyFlags assemblyFlags)
{
AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
if ((assemblyFlags & AssemblyFlags.Retargetable) != 0)
{
assemblyNameFlags |= AssemblyNameFlags.Retargetable;
}
return assemblyNameFlags;
}
//
// Note that for a top level type, the resulting ns is string.Empty, *not* null.
// This is a concession to the fact that MetadataReader's fast String equal methods
// don't accept null.
//
public static void SplitTypeName(this string fullName, out string ns, out string name)
{
Debug.Assert(fullName != null);
int indexOfLastDot = fullName.LastIndexOf('.');
if (indexOfLastDot == -1)
{
ns = string.Empty;
name = fullName;
}
else
{
ns = fullName.Substring(0, indexOfLastDot);
name = fullName.Substring(indexOfLastDot + 1);
}
}
//
// Rejoin a namespace and type name back into a full name.
//
// Note that for a top level type, the namespace is string.Empty, *not* null (as Reflection surfaces it.)
// This is a concession to the fact that MetadataReader's fast String equal methods don't accept null.
//
public static string AppendTypeName(this string ns, string name)
{
Debug.Assert(ns != null, "For top level types, the namespace must be string.Empty, not null");
Debug.Assert(name != null);
return ns.Length == 0 ? name : ns + "." + name;
}
//
// Common helper for ConstructorInfo.ToString() and MethodInfo.ToString()
//
public static string ToString(this IRoMethodBase roMethodBase, MethodSig<string> methodSigStrings)
{
TypeContext typeContext = roMethodBase.TypeContext;
StringBuilder sb = new StringBuilder();
sb.Append(methodSigStrings[-1]);
sb.Append(' ');
sb.Append(roMethodBase.MethodBase.Name);
Type[] genericMethodArguments = typeContext.GenericMethodArguments;
int count = genericMethodArguments == null ? 0 : genericMethodArguments.Length;
if (count != 0)
{
sb.Append('[');
for (int gpi = 0; gpi < count; gpi++)
{
if (gpi != 0)
sb.Append(',');
sb.Append(genericMethodArguments[gpi].ToString());
}
sb.Append(']');
}
sb.Append('(');
for (int position = 0; position < methodSigStrings.Parameters.Length; position++)
{
if (position != 0)
sb.Append(", ");
sb.Append(methodSigStrings[position]);
}
sb.Append(')');
return sb.ToString();
}
public static bool HasSameMetadataDefinitionAsCore<M>(this M thisMember, MemberInfo other) where M : MemberInfo
{
if (other == null)
throw new ArgumentNullException(nameof(other));
// Ensure that "other" is one of our MemberInfo objects. Do this check before calling any methods on it!
if (!(other is M))
return false;
if (thisMember.MetadataToken != other.MetadataToken)
return false;
if (!(thisMember.Module.Equals(other.Module)))
return false;
return true;
}
public static RoType LoadTypeFromAssemblyQualifiedName(string name, RoAssembly defaultAssembly, bool ignoreCase, bool throwOnError)
{
if (!name.TypeNameContainsTypeParserMetacharacters())
{
// Fast-path: the type contains none of the parser metacharacters nor the escape character. Just treat as plain old type name.
name.SplitTypeName(out string ns, out string simpleName);
RoType type = defaultAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase, out Exception e);
if (type != null)
return type;
if (throwOnError)
throw e;
}
MetadataLoadContext loader = defaultAssembly.Loader;
Func<AssemblyName, Assembly> assemblyResolver =
delegate (AssemblyName assemblyName)
{
return loader.LoadFromAssemblyName(assemblyName);
};
Func<Assembly, string, bool, Type> typeResolver =
delegate (Assembly assembly, string fullName, bool ignoreCase2)
{
if (assembly == null)
assembly = defaultAssembly;
Debug.Assert(assembly is RoAssembly);
RoAssembly roAssembly = (RoAssembly)assembly;
fullName = fullName.UnescapeTypeNameIdentifier();
fullName.SplitTypeName(out string ns, out string simpleName);
Type type = roAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase2, out Exception e);
if (type != null)
return type;
if (throwOnError)
throw e;
return null;
};
return (RoType)Type.GetType(name, assemblyResolver: assemblyResolver, typeResolver: typeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase);
}
public static Type[] ExtractCustomModifiers(this RoType type, bool isRequired)
{
int count = 0;
RoType walk = type;
while (walk is RoModifiedType roModifiedType)
{
if (roModifiedType.IsRequired == isRequired)
{
count++;
}
walk = roModifiedType.UnmodifiedType;
}
Type[] modifiers = new Type[count];
walk = type;
int index = count;
while (walk is RoModifiedType roModifiedType)
{
if (roModifiedType.IsRequired == isRequired)
{
modifiers[--index] = roModifiedType.Modifier;
}
walk = roModifiedType.UnmodifiedType;
}
Debug.Assert(index == 0);
return modifiers;
}
public static RoType SkipTypeWrappers(this RoType type)
{
while (type is RoWrappedType roWrappedType)
{
type = roWrappedType.UnmodifiedType;
}
return type;
}
public static bool IsVisibleOutsideAssembly(this Type type)
{
TypeAttributes visibility = type.Attributes & TypeAttributes.VisibilityMask;
if (visibility == TypeAttributes.Public)
return true;
if (visibility == TypeAttributes.NestedPublic)
return type.DeclaringType.IsVisibleOutsideAssembly();
return false;
}
//
// Converts an AssemblyName to a RoAssemblyName that is free from any future mutations on the AssemblyName.
//
public static RoAssemblyName ToRoAssemblyName(this AssemblyName assemblyName)
{
if (assemblyName.Name == null)
throw new ArgumentException();
// AssemblyName's PKT property getters do NOT copy the array before giving it out. Make our own copy
// as the original is wide open to tampering by anyone.
byte[] pkt = assemblyName.GetPublicKeyToken().CloneArray();
return new RoAssemblyName(assemblyName.Name, assemblyName.Version, assemblyName.CultureName, pkt, assemblyName.Flags);
}
public static byte[] ToUtf8(this string s) => Encoding.UTF8.GetBytes(s);
public static string ToUtf16(this ReadOnlySpan<byte> utf8) => ToUtf16(utf8.ToArray());
public static string ToUtf16(this byte[] utf8) => Encoding.UTF8.GetString(utf8);
// Guards ToString() implementations. Sample usage:
//
// public sealed override string ToString() => Loader.GetDisposedString() ?? <your real ToString() code>;"
//
public static string GetDisposedString(this MetadataLoadContext loader) => loader.IsDisposed ? SR.MetadataLoadContextDisposed : null;
public static TypeContext ToTypeContext(this RoType[] instantiation) => new TypeContext(instantiation, null);
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// This data type is used as a response element in the <a>DescribeReservedDBInstancesOfferings</a>
/// action.
/// </summary>
public partial class ReservedDBInstancesOffering
{
private string _currencyCode;
private string _dbInstanceClass;
private int? _duration;
private double? _fixedPrice;
private bool? _multiAZ;
private string _offeringType;
private string _productDescription;
private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>();
private string _reservedDBInstancesOfferingId;
private double? _usagePrice;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ReservedDBInstancesOffering() { }
/// <summary>
/// Gets and sets the property CurrencyCode.
/// <para>
/// The currency code for the reserved DB instance offering.
/// </para>
/// </summary>
public string CurrencyCode
{
get { return this._currencyCode; }
set { this._currencyCode = value; }
}
// Check to see if CurrencyCode property is set
internal bool IsSetCurrencyCode()
{
return this._currencyCode != null;
}
/// <summary>
/// Gets and sets the property DBInstanceClass.
/// <para>
/// The DB instance class for the reserved DB instance.
/// </para>
/// </summary>
public string DBInstanceClass
{
get { return this._dbInstanceClass; }
set { this._dbInstanceClass = value; }
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this._dbInstanceClass != null;
}
/// <summary>
/// Gets and sets the property Duration.
/// <para>
/// The duration of the offering in seconds.
/// </para>
/// </summary>
public int Duration
{
get { return this._duration.GetValueOrDefault(); }
set { this._duration = value; }
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this._duration.HasValue;
}
/// <summary>
/// Gets and sets the property FixedPrice.
/// <para>
/// The fixed price charged for this offering.
/// </para>
/// </summary>
public double FixedPrice
{
get { return this._fixedPrice.GetValueOrDefault(); }
set { this._fixedPrice = value; }
}
// Check to see if FixedPrice property is set
internal bool IsSetFixedPrice()
{
return this._fixedPrice.HasValue;
}
/// <summary>
/// Gets and sets the property MultiAZ.
/// <para>
/// Indicates if the offering applies to Multi-AZ deployments.
/// </para>
/// </summary>
public bool MultiAZ
{
get { return this._multiAZ.GetValueOrDefault(); }
set { this._multiAZ = value; }
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this._multiAZ.HasValue;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The offering type.
/// </para>
/// </summary>
public string OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The database engine used by the offering.
/// </para>
/// </summary>
public string ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property RecurringCharges.
/// <para>
/// The recurring price charged to run this reserved DB instance.
/// </para>
/// </summary>
public List<RecurringCharge> RecurringCharges
{
get { return this._recurringCharges; }
set { this._recurringCharges = value; }
}
// Check to see if RecurringCharges property is set
internal bool IsSetRecurringCharges()
{
return this._recurringCharges != null && this._recurringCharges.Count > 0;
}
/// <summary>
/// Gets and sets the property ReservedDBInstancesOfferingId.
/// <para>
/// The offering identifier.
/// </para>
/// </summary>
public string ReservedDBInstancesOfferingId
{
get { return this._reservedDBInstancesOfferingId; }
set { this._reservedDBInstancesOfferingId = value; }
}
// Check to see if ReservedDBInstancesOfferingId property is set
internal bool IsSetReservedDBInstancesOfferingId()
{
return this._reservedDBInstancesOfferingId != null;
}
/// <summary>
/// Gets and sets the property UsagePrice.
/// <para>
/// The hourly price charged for this offering.
/// </para>
/// </summary>
public double UsagePrice
{
get { return this._usagePrice.GetValueOrDefault(); }
set { this._usagePrice = value; }
}
// Check to see if UsagePrice property is set
internal bool IsSetUsagePrice()
{
return this._usagePrice.HasValue;
}
}
}
| |
#region [Copyright (c) 2015 Cristian Alexandru Geambasu]
// Distributed under the terms of an MIT-style license:
//
// The MIT License
//
// Copyright (c) 2015 Cristian Alexandru Geambasu
//
// 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 UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using TeamUtility.IO;
using TeamUtilityEditor.IO.InputManager;
using _InputManager = TeamUtility.IO.InputManager;
namespace TeamUtilityEditor.IO
{
[CustomEditor(typeof(_InputManager))]
public sealed class InputManagerEditor : UnityEditor.Editor
{
private SerializedProperty _intputConfigurations;
private SerializedProperty _dontDestroyOnLoad;
private SerializedProperty _ignoreTimescale;
private SerializedProperty _playerOneDefault;
private SerializedProperty _playerTwoDefault;
private SerializedProperty _playerThreeDefault;
private SerializedProperty _playerFourDefault;
private GUIContent _gravityInfo = new GUIContent("Gravity", "The speed(in units/sec) at which a digital axis falls towards neutral.");
private GUIContent _sensitivityInfo = new GUIContent("Sensitivity", "The speed(in units/sec) at which an axis moves towards the target value.");
private GUIContent _snapInfo = new GUIContent("Snap", "If input switches direction, do we snap to neutral and continue from there? For digital axes only.");
private GUIContent _deadZoneInfo = new GUIContent("Dead Zone", "Size of analog dead zone. Values within this range map to neutral.");
private GUIContent _createSnapshotIngo = new GUIContent("Create\nSnapshot", "Creates a snapshot of your input configurations which can be restored at a later time(when you exit play-mode for example)");
private string[] _axisOptions = new string[] { "X", "Y", "3rd(Scrollwheel)", "4th", "5th", "6th", "7th", "8th", "9th", "10th" };
private string[] _joystickOptions = new string[] { "Joystick 1", "Joystick 2", "Joystick 3", "Joystick 4" };
private string _keyString;
private bool _editingPositiveKey = false;
private bool _editingAltPositiveKey = false;
private bool _editingNegativeKey = false;
private bool _editingAltNegativeKey = false;
private void OnEnable()
{
EditorToolbox.ShowStartupWarning();
_intputConfigurations = serializedObject.FindProperty("inputConfigurations");
_dontDestroyOnLoad = serializedObject.FindProperty("dontDestroyOnLoad");
_ignoreTimescale = serializedObject.FindProperty("ignoreTimescale");
_playerOneDefault = serializedObject.FindProperty("playerOneDefault");
_playerTwoDefault = serializedObject.FindProperty("playerTwoDefault");
_playerThreeDefault = serializedObject.FindProperty("playerThreeDefault");
_playerFourDefault = serializedObject.FindProperty("playerFourDefault");
}
public override void OnInspectorGUI()
{
_InputManager inputManager = target as _InputManager;
serializedObject.Update();
GUILayout.Space(5.0f);
GUILayout.BeginHorizontal();
GUI.enabled = !AdvancedInputEditor.IsOpen;
if(GUILayout.Button("Input\nEditor", GUILayout.Height(40.0f)))
{
AdvancedInputEditor.OpenWindow(inputManager);
}
GUI.enabled = true;
if(GUILayout.Button(_createSnapshotIngo, GUILayout.Height(40.0f)))
{
EditorToolbox.CreateSnapshot(inputManager);
}
GUI.enabled = EditorToolbox.CanLoadSnapshot();
if(GUILayout.Button("Restore\nSnapshot", GUILayout.Height(40.0f)))
{
EditorToolbox.LoadSnapshot(inputManager);
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.Space(5.0f);
EditorGUILayout.PropertyField(_playerOneDefault);
EditorGUILayout.PropertyField(_playerTwoDefault);
EditorGUILayout.PropertyField(_playerThreeDefault);
EditorGUILayout.PropertyField(_playerFourDefault);
EditorGUILayout.PropertyField(_dontDestroyOnLoad);
EditorGUILayout.PropertyField(_ignoreTimescale);
EditorGUILayout.PropertyField(_intputConfigurations);
if(_intputConfigurations.isExpanded)
{
EditorGUI.indentLevel++;
int arraySize = EditorGUILayout.IntField("Size", _intputConfigurations.arraySize);
if(arraySize != _intputConfigurations.arraySize)
{
_intputConfigurations.arraySize = arraySize;
}
for(int i = 0; i < _intputConfigurations.arraySize; i++)
{
DisplayInputConfigurations(_intputConfigurations.GetArrayElementAtIndex(i));
}
EditorGUI.indentLevel--;
}
GUILayout.Space(5.0f);
serializedObject.ApplyModifiedProperties();
}
private void DisplayInputConfigurations(SerializedProperty inputConfig)
{
EditorGUILayout.PropertyField(inputConfig);
if(!inputConfig.isExpanded)
return;
SerializedProperty name = inputConfig.FindPropertyRelative("name");
SerializedProperty axes = inputConfig.FindPropertyRelative("axes");
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(name);
EditorGUILayout.PropertyField(axes);
if(axes.isExpanded)
{
EditorGUI.indentLevel++;
int arraySize = EditorGUILayout.IntField("Size", axes.arraySize);
if(arraySize != axes.arraySize)
{
axes.arraySize = arraySize;
}
for(int i = 0; i < axes.arraySize; i++)
{
DisplayAxisConfiguration(axes.GetArrayElementAtIndex(i));
}
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
private void DisplayAxisConfiguration(SerializedProperty axisConfig)
{
EditorGUILayout.PropertyField(axisConfig);
if(!axisConfig.isExpanded)
return;
SerializedProperty name = axisConfig.FindPropertyRelative("name");
SerializedProperty description = axisConfig.FindPropertyRelative("description");
SerializedProperty positive = axisConfig.FindPropertyRelative("positive");
SerializedProperty altPositive = axisConfig.FindPropertyRelative("altPositive");
SerializedProperty negative = axisConfig.FindPropertyRelative("negative");
SerializedProperty altNegative = axisConfig.FindPropertyRelative("altNegative");
SerializedProperty deadZone = axisConfig.FindPropertyRelative("deadZone");
SerializedProperty gravity = axisConfig.FindPropertyRelative("gravity");
SerializedProperty sensitivity = axisConfig.FindPropertyRelative("sensitivity");
SerializedProperty snap = axisConfig.FindPropertyRelative("snap");
SerializedProperty invert = axisConfig.FindPropertyRelative("invert");
SerializedProperty type = axisConfig.FindPropertyRelative("type");
SerializedProperty axis = axisConfig.FindPropertyRelative("axis");
SerializedProperty joystick = axisConfig.FindPropertyRelative("joystick");
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(name);
EditorGUILayout.PropertyField(description);
// Positive Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingPositiveKey, "Positive",
"inspector_positive_key", PropertyToKeyCode(positive));
ProcessKeyString(ref _editingPositiveKey, positive);
// Negative Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingNegativeKey, "Negative",
"inspector_negative_key", PropertyToKeyCode(negative));
ProcessKeyString(ref _editingNegativeKey, negative);
// Alt Positive Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltPositiveKey, "Alt Positive",
"inspector_alt_positive_key", PropertyToKeyCode(altPositive));
ProcessKeyString(ref _editingAltPositiveKey, altPositive);
// Alt Negative Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltNegativeKey, "Alt Negative",
"inspector_alt_negative_key", PropertyToKeyCode(altNegative));
ProcessKeyString(ref _editingAltNegativeKey, altNegative);
EditorGUILayout.PropertyField(gravity, _gravityInfo);
EditorGUILayout.PropertyField(deadZone, _deadZoneInfo);
EditorGUILayout.PropertyField(sensitivity, _sensitivityInfo);
EditorGUILayout.PropertyField(snap, _snapInfo);
EditorGUILayout.PropertyField(invert);
EditorGUILayout.PropertyField(type);
axis.intValue = EditorGUILayout.Popup("Axis", axis.intValue, _axisOptions);
joystick.intValue = EditorGUILayout.Popup("Joystick", joystick.intValue, _joystickOptions);
EditorGUI.indentLevel--;
}
private KeyCode PropertyToKeyCode(SerializedProperty key)
{
return AxisConfiguration.StringToKey(key.enumNames[key.enumValueIndex]);
}
private void ProcessKeyString(ref bool isEditing, SerializedProperty key)
{
if(isEditing && Event.current.type == EventType.KeyUp)
{
KeyCode keyCode = AxisConfiguration.StringToKey(_keyString);
if(keyCode == KeyCode.None)
{
key.enumValueIndex = 0;
_keyString = string.Empty;
}
else
{
key.enumValueIndex = IndexOfKeyName(key.enumNames, _keyString);
_keyString = keyCode.ToString();
}
}
}
private int IndexOfKeyName(string[] array, string name)
{
for(int i = 0; i < array.Length; i++)
{
if(string.Compare(name, array[i], StringComparison.InvariantCultureIgnoreCase) == 0)
return i;
}
return 0;
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\CameraShake.h:136
namespace UnrealEngine
{
public partial class UCameraShake : UObject
{
public UCameraShake(IntPtr adress)
: base(adress)
{
}
public UCameraShake(UObject Parent = null, string Name = "CameraShake")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UCameraShake(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_AnimBlendInTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_AnimBlendInTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_AnimBlendOutTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_AnimBlendOutTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_PROP_UCameraShake_AnimInst_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_AnimInst_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_AnimPlayRate_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_AnimPlayRate_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_AnimScale_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_AnimScale_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraShake_FOVOscillation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_FOVOscillation_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraShake_LocOscillation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_LocOscillation_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_OscillationBlendInTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_OscillationBlendInTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_OscillationBlendOutTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_OscillationBlendOutTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_OscillationDuration_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_OscillationDuration_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_OscillatorTimeRemaining_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_OscillatorTimeRemaining_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_RandomAnimSegmentDuration_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_RandomAnimSegmentDuration_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraShake_RotOscillation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_RotOscillation_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraShake_ShakeScale_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraShake_ShakeScale_SET(IntPtr Ptr, float Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UCameraShake(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_BlueprintUpdateCameraShake(IntPtr self, float deltaTime, float alpha, IntPtr pOV, IntPtr modifiedPOV);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UCameraShake_IsFinished(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UCameraShake_IsLooping(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UCameraShake_ReceiveIsFinished(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_ReceivePlayShake(IntPtr self, float scale);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_ReceiveStopShake(IntPtr self, bool bImmediately);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_SetCurrentTimeAndApplyShake(IntPtr self, float newTime, IntPtr pOV);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_SetTempCameraAnimActor(IntPtr self, IntPtr actor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_StopShake(IntPtr self, bool bImmediately);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraShake_UpdateAndApplyCameraShake(IntPtr self, float deltaTime, float alpha, IntPtr inOutPOV);
#endregion
#region Property
/// <summary>
/// Linear blend-in time.
/// </summary>
public float AnimBlendInTime
{
get => E_PROP_UCameraShake_AnimBlendInTime_GET(NativePointer);
set => E_PROP_UCameraShake_AnimBlendInTime_SET(NativePointer, value);
}
/// <summary>
/// Linear blend-out time.
/// </summary>
public float AnimBlendOutTime
{
get => E_PROP_UCameraShake_AnimBlendOutTime_GET(NativePointer);
set => E_PROP_UCameraShake_AnimBlendOutTime_SET(NativePointer, value);
}
/// <summary>
/// The playing instance of the CameraAnim-based shake, if any.
/// </summary>
public UCameraAnimInst AnimInst
{
get => E_PROP_UCameraShake_AnimInst_GET(NativePointer);
set => E_PROP_UCameraShake_AnimInst_SET(NativePointer, value);
}
/// <summary>
/// Scalar defining how fast to play the anim.
/// </summary>
public float AnimPlayRate
{
get => E_PROP_UCameraShake_AnimPlayRate_GET(NativePointer);
set => E_PROP_UCameraShake_AnimPlayRate_SET(NativePointer, value);
}
/// <summary>
/// Scalar defining how "intense" to play the anim.
/// </summary>
public float AnimScale
{
get => E_PROP_UCameraShake_AnimScale_GET(NativePointer);
set => E_PROP_UCameraShake_AnimScale_SET(NativePointer, value);
}
/// <summary>
/// FOV oscillation
/// </summary>
public FFOscillator FOVOscillation
{
get => E_PROP_UCameraShake_FOVOscillation_GET(NativePointer);
set => E_PROP_UCameraShake_FOVOscillation_SET(NativePointer, value);
}
/// <summary>
/// Positional oscillation
/// </summary>
public FVOscillator LocOscillation
{
get => E_PROP_UCameraShake_LocOscillation_GET(NativePointer);
set => E_PROP_UCameraShake_LocOscillation_SET(NativePointer, value);
}
/// <summary>
/// Duration of the blend-in, where the oscillation scales from 0 to 1.
/// </summary>
public float OscillationBlendInTime
{
get => E_PROP_UCameraShake_OscillationBlendInTime_GET(NativePointer);
set => E_PROP_UCameraShake_OscillationBlendInTime_SET(NativePointer, value);
}
/// <summary>
/// Duration of the blend-out, where the oscillation scales from 1 to 0.
/// </summary>
public float OscillationBlendOutTime
{
get => E_PROP_UCameraShake_OscillationBlendOutTime_GET(NativePointer);
set => E_PROP_UCameraShake_OscillationBlendOutTime_SET(NativePointer, value);
}
/// <summary>
/// Duration in seconds of current screen shake. Less than 0 means indefinite, 0 means no oscillation.
/// </summary>
public float OscillationDuration
{
get => E_PROP_UCameraShake_OscillationDuration_GET(NativePointer);
set => E_PROP_UCameraShake_OscillationDuration_SET(NativePointer, value);
}
/// <summary>
/// Time remaining for oscillation shakes. Less than 0.f means shake infinitely.
/// </summary>
public float OscillatorTimeRemaining
{
get => E_PROP_UCameraShake_OscillatorTimeRemaining_GET(NativePointer);
set => E_PROP_UCameraShake_OscillatorTimeRemaining_SET(NativePointer, value);
}
/// <summary>
/// When bRandomAnimSegment is true, this defines how long the anim should play.
/// </summary>
public float RandomAnimSegmentDuration
{
get => E_PROP_UCameraShake_RandomAnimSegmentDuration_GET(NativePointer);
set => E_PROP_UCameraShake_RandomAnimSegmentDuration_SET(NativePointer, value);
}
/// <summary>
/// Rotational oscillation
/// </summary>
public FROscillator RotOscillation
{
get => E_PROP_UCameraShake_RotOscillation_GET(NativePointer);
set => E_PROP_UCameraShake_RotOscillation_SET(NativePointer, value);
}
/// <summary>
/// Overall intensity scale for this shake instance.
/// </summary>
public float ShakeScale
{
get => E_PROP_UCameraShake_ShakeScale_GET(NativePointer);
set => E_PROP_UCameraShake_ShakeScale_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Called every tick to let the shake modify the point of view
/// </summary>
public void BlueprintUpdateCameraShake(float deltaTime, float alpha, FMinimalViewInfo pOV, FMinimalViewInfo modifiedPOV)
=> E_UCameraShake_BlueprintUpdateCameraShake(this, deltaTime, alpha, pOV, modifiedPOV);
public virtual bool IsFinished()
=> E_UCameraShake_IsFinished(this);
public bool IsLooping()
=> E_UCameraShake_IsLooping(this);
/// <summary>
/// Called to allow a shake to decide when it's finished playing.
/// </summary>
public bool ReceiveIsFinished()
=> E_UCameraShake_ReceiveIsFinished(this);
/// <summary>
/// Called when the shake starts playing
/// </summary>
public void ReceivePlayShake(float scale)
=> E_UCameraShake_ReceivePlayShake(this, scale);
/// <summary>
/// Called when the shake is explicitly stopped.
/// </summary>
/// <param name="bImmediatly">If true, shake stops right away regardless of blend out settings. If false, shake may blend out according to its settings.</param>
public void ReceiveStopShake(bool bImmediately)
=> E_UCameraShake_ReceiveStopShake(this, bImmediately);
/// <summary>
/// Sets current playback time and applies the shake (both oscillation and cameraanim) to the given POV.
/// </summary>
public void SetCurrentTimeAndApplyShake(float newTime, FMinimalViewInfo pOV)
=> E_UCameraShake_SetCurrentTimeAndApplyShake(this, newTime, pOV);
public void SetTempCameraAnimActor(AActor actor)
=> E_UCameraShake_SetTempCameraAnimActor(this, actor);
/// <summary>
/// Stops this shake from playing.
/// </summary>
/// <param name="bImmediatly">If true, shake stops right away regardless of blend out settings. If false, shake may blend out according to its settings.</param>
public virtual void StopShake(bool bImmediately)
=> E_UCameraShake_StopShake(this, bImmediately);
public virtual void UpdateAndApplyCameraShake(float deltaTime, float alpha, FMinimalViewInfo inOutPOV)
=> E_UCameraShake_UpdateAndApplyCameraShake(this, deltaTime, alpha, inOutPOV);
#endregion
public static implicit operator IntPtr(UCameraShake self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UCameraShake(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UCameraShake>(PtrDesc);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SocketErrors.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.Sockets {
using System;
using System.Net;
/// <devdoc>
/// <para>
/// Defines socket error constants.
/// </para>
/// </devdoc>
public enum SocketError : int {
/// <devdoc>
/// <para>
/// The operation completed succesfully.
/// </para>
/// </devdoc>
Success = 0,
/// <devdoc>
/// <para>
/// The socket has an error.
/// </para>
/// </devdoc>
SocketError = (-1),
/*
* All Windows Sockets error constants are biased by WSABASEERR from
* the "normal"
*/
/// <devdoc>
/// <para>
/// The base value of all socket error constants. All other socket errors are
/// offset from this value.
/// </para>
/// </devdoc>
///WSABASEERR = 10000;
/*
* Windows Sockets definitions of regular Microsoft C error constants
*/
/// <devdoc>
/// <para>
/// A blocking socket call was canceled.
/// </para>
/// </devdoc>
Interrupted = (10000+4), //WSAEINTR
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
//WSAEBADF = (10000+9), //
/// <devdoc>
/// <para>
/// Permission denied.
/// </para>
/// </devdoc>
AccessDenied = (10000+13), //WSAEACCES
/// <devdoc>
/// <para>
/// Bad address.
/// </para>
/// </devdoc>
Fault = (10000+14), //WSAEFAULT
/// <devdoc>
/// <para>
/// Invalid argument.
/// </para>
/// </devdoc>
InvalidArgument = (10000+22), //WSAEINVAL
/// <devdoc>
/// <para>
/// Too many open
/// files.
/// </para>
/// </devdoc>
TooManyOpenSockets = (10000+24), //WSAEMFILE
/*
* Windows Sockets definitions of regular Berkeley error constants
*/
/// <devdoc>
/// <para>
/// Resource temporarily unavailable.
/// </para>
/// </devdoc>
WouldBlock = (10000+35), //WSAEWOULDBLOCK
/// <devdoc>
/// <para>
/// Operation now in progress.
/// </para>
/// </devdoc>
InProgress = (10000+36), // WSAEINPROGRESS
/// <devdoc>
/// <para>
/// Operation already in progress.
/// </para>
/// </devdoc>
AlreadyInProgress = (10000+37), //WSAEALREADY
/// <devdoc>
/// <para>
/// Socket operation on nonsocket.
/// </para>
/// </devdoc>
NotSocket = (10000+38), //WSAENOTSOCK
/// <devdoc>
/// <para>
/// Destination address required.
/// </para>
/// </devdoc>
DestinationAddressRequired = (10000+39), //WSAEDESTADDRREQ
/// <devdoc>
/// <para>
/// Message too long.
/// </para>
/// </devdoc>
MessageSize = (10000+40), //WSAEMSGSIZE
/// <devdoc>
/// <para>
/// Protocol wrong type for socket.
/// </para>
/// </devdoc>
ProtocolType = (10000+41), //WSAEPROTOTYPE
/// <devdoc>
/// <para>
/// Bad protocol option.
/// </para>
/// </devdoc>
ProtocolOption = (10000+42), //WSAENOPROTOOPT
/// <devdoc>
/// <para>
/// Protocol not supported.
/// </para>
/// </devdoc>
ProtocolNotSupported = (10000+43), //WSAEPROTONOSUPPORT
/// <devdoc>
/// <para>
/// Socket type not supported.
/// </para>
/// </devdoc>
SocketNotSupported = (10000+44), //WSAESOCKTNOSUPPORT
/// <devdoc>
/// <para>
/// Operation not supported.
/// </para>
/// </devdoc>
OperationNotSupported = (10000+45), //WSAEOPNOTSUPP
/// <devdoc>
/// <para>
/// Protocol family not supported.
/// </para>
/// </devdoc>
ProtocolFamilyNotSupported = (10000+46), //WSAEPFNOSUPPORT
/// <devdoc>
/// <para>
/// Address family not supported by protocol family.
/// </para>
/// </devdoc>
AddressFamilyNotSupported = (10000+47), //WSAEAFNOSUPPORT
/// <devdoc>
/// Address already in use.
/// </devdoc>
AddressAlreadyInUse = (10000+48), // WSAEADDRINUSE
/// <devdoc>
/// <para>
/// Cannot assign requested address.
/// </para>
/// </devdoc>
AddressNotAvailable = (10000+49), //WSAEADDRNOTAVAIL
/// <devdoc>
/// <para>
/// Network is down.
/// </para>
/// </devdoc>
NetworkDown = (10000+50), //WSAENETDOWN
/// <devdoc>
/// <para>
/// Network is unreachable.
/// </para>
/// </devdoc>
NetworkUnreachable = (10000+51), //WSAENETUNREACH
/// <devdoc>
/// <para>
/// Network dropped connection on reset.
/// </para>
/// </devdoc>
NetworkReset = (10000+52), //WSAENETRESET
/// <devdoc>
/// <para>
/// Software caused connection to abort.
/// </para>
/// </devdoc>
ConnectionAborted = (10000+53), //WSAECONNABORTED
/// <devdoc>
/// <para>
/// Connection reset by peer.
/// </para>
/// </devdoc>
ConnectionReset = (10000+54), //WSAECONNRESET
/// <devdoc>
/// No buffer space available.
/// </devdoc>
NoBufferSpaceAvailable = (10000+55), //WSAENOBUFS
/// <devdoc>
/// <para>
/// Socket is already connected.
/// </para>
/// </devdoc>
IsConnected = (10000+56), //WSAEISCONN
/// <devdoc>
/// <para>
/// Socket is not connected.
/// </para>
/// </devdoc>
NotConnected = (10000+57), //WSAENOTCONN
/// <devdoc>
/// <para>
/// Cannot send after socket shutdown.
/// </para>
/// </devdoc>
Shutdown = (10000+58), //WSAESHUTDOWN
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAETOOMANYREFS = (10000+59), //WSAETOOMANYREFS
/// <devdoc>
/// <para>
/// Connection timed out.
/// </para>
/// </devdoc>
TimedOut = (10000+60), //WSAETIMEDOUT
/// <devdoc>
/// <para>
/// Connection refused.
/// </para>
/// </devdoc>
ConnectionRefused = (10000+61), //WSAECONNREFUSED
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAELOOP = (10000+62),
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAENAMETOOLONG = (10000+63),
/// <devdoc>
/// <para>
/// Host is down.
/// </para>
/// </devdoc>
HostDown = (10000+64), //WSAEHOSTDOWN
/// <devdoc>
/// <para>
/// No route to host.
/// </para>
/// </devdoc>
HostUnreachable = (10000+65), //WSAEHOSTUNREACH
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAENOTEMPTY = (10000+66),
/// <devdoc>
/// <para>
/// Too many processes.
/// </para>
/// </devdoc>
ProcessLimit = (10000+67), //WSAEPROCLIM
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAEUSERS = (10000+68),
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAEDQUOT = (10000+69),
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
// WSAESTALE = (10000+70),
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
/*
* Extended Windows Sockets error constant definitions
*/
/// <devdoc>
/// <para>
/// Network subsystem is unavailable.
/// </para>
/// </devdoc>
SystemNotReady = (10000+91), //WSASYSNOTREADY
/// <devdoc>
/// <para>
/// Winsock.dll out of range.
/// </para>
/// </devdoc>
VersionNotSupported = (10000+92), //WSAVERNOTSUPPORTED
/// <devdoc>
/// <para>
/// Successful startup not yet performed.
/// </para>
/// </devdoc>
NotInitialized = (10000+93), //WSANOTINITIALISED
// WSAEREMOTE = (10000+71),
/// <devdoc>
/// <para>
/// Graceful shutdown in progress.
/// </para>
/// </devdoc>
Disconnecting = (10000+101), //WSAEDISCON
TypeNotFound = (10000+109), //WSATYPE_NOT_FOUND
/*
* Error return codes from gethostbyname() and gethostbyaddr()
* = (when using the resolver). Note that these errors are
* retrieved via WSAGetLastError() and must therefore follow
* the rules for avoiding clashes with error numbers from
* specific implementations or language run-time systems.
* For this reason the codes are based at 10000+1001.
* Note also that [WSA]NO_ADDRESS is defined only for
* compatibility purposes.
*/
/// <devdoc>
/// <para>
/// Host not found (Authoritative Answer: Host not found).
/// </para>
/// </devdoc>
HostNotFound = (10000+1001), //WSAHOST_NOT_FOUND
/// <devdoc>
/// <para>
/// Nonauthoritative host not found (Non-Authoritative: Host not found, or SERVERFAIL).
/// </para>
/// </devdoc>
TryAgain = (10000+1002), //WSATRY_AGAIN
/// <devdoc>
/// <para>
/// This is a nonrecoverable error (Non recoverable errors, FORMERR, REFUSED, NOTIMP).
/// </para>
/// </devdoc>
NoRecovery = (10000+1003), //WSANO_RECOVERY
/// <devdoc>
/// <para>
/// Valid name, no data record of requested type.
/// </para>
/// </devdoc>
NoData = (10000+1004), //WSANO_DATA
//OS dependent errors
/// <devdoc>
/// <para>
/// Overlapped operations will complete later.
/// </para>
/// </devdoc>
IOPending = (int) UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING, // 997
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
OperationAborted = (int) UnsafeNclNativeMethods.ErrorCodes.ERROR_OPERATION_ABORTED, // 995, WSA_OPERATION_ABORTED
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Authentication;
namespace System.DirectoryServices.ActiveDirectory
{
public class SyncFromAllServersErrorInformation
{
internal SyncFromAllServersErrorInformation(SyncFromAllServersErrorCategory category, int errorCode, string errorMessage, string sourceServer, string targetServer)
{
ErrorCategory = category;
ErrorCode = errorCode;
ErrorMessage = errorMessage;
SourceServer = sourceServer;
TargetServer = targetServer;
}
public SyncFromAllServersErrorCategory ErrorCategory { get; }
public int ErrorCode { get; }
public string ErrorMessage { get; }
public string TargetServer { get; }
public string SourceServer { get; }
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ActiveDirectoryObjectNotFoundException : Exception, ISerializable
{
public ActiveDirectoryObjectNotFoundException(string message, Type type, string name) : base(message)
{
Type = type;
Name = name;
}
public ActiveDirectoryObjectNotFoundException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryObjectNotFoundException(string message) : base(message) { }
public ActiveDirectoryObjectNotFoundException() : base() { }
protected ActiveDirectoryObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public Type Type { get; }
public string Name { get; }
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ActiveDirectoryOperationException : Exception, ISerializable
{
public ActiveDirectoryOperationException(string message, Exception inner, int errorCode) : base(message, inner)
{
ErrorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, int errorCode) : base(message)
{
ErrorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryOperationException(string message) : base(message) { }
public ActiveDirectoryOperationException() : base(SR.DSUnknownFailure) { }
protected ActiveDirectoryOperationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public int ErrorCode { get; }
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ActiveDirectoryServerDownException : Exception, ISerializable
{
public ActiveDirectoryServerDownException(string message, Exception inner, int errorCode, string name) : base(message, inner)
{
ErrorCode = errorCode;
Name = name;
}
public ActiveDirectoryServerDownException(string message, int errorCode, string name) : base(message)
{
ErrorCode = errorCode;
Name = name;
}
public ActiveDirectoryServerDownException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryServerDownException(string message) : base(message) { }
public ActiveDirectoryServerDownException() : base() { }
protected ActiveDirectoryServerDownException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public int ErrorCode { get; }
public string Name { get; }
public override string Message
{
get
{
string s = base.Message;
if (!((Name == null) ||
(Name.Length == 0)))
return s + Environment.NewLine + SR.Format(SR.Name, Name) + Environment.NewLine;
else
return s;
}
}
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ActiveDirectoryObjectExistsException : Exception
{
public ActiveDirectoryObjectExistsException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryObjectExistsException(string message) : base(message) { }
public ActiveDirectoryObjectExistsException() : base() { }
protected ActiveDirectoryObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class SyncFromAllServersOperationException : ActiveDirectoryOperationException, ISerializable
{
private readonly SyncFromAllServersErrorInformation[] _errors = null;
public SyncFromAllServersOperationException(string message, Exception inner, SyncFromAllServersErrorInformation[] errors) : base(message, inner)
{
_errors = errors;
}
public SyncFromAllServersOperationException(string message, Exception inner) : base(message, inner) { }
public SyncFromAllServersOperationException(string message) : base(message) { }
public SyncFromAllServersOperationException() : base(SR.DSSyncAllFailure) { }
protected SyncFromAllServersOperationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public SyncFromAllServersErrorInformation[] ErrorInformation
{
get
{
if (_errors == null)
return Array.Empty<SyncFromAllServersErrorInformation>();
SyncFromAllServersErrorInformation[] tempError = new SyncFromAllServersErrorInformation[_errors.Length];
for (int i = 0; i < _errors.Length; i++)
tempError[i] = new SyncFromAllServersErrorInformation(_errors[i].ErrorCategory, _errors[i].ErrorCode, _errors[i].ErrorMessage, _errors[i].SourceServer, _errors[i].TargetServer);
return tempError;
}
}
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ForestTrustCollisionException : ActiveDirectoryOperationException, ISerializable
{
public ForestTrustCollisionException(string message, Exception inner, ForestTrustRelationshipCollisionCollection collisions) : base(message, inner)
{
Collisions = collisions;
}
public ForestTrustCollisionException(string message, Exception inner) : base(message, inner) { }
public ForestTrustCollisionException(string message) : base(message) { }
public ForestTrustCollisionException() : base(SR.ForestTrustCollision) { }
protected ForestTrustCollisionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public ForestTrustRelationshipCollisionCollection Collisions { get; } = new ForestTrustRelationshipCollisionCollection();
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
internal class ExceptionHelper
{
private const int ERROR_NOT_ENOUGH_MEMORY = 8; // map to outofmemory exception
private const int ERROR_OUTOFMEMORY = 14; // map to outofmemory exception
private const int ERROR_DS_DRA_OUT_OF_MEM = 8446; // map to outofmemory exception
private const int ERROR_NO_SUCH_DOMAIN = 1355; // map to ActiveDirectoryServerDownException
private const int ERROR_ACCESS_DENIED = 5; // map to UnauthorizedAccessException
private const int ERROR_NO_LOGON_SERVERS = 1311; // map to ActiveDirectoryServerDownException
private const int ERROR_DS_DRA_ACCESS_DENIED = 8453; // map to UnauthorizedAccessException
private const int RPC_S_OUT_OF_RESOURCES = 1721; // map to outofmemory exception
internal const int RPC_S_SERVER_UNAVAILABLE = 1722; // map to ActiveDirectoryServerDownException
internal const int RPC_S_CALL_FAILED = 1726; // map to ActiveDirectoryServerDownException
private const int ERROR_CANCELLED = 1223;
internal const int ERROR_DS_DRA_BAD_DN = 8439;
internal const int ERROR_DS_NAME_UNPARSEABLE = 8350;
internal const int ERROR_DS_UNKNOWN_ERROR = 8431;
//
// This method maps some common COM Hresults to
// existing clr exceptions
//
internal static Exception GetExceptionFromCOMException(COMException e)
{
return GetExceptionFromCOMException(null, e);
}
internal static Exception GetExceptionFromCOMException(DirectoryContext context, 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)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)0x80071392))
{
//
// Object already exists
//
exception = new ActiveDirectoryObjectExistsException(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)))
{
//
// ServerDown/Unavailable/Busy
//
if (context != null)
{
exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, context.GetServerName());
}
else
{
exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, null);
}
}
else
{
//
// Wrap the exception in a generic OperationException
//
exception = new ActiveDirectoryOperationException(errorMessage, e, errorCode);
}
return exception;
}
internal static Exception GetExceptionFromErrorCode(int errorCode)
{
return GetExceptionFromErrorCode(errorCode, null);
}
internal static Exception GetExceptionFromErrorCode(int errorCode, string targetName)
{
string errorMsg = GetErrorMessage(errorCode, false);
if ((errorCode == ERROR_ACCESS_DENIED) || (errorCode == ERROR_DS_DRA_ACCESS_DENIED))
return new UnauthorizedAccessException(errorMsg);
else if ((errorCode == ERROR_NOT_ENOUGH_MEMORY) || (errorCode == ERROR_OUTOFMEMORY) || (errorCode == ERROR_DS_DRA_OUT_OF_MEM) || (errorCode == RPC_S_OUT_OF_RESOURCES))
return new OutOfMemoryException();
else if ((errorCode == ERROR_NO_LOGON_SERVERS) || (errorCode == ERROR_NO_SUCH_DOMAIN) || (errorCode == RPC_S_SERVER_UNAVAILABLE) || (errorCode == RPC_S_CALL_FAILED))
return new ActiveDirectoryServerDownException(errorMsg, errorCode, targetName);
else
return new ActiveDirectoryOperationException(errorMsg, errorCode);
}
internal static string GetErrorMessage(int errorCode, bool hresult)
{
uint temp = (uint)errorCode;
if (!hresult)
{
temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000));
}
return new Win32Exception((int)temp).Message;
}
internal static SyncFromAllServersOperationException CreateSyncAllException(IntPtr errorInfo, bool singleError)
{
if (errorInfo == (IntPtr)0)
return new SyncFromAllServersOperationException();
if (singleError)
{
// single error
DS_REPSYNCALL_ERRINFO error = new DS_REPSYNCALL_ERRINFO();
Marshal.PtrToStructure(errorInfo, error);
string message = GetErrorMessage(error.dwWin32Err, false);
string source = Marshal.PtrToStringUni(error.pszSrcId);
string target = Marshal.PtrToStringUni(error.pszSvrId);
if (error.dwWin32Err == ERROR_CANCELLED)
{
// this is a special case. the failure is because user specifies SyncAllOptions.CheckServerAlivenessOnly, ignore it here
return null;
}
else
{
SyncFromAllServersErrorInformation managedError = new SyncFromAllServersErrorInformation(error.error, error.dwWin32Err, message, source, target);
return new SyncFromAllServersOperationException(SR.DSSyncAllFailure, null, new SyncFromAllServersErrorInformation[] { managedError });
}
}
else
{
// it is a NULL terminated array of DS_REPSYNCALL_ERRINFO
IntPtr tempPtr = Marshal.ReadIntPtr(errorInfo);
ArrayList errorList = new ArrayList();
int i = 0;
while (tempPtr != (IntPtr)0)
{
DS_REPSYNCALL_ERRINFO error = new DS_REPSYNCALL_ERRINFO();
Marshal.PtrToStructure(tempPtr, error);
// this is a special case. the failure is because user specifies SyncAllOptions.CheckServerAlivenessOnly, ignore it here
if (error.dwWin32Err != ERROR_CANCELLED)
{
string message = GetErrorMessage(error.dwWin32Err, false);
string source = Marshal.PtrToStringUni(error.pszSrcId);
string target = Marshal.PtrToStringUni(error.pszSvrId);
SyncFromAllServersErrorInformation managedError = new SyncFromAllServersErrorInformation(error.error, error.dwWin32Err, message, source, target);
errorList.Add(managedError);
}
i++;
tempPtr = Marshal.ReadIntPtr(errorInfo, i * IntPtr.Size);
}
// no error information, so we should not throw exception.
if (errorList.Count == 0)
return null;
SyncFromAllServersErrorInformation[] info = new SyncFromAllServersErrorInformation[errorList.Count];
for (int j = 0; j < errorList.Count; j++)
{
SyncFromAllServersErrorInformation tmp = (SyncFromAllServersErrorInformation)errorList[j];
info[j] = new SyncFromAllServersErrorInformation(tmp.ErrorCategory, tmp.ErrorCode, tmp.ErrorMessage, tmp.SourceServer, tmp.TargetServer);
}
return new SyncFromAllServersOperationException(SR.DSSyncAllFailure, null, info);
}
}
internal static Exception CreateForestTrustCollisionException(IntPtr collisionInfo)
{
ForestTrustRelationshipCollisionCollection collection = new ForestTrustRelationshipCollisionCollection();
LSA_FOREST_TRUST_COLLISION_INFORMATION collision = new LSA_FOREST_TRUST_COLLISION_INFORMATION();
Marshal.PtrToStructure(collisionInfo, collision);
int count = collision.RecordCount;
IntPtr addr = (IntPtr)0;
for (int i = 0; i < count; i++)
{
addr = Marshal.ReadIntPtr(collision.Entries, i * IntPtr.Size);
LSA_FOREST_TRUST_COLLISION_RECORD record = new LSA_FOREST_TRUST_COLLISION_RECORD();
Marshal.PtrToStructure(addr, record);
ForestTrustCollisionType type = record.Type;
string recordName = Marshal.PtrToStringUni(record.Name.Buffer, record.Name.Length / 2);
TopLevelNameCollisionOptions TLNFlag = TopLevelNameCollisionOptions.None;
DomainCollisionOptions domainFlag = DomainCollisionOptions.None;
if (type == ForestTrustCollisionType.TopLevelName)
{
TLNFlag = (TopLevelNameCollisionOptions)record.Flags;
}
else if (type == ForestTrustCollisionType.Domain)
{
domainFlag = (DomainCollisionOptions)record.Flags;
}
ForestTrustRelationshipCollision tmp = new ForestTrustRelationshipCollision(type, TLNFlag, domainFlag, recordName);
collection.Add(tmp);
}
ForestTrustCollisionException exception = new ForestTrustCollisionException(SR.ForestTrustCollision, null, collection);
return exception;
}
}
}
| |
using GildedRose.Console;
using System.Collections.Generic;
using Xunit;
using System;
namespace GildedRose.Tests
{
public class TestAssemblyTests
{
private ItemManager itemManager;
private IList<Item> items;
[Fact]
public void BackStageQualityAtZeroSellInTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(15);
Then_Backstage_Passes_Quality_Is_Zero();
}
[Fact]
public void ConjuringItemQualityZeroTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(3);
Then_Conjuring_Items_Are_Zero();
}
[Fact]
public void ConjuringItemQualityFourTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(1);
Then_Conjuring_Items_Are_Four();
}
private void Then_Conjuring_Items_Are_Four()
{
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(2, items[5].SellIn);
Assert.Equal(4, items[5].Quality);
}
private void Then_Conjuring_Items_Are_Zero()
{
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(0, items[5].SellIn);
Assert.Equal(0, items[5].Quality);
}
private void When_Items_Are_Updated_N_Times(int n)
{
for (int i = 0; i < n; i++)
{
itemManager.UpdateQuality();
}
}
[Fact]
public void BackStageQualityAboveTenSellInTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(5);
Then_Backstage_Passes_Quality_Is_25();
}
private void Then_Backstage_Passes_Quality_Is_25()
{
Assert.Equal(25, items[4].Quality);
}
[Fact]
public void BackStageQualityBelowTenSellInTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(6);
Then_Backstage_Passes_Quality_Is_27();
}
private void Then_Backstage_Passes_Quality_Is_27()
{
Assert.Equal(27, items[4].Quality);
}
[Fact]
public void BackStageQualityBelowFiveSellInTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(11);
Then_Backstage_Passes_Quality_Is_38();
}
private void Then_Backstage_Passes_Quality_Is_38()
{
Assert.Equal(38, items[4].Quality);
}
private void Then_Backstage_Passes_Quality_Is_Zero()
{
Assert.Equal(0, items[5].Quality);
}
[Fact]
public void UpdateQualityOnceTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
Then_Items_Have_Valid_Initial_Values();
When_Items_Are_Updated_N_Times(1);
Then_Items_Are_Valid_After_One_Update();
}
[Fact]
public void UpdateQualityTwentyTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
Then_Items_Have_Valid_Initial_Values();
When_Items_Are_Updated_N_Times(20);
Then_Items_Are_Valid_After_Twenty_Updates();
}
private void Then_Items_Are_Valid_After_Twenty_Updates()
{
Assert.Equal("+5 Dexterity Vest", items[0].Name);
Assert.Equal(0, items[0].Quality);
Assert.Equal(-10, items[0].SellIn);
Assert.Equal("Aged Brie", items[1].Name);
Assert.Equal(38, items[1].Quality);
Assert.Equal(-18, items[1].SellIn);
Assert.Equal("Elixir of the Mongoose", items[2].Name);
Assert.Equal(0, items[2].Quality);
Assert.Equal(-15, items[2].SellIn);
Assert.Equal("Sulfuras, Hand of Ragnaros", items[3].Name);
Assert.Equal(80, items[3].Quality);
Assert.Equal(0, items[3].SellIn);
Assert.Equal("Backstage passes to a TAFKAL80ETC concert", items[4].Name);
Assert.Equal(0, items[4].Quality);
Assert.Equal(-5, items[4].SellIn);
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(0, items[5].Quality);
Assert.Equal(-17, items[5].SellIn);
}
[Fact]
public void QualityDegradeTwiceAsFastTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(6);
Then_Item_Elixir_Quality_Is_Zero();
}
[Fact]
public void QualityBelowZeroTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(21);
Then_All_Items_Qualities_Are_Non_Negative();
}
[Fact]
public void AgedBrieQualityMaxTest()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(30);
Then_Aged_Brie_Is_Max_Quality_50();
}
[Fact]
public void Test_BackStage_Passes_Are_Max_Quality_50()
{
Given_A_Clone_Of_ItemManager();
Given_A_List_Of_Items();
When_Items_Are_Updated_N_Times(15);
Then_Backstage_Passes_Quality_Is_50();
}
private void Then_Backstage_Passes_Quality_Is_50()
{
Assert.Equal("Backstage passes to a TAFKAL80ETC concert", items[4].Name);
Assert.Equal(50, items[4].Quality);
Assert.Equal(0, items[4].SellIn);
}
private void Then_Aged_Brie_Is_Max_Quality_50()
{
//Initial condition for item +5 Aged Brie.
Assert.Equal("Aged Brie", items[1].Name);
Assert.Equal(50, items[1].Quality);
Assert.Equal(-28, items[1].SellIn);
}
private void Then_All_Items_Qualities_Are_Non_Negative()
{
//Initial condition for item +5 Dexterity Vest.
Assert.Equal("+5 Dexterity Vest", items[0].Name);
Assert.Equal(0, items[0].Quality);
Assert.Equal(-11, items[0].SellIn);
//Initial condition for item +5 Aged Brie.
Assert.Equal("Aged Brie", items[1].Name);
Assert.Equal(40, items[1].Quality);
Assert.Equal(-19, items[1].SellIn);
////Initial condition for item Elixir of the Mongoose.
Assert.Equal("Elixir of the Mongoose", items[2].Name);
Assert.Equal(0, items[2].Quality);
Assert.Equal(-16, items[2].SellIn);
////Initial condition for item Sulfuras, Hand of Ragnaros.
Assert.Equal("Sulfuras, Hand of Ragnaros", items[3].Name);
Assert.Equal(80, items[3].Quality);
Assert.Equal(0, items[3].SellIn);
////Initial condition for item Backstage passes to a TAFKAL80ETC concert.
Assert.Equal("Backstage passes to a TAFKAL80ETC concert", items[4].Name);
Assert.Equal(0, items[4].Quality);
Assert.Equal(-6, items[4].SellIn);
////Initial condition for item Conjured Mana Cake.
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(0, items[5].Quality);
Assert.Equal(-18, items[5].SellIn);
}
private void Then_Item_Elixir_Quality_Is_Zero()
{
Assert.Equal(0, items[2].Quality);
Assert.Equal(-1, items[2].SellIn);
}
private void Then_Items_Are_Valid_After_One_Update()
{
// After update.
Assert.Equal("+5 Dexterity Vest", items[0].Name);
Assert.Equal(19, items[0].Quality);
Assert.Equal(9, items[0].SellIn);
Assert.Equal("Aged Brie", items[1].Name);
Assert.Equal(1, items[1].Quality);
Assert.Equal(1, items[1].SellIn);
Assert.Equal("Elixir of the Mongoose", items[2].Name);
Assert.Equal(6, items[2].Quality);
Assert.Equal(4, items[2].SellIn);
Assert.Equal("Sulfuras, Hand of Ragnaros", items[3].Name);
Assert.Equal(80, items[3].Quality);
Assert.Equal(0, items[3].SellIn);
Assert.Equal("Backstage passes to a TAFKAL80ETC concert", items[4].Name);
Assert.Equal(21, items[4].Quality);
Assert.Equal(14, items[4].SellIn);
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(4, items[5].Quality);
Assert.Equal(2, items[5].SellIn);
}
private void Then_Items_Have_Valid_Initial_Values()
{
//Initial condition for item +5 Dexterity Vest.
Assert.Equal("+5 Dexterity Vest", items[0].Name);
Assert.Equal(20, items[0].Quality);
Assert.Equal(10, items[0].SellIn);
//Initial condition for item +5 Aged Brie.
Assert.Equal("Aged Brie", items[1].Name);
Assert.Equal(0, items[1].Quality);
Assert.Equal(2, items[1].SellIn);
//Initial condition for item Elixir of the Mongoose.
Assert.Equal("Elixir of the Mongoose", items[2].Name);
Assert.Equal(7, items[2].Quality);
Assert.Equal(5, items[2].SellIn);
//Initial condition for item Sulfuras, Hand of Ragnaros.
Assert.Equal("Sulfuras, Hand of Ragnaros", items[3].Name);
Assert.Equal(80, items[3].Quality);
Assert.Equal(0, items[3].SellIn);
//Initial condition for item Sulfuras, Hand of Ragnaros.
Assert.Equal("Backstage passes to a TAFKAL80ETC concert", items[4].Name);
Assert.Equal(20, items[4].Quality);
Assert.Equal(15, items[4].SellIn);
//Initial condition for item Conjured Mana Cake.
Assert.Equal("Conjured Mana Cake", items[5].Name);
Assert.Equal(6, items[5].Quality);
Assert.Equal(3, items[5].SellIn);
}
private void Given_A_Clone_Of_ItemManager()
{
itemManager = new ItemManager();
}
private void Given_A_List_Of_Items()
{
items = itemManager.GetItems();
}
}
}
| |
using RawNet.Format.Tiff;
using System;
using System.Collections.Generic;
namespace RawNet.Dng
{
class DngOpcode
{
public DngOpcode() { }
/* Will be called exactly once, when input changes */
/* Can be used for preparing pre-calculated values, etc */
public virtual RawImage<ushort> CreateOutput(RawImage<ushort> input) { return input; }
/* Will be called for actual processing */
/* If multiThreaded is true, it will be called several times, */
/* otherwise only once */
/* Properties of out will not have changed from createOutput */
public virtual void Apply(RawImage<ushort> input, ref RawImage<ushort> output, UInt32 startY, UInt32 endY) { }
public Rectangle2D aoi = new Rectangle2D();
public int flags;
public enum Flags
{
MultiThreaded = 1,
PureLookup = 2
};
};
class DngOpcodes
{
List<DngOpcode> opcodes = new List<DngOpcode>();
static UInt32 GetULong(byte[] ptr)
{
return (UInt32)ptr[1] << 24 | (UInt32)ptr[2] << 16 | (UInt32)ptr[3] << 8 | ptr[4];
//return (UInt32)ptr[0] << 24 | (UInt32)ptr[1] << 16 | (UInt32)ptr[2] << 8 | (UInt32)ptr[3];
}
unsafe public DngOpcodes(Tag entry)
{
using (TiffBinaryReaderBigEndian reader = new TiffBinaryReaderBigEndian(entry.GetByteArray()))
{
UInt32 entry_size = entry.dataCount;
if (entry_size < 20)
throw new RawDecoderException("Not enough bytes to read a single opcode");
UInt32 opcode_count = reader.ReadUInt32();
uint bytes_used = 4;
for (UInt32 i = 0; i < opcode_count; i++)
{
//if ((int)entry_size - bytes_used < 16)
// throw new RawDecoderException("DngOpcodes: Not enough bytes to read a new opcode");
reader.BaseStream.Position = bytes_used;
UInt32 code = reader.ReadUInt32();
reader.ReadUInt32();
reader.ReadUInt32();
UInt32 expected_size = reader.ReadUInt32();
bytes_used += 16;
int opcode_used = 0;
switch (code)
{
/*
case 4:
mOpcodes.Add(new OpcodeFixBadPixelsConstant(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;
case 5:
mOpcodes.Add(new OpcodeFixBadPixelsList(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;*/
case 6:
opcodes.Add(new OpcodeTrimBounds(reader, entry_size - bytes_used, ref opcode_used));
break;
case 7:
opcodes.Add(new OpcodeMapTable(reader, entry_size - bytes_used, ref opcode_used, bytes_used));
break;
case 8:
opcodes.Add(new OpcodeMapPolynomial(reader, entry_size - bytes_used, ref opcode_used, bytes_used));
break;
case 9:
opcodes.Add(new OpcodeGainMap(reader, entry_size - bytes_used, ref opcode_used, bytes_used));
break;
/*
case 10:
mOpcodes.Add(new OpcodeDeltaPerRow(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;
case 11:
mOpcodes.Add(new OpcodeDeltaPerCol(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;
case 12:
mOpcodes.Add(new OpcodeScalePerRow(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;
case 13:
mOpcodes.Add(new OpcodeScalePerCol(&data[bytes_used], entry_size - bytes_used, &opcode_used));
break;*/
default:
// Throw Error if not marked as optional
/*if ((flags & 1) == 0)
throw new RawDecoderException("DngOpcodes: Unsupported Opcode: " + code);*/
break;
}
//if (opcode_used != expected_size)
//throw new RawDecoderException("DngOpcodes: Inconsistent length of opcode");
bytes_used += (uint)opcode_used;
}
}
}
public RawImage<ushort> ApplyOpCodes(RawImage<ushort> img)
{
int codes = opcodes.Count;
for (int i = 0; i < codes; i++)
{
RawImage<ushort> img_out = opcodes[i].CreateOutput(img);
Rectangle2D fullImage = new Rectangle2D(0, 0, img.raw.dim.Width, img.raw.dim.Height);
if (!opcodes[i].aoi.IsThisInside(fullImage))
throw new RawDecoderException("Area of interest not inside image!");
if (opcodes[i].aoi.HasPositiveArea())
{
opcodes[i].Apply(img, ref img_out, opcodes[i].aoi.Top, opcodes[i].aoi.Bottom);
img = img_out;
}
}
return img;
}
}
/*
public class OpcodeFixBadPixelsConstant : DngOpcode
{
virtual RawImage<ushort> createOutput(RawImage<ushort> input);
virtual void apply(RawImage<ushort> input, RawImage<ushort> output, UInt32 startY, UInt32 endY);
public int mValue;
};
class OpcodeFixBadPixelsList : DngOpcode
{
public:
OpcodeFixBadPixelsList(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used);
virtual ~OpcodeFixBadPixelsList(void) {};
virtual void apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY);
private:
vector<UInt32> bad_pos;
};
*/
class OpcodeTrimBounds : DngOpcode
{
UInt64 mTop, mLeft, mBottom, mRight;
/***************** OpcodeTrimBounds ****************/
public OpcodeTrimBounds(TiffBinaryReader parameters, UInt32 param_max_bytes, ref Int32 bytes_used)
{
if (param_max_bytes < 16)
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
mTop = parameters.ReadUInt16();
mLeft = parameters.ReadUInt16();
mBottom = parameters.ReadUInt16();
mRight = parameters.ReadUInt16();
bytes_used = 16;
}
public override void Apply(RawImage<ushort> input, ref RawImage<ushort> output, UInt32 startY, UInt32 endY)
{
Rectangle2D crop = new Rectangle2D((uint)mLeft, (uint)mTop, (uint)(mRight - mLeft), (uint)(mBottom - mTop));
output.raw.offset = crop.TopLeft;
output.raw.dim = crop.BottomRight;
}
};
class OpcodeMapTable : DngOpcode
{
UInt64 firstPlane, planes, rowPitch, colPitch;
UInt16[] Lookup = new UInt16[65536];
/***************** OpcodeMapTable ****************/
public OpcodeMapTable(TiffBinaryReader parameters, ulong param_max_bytes, ref Int32 bytes_used, uint offset)
{
if (param_max_bytes < 36)
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
uint h1 = parameters.ReadUInt32();
uint w1 = parameters.ReadUInt32();
uint h2 = parameters.ReadUInt32();
uint w2 = parameters.ReadUInt32();
aoi.SetAbsolute(w1, h1, w2, h2);
firstPlane = parameters.ReadUInt32();
planes = parameters.ReadUInt32();
rowPitch = parameters.ReadUInt32();
colPitch = parameters.ReadUInt32();
if (planes == 0)
throw new RawDecoderException("Zero planes");
if (rowPitch == 0 || colPitch == 0)
throw new RawDecoderException("Invalid Pitch");
int tablesize = (int)parameters.ReadUInt32();
bytes_used = 36;
if (tablesize <= 0)
throw new RawDecoderException("Table size must be positive");
if (tablesize > 65536)
throw new RawDecoderException("A map with more than 65536 entries not allowed");
if (param_max_bytes < 36 + ((UInt64)tablesize * 2))
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
for (int i = 0; i <= 65535; i++)
{
int location = Math.Min(tablesize - 1, i);
parameters.BaseStream.Position = 36 + 2 * location + offset;
Lookup[i] = parameters.ReadUInt16();
}
bytes_used += tablesize * 2;
flags = (int)Flags.MultiThreaded | (int)Flags.PureLookup;
}
public override RawImage<ushort> CreateOutput(RawImage<ushort> input)
{
if (firstPlane > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
if (firstPlane + planes > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
return input;
}
public unsafe override void Apply(RawImage<ushort> input, ref RawImage<ushort> output, UInt32 startY, UInt32 endY)
{
for (UInt64 y = startY; y < endY; y += rowPitch)
{
fixed (UInt16* t = &output.raw.rawView[(int)y * output.raw.dim.Width + aoi.Left])
{
var src = t;
// Add offset, so this is always first plane
src += firstPlane;
for (ulong x = 0; x < aoi.Width; x += colPitch)
{
for (uint p = 0; p < planes; p++)
{
src[x * output.raw.cpp + p] = Lookup[src[x * output.raw.cpp + p]];
}
}
}
}
}
}
class OpcodeMapPolynomial : DngOpcode
{
UInt64 mFirstPlane, mPlanes, mRowPitch, mColPitch, mDegree;
double[] mCoefficient = new double[9];
UInt16[] mLookup = new UInt16[65536];
public OpcodeMapPolynomial(TiffBinaryReader parameters, UInt32 param_max_bytes, ref int bytes_used, uint offset)
{
if (param_max_bytes < 36)
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
uint h1 = parameters.ReadUInt32();
uint w1 = parameters.ReadUInt32();
uint h2 = parameters.ReadUInt32();
uint w2 = parameters.ReadUInt32();
aoi.SetAbsolute(w1, h1, w2, h2);
mFirstPlane = parameters.ReadUInt32();
mPlanes = parameters.ReadUInt32();
mRowPitch = parameters.ReadUInt32();
mColPitch = parameters.ReadUInt32();
if (mPlanes == 0)
throw new RawDecoderException("Zero planes");
if (mRowPitch == 0 || mColPitch == 0)
throw new RawDecoderException("Invalid Pitch");
mDegree = parameters.ReadUInt32();
bytes_used = 36;
if (mDegree > 8)
throw new RawDecoderException("A polynomial with more than 8 degrees not allowed");
if (param_max_bytes < 36 + (mDegree * 8))
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
for (UInt64 i = 0; i <= mDegree; i++)
{
parameters.BaseStream.Position = (long)(36 + 8 * i) + offset;
mCoefficient[i] = Convert.ToDouble(parameters.ReadBytes(8));
}
bytes_used += (int)(8 * mDegree + 8);
flags = (int)Flags.MultiThreaded | (int)Flags.PureLookup;
}
public override RawImage<ushort> CreateOutput(RawImage<ushort> input)
{
if (mFirstPlane > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
if (mFirstPlane + mPlanes > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
// Create lookup
for (int i = 0; i < 65536; i++)
{
double in_val = i / 65536.0;
double val = mCoefficient[0];
for (UInt64 j = 1; j <= mDegree; j++)
val += mCoefficient[j] * Math.Pow(in_val, j);
mLookup[i] = (ushort)Common.Clampbits((int)(val * 65535.5), 16);
}
return input;
}
public unsafe override void Apply(RawImage<ushort> input, ref RawImage<ushort> output, UInt32 startY, UInt32 endY)
{
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
fixed (UInt16* t = &output.raw.rawView[(int)y * output.raw.dim.Width + aoi.Left])
{
var src = t;
// Add offset, so this is always first plane
src += mFirstPlane;
for (UInt64 x = 0; x < aoi.Width; x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * output.raw.cpp + p] = mLookup[src[x * output.raw.cpp + p]];
}
}
}
}
}
}
class OpcodeGainMap : DngOpcode
{
UInt64 firstPlane, planes, rowPitch, colPitch, mapPointsV, mapPointsH, mapPlanes;
double mapSpacingV, mapSpacingH, mapOriginV, mapOriginH;
double[,,] gain;
//double[] coefficient = new double[9];
//UInt16[] lookup = new UInt16[65536];
public OpcodeGainMap(TiffBinaryReaderBigEndian parameters, UInt32 param_max_bytes, ref int bytes_used, uint offset)
{
if (param_max_bytes < 36)
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
uint h1 = parameters.ReadUInt32();
uint w1 = parameters.ReadUInt32();
uint h2 = parameters.ReadUInt32();
uint w2 = parameters.ReadUInt32();
aoi.SetAbsolute(w1, h1, w2, h2);
firstPlane = parameters.ReadUInt32();
planes = parameters.ReadUInt32();
rowPitch = parameters.ReadUInt32();
colPitch = parameters.ReadUInt32();
if (planes == 0)
throw new RawDecoderException("Zero planes");
if (rowPitch == 0 || colPitch == 0)
throw new RawDecoderException("Invalid Pitch");
mapPointsV = parameters.ReadUInt32();
mapPointsH = parameters.ReadUInt32();
mapSpacingV = parameters.ReadDouble() * h2;
mapSpacingH = parameters.ReadDouble() * w2;
mapOriginV = parameters.ReadDouble();
mapOriginH = parameters.ReadDouble();
mapPlanes = parameters.ReadUInt32();
gain = new double[mapPointsV, mapPointsH, mapPlanes];
bytes_used = 76;
if (param_max_bytes < 36 + (mapPointsV * mapPointsH * mapPlanes * 8))
throw new RawDecoderException("Not enough data to read parameters, only " + param_max_bytes + " bytes left.");
for (UInt64 i = 0; i < mapPointsV; i++)
{
for (UInt64 j = 0; j < mapPointsH; j++)
{
for (UInt64 k = 0; k < mapPlanes; k++)
{
gain[i, j, k] = parameters.ReadSingle();
}
}
}
bytes_used += (int)(8 * mapPointsV * mapPointsH * mapPlanes);
flags = (int)Flags.MultiThreaded | (int)Flags.PureLookup;
}
public override RawImage<ushort> CreateOutput(RawImage<ushort> input)
{
if (firstPlane > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
if (firstPlane + planes > input.raw.cpp)
throw new RawDecoderException("Not that many planes in actual image");
/*
// Create lookup
for (int i = 0; i < 65536; i++)
{
double in_val = i / 65536.0;
double val = coefficient[0];
for (UInt64 j = 1; j <= degree; j++)
val += coefficient[j] * Math.Pow(in_val, j);
lookup[i] = (ushort)Common.Clampbits((int)(val * 65535.5), 16);
}*/
return input;
}
public unsafe override void Apply(RawImage<ushort> input, ref RawImage<ushort> output, UInt32 startY, UInt32 endY)
{
for (UInt64 y = startY; y < endY; y += rowPitch)
{
ulong realY = (y - startY);
fixed (UInt16* t = &output.raw.rawView[(int)y * output.raw.UncroppedDim.Width + aoi.Left])
{
var src = t;
// Add offset, so this is always first plane
src += firstPlane;
for (UInt64 x = 0; x < aoi.Width; x += colPitch)
{
for (UInt64 p = 0; p < planes; p++)
{
//if outside the bound, last pixel or first
src[x] = (ushort)(src[x] * gain[(int)((y - startY) / mapSpacingV), (int)(x / mapSpacingH), 0]);
}
}
}
}
}
}
}
/*
class OpcodeDeltaPerRow : DngOpcode
{
UInt64 mFirstPlane, mPlanes, mRowPitch, mColPitch, mCount;
float* mDelta;
};
class OpcodeDeltaPerCol : public DngOpcode
{
public:
OpcodeDeltaPerCol(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used);
virtual ~OpcodeDeltaPerCol(void);
virtual RawImage& createOutput(RawImage<ushort> &in);
virtual void apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY);
private:
UInt64 mFirstPlane, mPlanes, mRowPitch, mColPitch, mCount;
float* mDelta;
int* mDeltaX;
};
class OpcodeScalePerRow : public DngOpcode
{
public:
OpcodeScalePerRow(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used);
virtual ~OpcodeScalePerRow(void) {};
virtual RawImage& createOutput(RawImage<ushort> &in);
virtual void apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY);
private:
UInt64 mFirstPlane, mPlanes, mRowPitch, mColPitch, mCount;
float* mDelta;
};
class OpcodeScalePerCol : public DngOpcode
{
public:
OpcodeScalePerCol(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used);
virtual ~OpcodeScalePerCol(void);
virtual RawImage& createOutput(RawImage<ushort> &in);
virtual void apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY);
private:
UInt64 mFirstPlane, mPlanes, mRowPitch, mColPitch, mCount;
float* mDelta;
int* mDeltaX;
};*/
/*
OpcodeFixBadPixelsConstant::OpcodeFixBadPixelsConstant(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 8)
throw new RawDecoderException("OpcodeFixBadPixelsConstant: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
mValue = getLong(¶meters[0]);
// Bayer Phase not used
* bytes_used = 8;
mFlags = MultiThreaded;
}
RawImage& OpcodeFixBadPixelsConstant::createOutput(RawImage<ushort> &in )
{
// These limitations are present within the DNG SDK as well.
if (in.getDataType() != TYPE_USHORT16)
throw new RawDecoderException("OpcodeFixBadPixelsConstant: Only 16 bit images supported");
if (in.getCpp() > 1)
throw new RawDecoderException("OpcodeFixBadPixelsConstant: This operation is only supported with 1 component");
return in;
}
void OpcodeFixBadPixelsConstant::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
iPoint2D crop = in.getCropOffset();
UInt32 offset = crop.x | (crop.y << 16);
vector<UInt32> bad_pos;
for (UInt32 y = startY; y < endY; y++)
{
UInt16* src = (UInt16*)out.getData(0, y);
for (UInt32 x = 0; x < (UInt32)in.dim.x; x++) {
if (src[x] == mValue)
{
bad_pos.Add(offset + ((UInt32)x | (UInt32)y << 16));
}
}
}
if (!bad_pos.empty()) {
pthread_mutex_lock(&out.mBadPixelMutex);
out.mBadPixelPositions.insert(out.mBadPixelPositions.end(), bad_pos.begin(), bad_pos.end());
pthread_mutex_unlock(&out.mBadPixelMutex);
}
}
OpcodeFixBadPixelsList::OpcodeFixBadPixelsList(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 12)
throw new RawDecoderException("OpcodeFixBadPixelsList: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
// Skip phase - we don't care
UInt64 BadPointCount = getULong(¶meters[4]);
UInt64 BadRectCount = getULong(¶meters[8]);
bytes_used[0] = 12;
if (12 + BadPointCount* 8 + BadRectCount* 16 > (UInt64) param_max_bytes)
throw new RawDecoderException("OpcodeFixBadPixelsList: Ran out parameter space, only %u bytes left.", param_max_bytes);
// Read points
for (UInt64 i = 0; i<BadPointCount; i++) {
UInt32 BadPointRow = (UInt32)getLong(¶meters[bytes_used[0]]);
UInt32 BadPointCol = (UInt32)getLong(¶meters[bytes_used[0] + 4]);
bytes_used[0] += 8;
bad_pos.Add(BadPointRow | (BadPointCol << 16));
}
// Read rects
for (UInt64 i = 0; i<BadRectCount; i++) {
UInt32 BadRectTop = (UInt32)getLong(¶meters[bytes_used[0]]);
UInt32 BadRectLeft = (UInt32)getLong(¶meters[bytes_used[0] + 4]);
UInt32 BadRectBottom = (UInt32)getLong(¶meters[bytes_used[0]]);
UInt32 BadRectRight = (UInt32)getLong(¶meters[bytes_used[0] + 4]);
bytes_used[0] += 16;
if (BadRectTop<BadRectBottom && BadRectLeft<BadRectRight) {
for (UInt32 y = BadRectLeft; y <= BadRectRight; y++) {
for (UInt32 x = BadRectTop; x <= BadRectBottom; x++) {
bad_pos.Add(x | (y << 16));
}
}
}
}
}
void OpcodeFixBadPixelsList::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
iPoint2D crop = in.getCropOffset();
UInt32 offset = crop.x | (crop.y << 16);
for (vector<UInt32>::iterator i = bad_pos.begin(); i != bad_pos.end(); ++i)
{
UInt32 pos = offset + (*i);
out.mBadPixelPositions.Add(pos);
}
}*/
/*
OpcodeDeltaPerRow::OpcodeDeltaPerRow(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 36)
throw new RawDecoderException("OpcodeDeltaPerRow: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
mAoi.setAbsolute(getLong(¶meters[4]), getLong(¶meters[0]), getLong(¶meters[12]), getLong(¶meters[8]));
mFirstPlane = getLong(¶meters[16]);
mPlanes = getLong(¶meters[20]);
mRowPitch = getLong(¶meters[24]);
mColPitch = getLong(¶meters[28]);
if (mPlanes == 0)
throw new RawDecoderException("OpcodeDeltaPerRow: Zero planes");
if (mRowPitch == 0 || mColPitch == 0)
throw new RawDecoderException("OpcodeDeltaPerRow: Invalid Pitch");
mCount = getLong(¶meters[32]);
* bytes_used = 36;
if (param_max_bytes< 36 + (mCount*4))
throw new RawDecoderException("OpcodeDeltaPerRow: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
if ((UInt64) mAoi.getHeight() != mCount)
throw new RawDecoderException("OpcodeDeltaPerRow: Element count (%llu) does not match height of area (%d.", mCount, mAoi.getHeight());
for (UInt64 i = 0; i<mCount; i++)
mDelta[i] = getFloat(¶meters[36 + 4 * i]);
* bytes_used += 4* mCount;
mFlags = MultiThreaded;
}
RawImage& OpcodeDeltaPerRow::createOutput(RawImage<ushort> &in )
{
if (mFirstPlane > in.getCpp())
throw new RawDecoderException("OpcodeDeltaPerRow: Not that many planes in actual image");
if (mFirstPlane+mPlanes > in.getCpp())
throw new RawDecoderException("OpcodeDeltaPerRow: Not that many planes in actual image");
return in;
}
void OpcodeDeltaPerRow::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
if (in.getDataType() == TYPE_USHORT16) {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
UInt16* src = (UInt16*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
int delta = (int)(65535.0f * mDelta[y]);
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = clampbits(16, delta + src[x * cpp + p]);
}
}
}
} else {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
float* src = (float*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
float delta = mDelta[y];
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = delta + src[x * cpp + p];
}
}
}
}
}
OpcodeDeltaPerCol::OpcodeDeltaPerCol(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 36)
throw new RawDecoderException("OpcodeDeltaPerCol: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
mAoi.setAbsolute(getLong(¶meters[4]), getLong(¶meters[0]), getLong(¶meters[12]), getLong(¶meters[8]));
mFirstPlane = getLong(¶meters[16]);
mPlanes = getLong(¶meters[20]);
mRowPitch = getLong(¶meters[24]);
mColPitch = getLong(¶meters[28]);
if (mPlanes == 0)
throw new RawDecoderException("OpcodeDeltaPerCol: Zero planes");
if (mRowPitch == 0 || mColPitch == 0)
throw new RawDecoderException("OpcodeDeltaPerCol: Invalid Pitch");
mCount = getLong(¶meters[32]);
* bytes_used = 36;
if (param_max_bytes< 36 + (mCount*4))
throw new RawDecoderException("OpcodeDeltaPerCol: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
if ((UInt64) mAoi.getWidth() != mCount)
throw new RawDecoderException("OpcodeDeltaPerRow: Element count (%llu) does not match width of area (%d).", mCount, mAoi.getWidth());
for (UInt64 i = 0; i<mCount; i++)
mDelta[i] = getFloat(¶meters[36 + 4 * i]);
* bytes_used += 4* mCount;
mFlags = MultiThreaded;
mDeltaX = null;
}
OpcodeDeltaPerCol::~OpcodeDeltaPerCol( void )
{
if (mDeltaX)
delete[] mDeltaX;
mDeltaX = null;
}
RawImage& OpcodeDeltaPerCol::createOutput(RawImage<ushort> &in )
{
if (mFirstPlane > in.getCpp())
throw new RawDecoderException("OpcodeDeltaPerCol: Not that many planes in actual image");
if (mFirstPlane+mPlanes > in.getCpp())
throw new RawDecoderException("OpcodeDeltaPerCol: Not that many planes in actual image");
if (in.getDataType() == TYPE_USHORT16) {
if (mDeltaX)
delete[] mDeltaX;
int w = mAoi.getWidth();
mDeltaX = new int[w];
for (int i = 0; i<w; i++)
mDeltaX[i] = (int) (65535.0f * mDelta[i] + 0.5f);
}
return in;
}
void OpcodeDeltaPerCol::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
if (in.getDataType() == TYPE_USHORT16) {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
UInt16* src = (UInt16*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = clampbits(16, mDeltaX[x] + src[x * cpp + p]);
}
}
}
} else {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
float* src = (float*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = mDelta[x] + src[x * cpp + p];
}
}
}
}
}
OpcodeScalePerRow::OpcodeScalePerRow(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 36)
throw new RawDecoderException("OpcodeScalePerRow: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
mAoi.setAbsolute(getLong(¶meters[4]), getLong(¶meters[0]), getLong(¶meters[12]), getLong(¶meters[8]));
mFirstPlane = getLong(¶meters[16]);
mPlanes = getLong(¶meters[20]);
mRowPitch = getLong(¶meters[24]);
mColPitch = getLong(¶meters[28]);
if (mPlanes == 0)
throw new RawDecoderException("OpcodeScalePerRow: Zero planes");
if (mRowPitch == 0 || mColPitch == 0)
throw new RawDecoderException("OpcodeScalePerRow: Invalid Pitch");
mCount = getLong(¶meters[32]);
* bytes_used = 36;
if (param_max_bytes< 36 + (mCount*4))
throw new RawDecoderException("OpcodeScalePerRow: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
if ((UInt64) mAoi.getHeight() != mCount)
throw new RawDecoderException("OpcodeScalePerRow: Element count (%llu) does not match height of area (%d).", mCount, mAoi.getHeight());
for (UInt64 i = 0; i<mCount; i++)
mDelta[i] = getFloat(¶meters[36 + 4 * i]);
* bytes_used += 4* mCount;
mFlags = MultiThreaded;
}
RawImage& OpcodeScalePerRow::createOutput(RawImage<ushort> &in )
{
if (mFirstPlane > in.getCpp())
throw new RawDecoderException("OpcodeScalePerRow: Not that many planes in actual image");
if (mFirstPlane+mPlanes > in.getCpp())
throw new RawDecoderException("OpcodeScalePerRow: Not that many planes in actual image");
return in;
}
void OpcodeScalePerRow::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
if (in.getDataType() == TYPE_USHORT16) {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
UInt16* src = (UInt16*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
int delta = (int)(1024.0f * mDelta[y]);
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = clampbits(16, (delta * src[x * cpp + p] + 512) >> 10);
}
}
}
} else {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
float* src = (float*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
float delta = mDelta[y];
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = delta * src[x * cpp + p];
}
}
}
}
}
OpcodeScalePerCol::OpcodeScalePerCol(byte[] parameters, UInt32 param_max_bytes, UInt32* bytes_used)
{
if (param_max_bytes< 36)
throw new RawDecoderException("OpcodeScalePerCol: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
mAoi.setAbsolute(getLong(¶meters[4]), getLong(¶meters[0]), getLong(¶meters[12]), getLong(¶meters[8]));
mFirstPlane = getLong(¶meters[16]);
mPlanes = getLong(¶meters[20]);
mRowPitch = getLong(¶meters[24]);
mColPitch = getLong(¶meters[28]);
if (mPlanes == 0)
throw new RawDecoderException("OpcodeScalePerCol: Zero planes");
if (mRowPitch == 0 || mColPitch == 0)
throw new RawDecoderException("OpcodeScalePerCol: Invalid Pitch");
mCount = getLong(¶meters[32]);
* bytes_used = 36;
if (param_max_bytes< 36 + (mCount*4))
throw new RawDecoderException("OpcodeScalePerCol: Not enough data to read parameters, only %u bytes left.", param_max_bytes);
if ((UInt64) mAoi.getWidth() != mCount)
throw new RawDecoderException("OpcodeScalePerCol: Element count (%llu) does not match width of area (%d).", mCount, mAoi.getWidth());
for (UInt64 i = 0; i<mCount; i++)
mDelta[i] = getFloat(¶meters[36 + 4 * i]);
* bytes_used += 4* mCount;
mFlags = MultiThreaded;
mDeltaX = null;
}
OpcodeScalePerCol::~OpcodeScalePerCol( void )
{
if (mDeltaX)
delete[] mDeltaX;
mDeltaX = null;
}
RawImage<ushort> OpcodeScalePerCol::createOutput(RawImage<ushort> &in )
{
if (mFirstPlane > in.getCpp())
throw new RawDecoderException("OpcodeScalePerCol: Not that many planes in actual image");
if (mFirstPlane + mPlanes > in.getCpp())
throw new RawDecoderException("OpcodeScalePerCol: Not that many planes in actual image");
if (in.getDataType() == TYPE_USHORT16) {
if (mDeltaX)
delete[] mDeltaX;
int w = mAoi.getWidth();
mDeltaX = new int[w];
for (int i = 0; i < w; i++)
mDeltaX[i] = (int)(1024.0f * mDelta[i]);
}
return in;
}
void OpcodeScalePerCol::apply(RawImage<ushort> &in, RawImage<ushort> &out, UInt32 startY, UInt32 endY)
{
if (in.getDataType() == TYPE_USHORT16) {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
UInt16* src = (UInt16*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = clampbits(16, (mDeltaX[x] * src[x * cpp + p] + 512) >> 10);
}
}
}
} else {
int cpp = out.getCpp();
for (UInt64 y = startY; y < endY; y += mRowPitch)
{
float* src = (float*)out.getData(mAoi.getLeft(), y);
// Add offset, so this is always first plane
src += mFirstPlane;
for (UInt64 x = 0; x < (UInt64)mAoi.getWidth(); x += mColPitch)
{
for (UInt64 p = 0; p < mPlanes; p++)
{
src[x * cpp + p] = mDelta[x] * src[x * cpp + p];
}
}
}
}
}
}
}
*/
| |
Func<int, int, char[][]> makeScreen = (w, h) =>
{
var a = new char[h][];
for (int y = 0; y < h; y++)
{
a[y] = new String('.', w).ToCharArray();
}
return a;
};
var realScreen = makeScreen(50, 6);
var testScreen = makeScreen(7, 3);
var realInput = @"rect 1x1
rotate row y=0 by 2
rect 1x1
rotate row y=0 by 5
rect 1x1
rotate row y=0 by 3
rect 1x1
rotate row y=0 by 3
rect 2x1
rotate row y=0 by 5
rect 1x1
rotate row y=0 by 5
rect 4x1
rotate row y=0 by 2
rect 1x1
rotate row y=0 by 2
rect 1x1
rotate row y=0 by 5
rect 4x1
rotate row y=0 by 3
rect 2x1
rotate row y=0 by 5
rect 4x1
rotate row y=0 by 2
rect 1x2
rotate row y=1 by 6
rotate row y=0 by 2
rect 1x2
rotate column x=32 by 1
rotate column x=23 by 1
rotate column x=13 by 1
rotate row y=0 by 6
rotate column x=0 by 1
rect 5x1
rotate row y=0 by 2
rotate column x=30 by 1
rotate row y=1 by 20
rotate row y=0 by 18
rotate column x=13 by 1
rotate column x=10 by 1
rotate column x=7 by 1
rotate column x=2 by 1
rotate column x=0 by 1
rect 17x1
rotate column x=16 by 3
rotate row y=3 by 7
rotate row y=0 by 5
rotate column x=2 by 1
rotate column x=0 by 1
rect 4x1
rotate column x=28 by 1
rotate row y=1 by 24
rotate row y=0 by 21
rotate column x=19 by 1
rotate column x=17 by 1
rotate column x=16 by 1
rotate column x=14 by 1
rotate column x=12 by 2
rotate column x=11 by 1
rotate column x=9 by 1
rotate column x=8 by 1
rotate column x=7 by 1
rotate column x=6 by 1
rotate column x=4 by 1
rotate column x=2 by 1
rotate column x=0 by 1
rect 20x1
rotate column x=47 by 1
rotate column x=40 by 2
rotate column x=35 by 2
rotate column x=30 by 2
rotate column x=10 by 3
rotate column x=5 by 3
rotate row y=4 by 20
rotate row y=3 by 10
rotate row y=2 by 20
rotate row y=1 by 16
rotate row y=0 by 9
rotate column x=7 by 2
rotate column x=5 by 2
rotate column x=3 by 2
rotate column x=0 by 2
rect 9x2
rotate column x=22 by 2
rotate row y=3 by 40
rotate row y=1 by 20
rotate row y=0 by 20
rotate column x=18 by 1
rotate column x=17 by 2
rotate column x=16 by 1
rotate column x=15 by 2
rotate column x=13 by 1
rotate column x=12 by 1
rotate column x=11 by 1
rotate column x=10 by 1
rotate column x=8 by 3
rotate column x=7 by 1
rotate column x=6 by 1
rotate column x=5 by 1
rotate column x=3 by 1
rotate column x=2 by 1
rotate column x=1 by 1
rotate column x=0 by 1
rect 19x1
rotate column x=44 by 2
rotate column x=40 by 3
rotate column x=29 by 1
rotate column x=27 by 2
rotate column x=25 by 5
rotate column x=24 by 2
rotate column x=22 by 2
rotate column x=20 by 5
rotate column x=14 by 3
rotate column x=12 by 2
rotate column x=10 by 4
rotate column x=9 by 3
rotate column x=7 by 3
rotate column x=3 by 5
rotate column x=2 by 2
rotate row y=5 by 10
rotate row y=4 by 8
rotate row y=3 by 8
rotate row y=2 by 48
rotate row y=1 by 47
rotate row y=0 by 40
rotate column x=47 by 5
rotate column x=46 by 5
rotate column x=45 by 4
rotate column x=43 by 2
rotate column x=42 by 3
rotate column x=41 by 2
rotate column x=38 by 5
rotate column x=37 by 5
rotate column x=36 by 5
rotate column x=33 by 1
rotate column x=28 by 1
rotate column x=27 by 5
rotate column x=26 by 5
rotate column x=25 by 1
rotate column x=23 by 5
rotate column x=22 by 1
rotate column x=21 by 2
rotate column x=18 by 1
rotate column x=17 by 3
rotate column x=12 by 2
rotate column x=11 by 2
rotate column x=7 by 5
rotate column x=6 by 5
rotate column x=5 by 4
rotate column x=3 by 5
rotate column x=2 by 5
rotate column x=1 by 3
rotate column x=0 by 4"
.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var testInput = @"rect 3x2
rotate column x=1 by 1
rotate row y=0 by 4
rotate column x=1 by 1"
.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var rectExpr = new Regex(@"^rect (?<x>\d+)x(?<y>\d+)$");
var rotateColumnExpr = new Regex(@"^rotate column x=(?<x>\d+) by (?<n>\d+)$");
var rotateRowExpr = new Regex(@"^rotate row y=(?<y>\d+) by (?<n>\d+)$");
Action<char[][], int, int> Rect = (char[][] a, int w, int h) =>
{
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
a[y][x] = '#';
}
}
};
Func<string, int, string> ShiftRight = (string s, int count) =>
{
if (count == 0 || count == s.Length)
return s;
count = count % s.Length;
var overflow = s.Substring(s.Length - count, count);
var left = s.Substring(0, s.Length - count);
return overflow + left;
};
Action<Char[][], int, int> ShiftDown = (Char[][] a, int index, int count) =>
{
string s = new String(a.Select(b => b[index]).ToArray());
s = ShiftRight(s, count);
for (int i = 0; i < a.Length; i++)
{
a[i][index] = s[i];
}
};
Action<char[][]> Print = (char[][] a) =>
{
for (int y = 0; y < a.Length; y++)
{
Console.WriteLine(new String(a[y]));
}
};
var input = realInput;
var screen = realScreen;
foreach (var line in input)
{
// Print(screen);
var match = rectExpr.Match(line);
if (match.Success)
{
var w = int.Parse(match.Groups["x"].Value);
var h = int.Parse(match.Groups["y"].Value);
Console.WriteLine($"rect({w}, {h})");
Rect(screen, w, h);
continue;
}
match = rotateColumnExpr.Match(line);
if (match.Success)
{
var x = int.Parse(match.Groups["x"].Value);
var n = int.Parse(match.Groups["n"].Value);
ShiftDown(screen, x, n);
Console.WriteLine($"rotate(x={x}, {n})");
continue;
}
match = rotateRowExpr.Match(line);
if (match.Success)
{
var y = int.Parse(match.Groups["y"].Value);
var n = int.Parse(match.Groups["n"].Value);
screen[y] = ShiftRight(new String(screen[y]), n).ToCharArray();
Console.WriteLine($"rotate(y={y}, {n})");
continue;
}
throw new Exception("Bad input line: '" + line + "'");
}
Print(screen);
screen.Sum(line => line.Sum(c => c == '#' ? 1 : 0)).Dump();
// 70? No, too low.
| |
using System;
using System.Reactive.Linq;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Threading;
using Avalonia.VisualTree;
using Avalonia.Layout;
namespace Avalonia.Controls.Presenters
{
public class TextPresenter : Control
{
public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly StyledProperty<bool> RevealPasswordProperty =
AvaloniaProperty.Register<TextPresenter, bool>(nameof(RevealPassword));
public static readonly StyledProperty<char> PasswordCharProperty =
AvaloniaProperty.Register<TextPresenter, char>(nameof(PasswordChar));
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionBrushProperty));
public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionForegroundBrushProperty));
public static readonly StyledProperty<IBrush> CaretBrushProperty =
AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(CaretBrushProperty));
public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
/// <summary>
/// Defines the <see cref="Text"/> property.
/// </summary>
public static readonly DirectProperty<TextPresenter, string> TextProperty =
AvaloniaProperty.RegisterDirect<TextPresenter, string>(
nameof(Text),
o => o.Text,
(o, v) => o.Text = v);
/// <summary>
/// Defines the <see cref="TextAlignment"/> property.
/// </summary>
public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
TextBlock.TextAlignmentProperty.AddOwner<TextPresenter>();
/// <summary>
/// Defines the <see cref="TextWrapping"/> property.
/// </summary>
public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner<TextPresenter>();
/// <summary>
/// Defines the <see cref="Background"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> BackgroundProperty =
Border.BackgroundProperty.AddOwner<TextPresenter>();
private readonly DispatcherTimer _caretTimer;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _caretBlink;
private string _text;
private FormattedText _formattedText;
private Size _constraint;
static TextPresenter()
{
AffectsRender<TextPresenter>(SelectionBrushProperty, TextBlock.ForegroundProperty,
SelectionForegroundBrushProperty, CaretBrushProperty);
AffectsMeasure<TextPresenter>(TextProperty, PasswordCharProperty, RevealPasswordProperty,
TextAlignmentProperty, TextWrappingProperty, TextBlock.FontSizeProperty,
TextBlock.FontStyleProperty, TextBlock.FontWeightProperty, TextBlock.FontFamilyProperty);
Observable.Merge<AvaloniaPropertyChangedEventArgs>(TextProperty.Changed, TextBlock.ForegroundProperty.Changed,
TextAlignmentProperty.Changed, TextWrappingProperty.Changed,
TextBlock.FontSizeProperty.Changed, TextBlock.FontStyleProperty.Changed,
TextBlock.FontWeightProperty.Changed, TextBlock.FontFamilyProperty.Changed,
SelectionStartProperty.Changed, SelectionEndProperty.Changed,
SelectionForegroundBrushProperty.Changed, PasswordCharProperty.Changed, RevealPasswordProperty.Changed
).AddClassHandler<TextPresenter>((x, _) => x.InvalidateFormattedText());
CaretIndexProperty.Changed.AddClassHandler<TextPresenter>((x, e) => x.CaretIndexChanged((int)e.NewValue));
}
public TextPresenter()
{
_text = string.Empty;
_caretTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
_caretTimer.Tick += CaretTimerTick;
}
/// <summary>
/// Gets or sets a brush used to paint the control's background.
/// </summary>
public IBrush Background
{
get => GetValue(BackgroundProperty);
set => SetValue(BackgroundProperty, value);
}
/// <summary>
/// Gets or sets the text.
/// </summary>
[Content]
public string Text
{
get => _text;
set => SetAndRaise(TextProperty, ref _text, value);
}
/// <summary>
/// Gets or sets the font family.
/// </summary>
public FontFamily FontFamily
{
get => TextBlock.GetFontFamily(this);
set => TextBlock.SetFontFamily(this, value);
}
/// <summary>
/// Gets or sets the font size.
/// </summary>
public double FontSize
{
get => TextBlock.GetFontSize(this);
set => TextBlock.SetFontSize(this, value);
}
/// <summary>
/// Gets or sets the font style.
/// </summary>
public FontStyle FontStyle
{
get => TextBlock.GetFontStyle(this);
set => TextBlock.SetFontStyle(this, value);
}
/// <summary>
/// Gets or sets the font weight.
/// </summary>
public FontWeight FontWeight
{
get => TextBlock.GetFontWeight(this);
set => TextBlock.SetFontWeight(this, value);
}
/// <summary>
/// Gets or sets a brush used to paint the text.
/// </summary>
public IBrush Foreground
{
get => TextBlock.GetForeground(this);
set => TextBlock.SetForeground(this, value);
}
/// <summary>
/// Gets or sets the control's text wrapping mode.
/// </summary>
public TextWrapping TextWrapping
{
get => GetValue(TextWrappingProperty);
set => SetValue(TextWrappingProperty, value);
}
/// <summary>
/// Gets or sets the text alignment.
/// </summary>
public TextAlignment TextAlignment
{
get => GetValue(TextAlignmentProperty);
set => SetValue(TextAlignmentProperty, value);
}
/// <summary>
/// Gets the <see cref="FormattedText"/> used to render the text.
/// </summary>
public FormattedText FormattedText
{
get
{
return _formattedText ?? (_formattedText = CreateFormattedText());
}
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
}
}
public char PasswordChar
{
get => GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
public bool RevealPassword
{
get => GetValue(RevealPasswordProperty);
set => SetValue(RevealPasswordProperty, value);
}
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
public IBrush SelectionForegroundBrush
{
get => GetValue(SelectionForegroundBrushProperty);
set => SetValue(SelectionForegroundBrushProperty, value);
}
public IBrush CaretBrush
{
get => GetValue(CaretBrushProperty);
set => SetValue(CaretBrushProperty, value);
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
public int GetCaretIndex(Point point)
{
var hit = FormattedText.HitTestPoint(point);
return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
/// <summary>
/// Creates the <see cref="FormattedText"/> used to render the text.
/// </summary>
/// <param name="constraint">The constraint of the text.</param>
/// <param name="text">The text to format.</param>
/// <returns>A <see cref="FormattedText"/> object.</returns>
private FormattedText CreateFormattedTextInternal(Size constraint, string text)
{
return new FormattedText
{
Constraint = constraint,
Typeface = new Typeface(FontFamily, FontStyle, FontWeight),
FontSize = FontSize,
Text = text ?? string.Empty,
TextAlignment = TextAlignment,
TextWrapping = TextWrapping,
};
}
/// <summary>
/// Invalidates <see cref="FormattedText"/>.
/// </summary>
protected void InvalidateFormattedText()
{
_formattedText = null;
}
/// <summary>
/// Renders the <see cref="TextPresenter"/> to a drawing context.
/// </summary>
/// <param name="context">The drawing context.</param>
private void RenderInternal(DrawingContext context)
{
var background = Background;
if (background != null)
{
context.FillRectangle(background, new Rect(Bounds.Size));
}
double top = 0;
var textSize = FormattedText.Bounds.Size;
if (Bounds.Height < textSize.Height)
{
switch (VerticalAlignment)
{
case VerticalAlignment.Center:
top += (Bounds.Height - textSize.Height) / 2;
break;
case VerticalAlignment.Bottom:
top += (Bounds.Height - textSize.Height);
break;
}
}
context.DrawText(Foreground, new Point(0, top), FormattedText);
}
public override void Render(DrawingContext context)
{
FormattedText.Constraint = Bounds.Size;
_constraint = Bounds.Size;
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
var rects = FormattedText.HitTestTextRange(start, length);
foreach (var rect in rects)
{
context.FillRectangle(SelectionBrush, rect);
}
}
RenderInternal(context);
if (selectionStart == selectionEnd)
{
var caretBrush = CaretBrush;
if (caretBrush is null)
{
var backgroundColor = (Background as SolidColorBrush)?.Color;
if (backgroundColor.HasValue)
{
byte red = (byte)~(backgroundColor.Value.R);
byte green = (byte)~(backgroundColor.Value.G);
byte blue = (byte)~(backgroundColor.Value.B);
caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
}
else
caretBrush = Brushes.Black;
}
if (_caretBlink)
{
var charPos = FormattedText.HitTestTextPosition(CaretIndex);
var x = Math.Floor(charPos.X) + 0.5;
var y = Math.Floor(charPos.Y) + 0.5;
var b = Math.Ceiling(charPos.Bottom) - 0.5;
context.DrawLine(
new Pen(caretBrush, 1),
new Point(x, y),
new Point(x, b));
}
}
}
public void ShowCaret()
{
_caretBlink = true;
_caretTimer.Start();
InvalidateVisual();
}
public void HideCaret()
{
_caretBlink = false;
_caretTimer.Stop();
InvalidateVisual();
}
internal void CaretIndexChanged(int caretIndex)
{
if (this.GetVisualParent() != null)
{
if (_caretTimer.IsEnabled)
{
_caretBlink = true;
_caretTimer.Stop();
_caretTimer.Start();
InvalidateVisual();
}
else
{
_caretTimer.Start();
InvalidateVisual();
_caretTimer.Stop();
}
if (IsMeasureValid)
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
}
else
{
// The measure is currently invalid so there's no point trying to bring the
// current char into view until a measure has been carried out as the scroll
// viewer extents may not be up-to-date.
Dispatcher.UIThread.Post(
() =>
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
},
DispatcherPriority.Render);
}
}
}
/// <summary>
/// Creates the <see cref="FormattedText"/> used to render the text.
/// </summary>
/// <returns>A <see cref="FormattedText"/> object.</returns>
protected virtual FormattedText CreateFormattedText()
{
FormattedText result = null;
var text = Text;
if (PasswordChar != default(char) && !RevealPassword)
{
result = CreateFormattedTextInternal(_constraint, new string(PasswordChar, text?.Length ?? 0));
}
else
{
result = CreateFormattedTextInternal(_constraint, text);
}
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
if (length > 0)
{
result.Spans = new[]
{
new FormattedTextStyleSpan(start, length, SelectionForegroundBrush),
};
}
return result;
}
/// <summary>
/// Measures the control.
/// </summary>
/// <param name="availableSize">The available size for the control.</param>
/// <returns>The desired size.</returns>
private Size MeasureInternal(Size availableSize)
{
if (!string.IsNullOrEmpty(Text))
{
if (TextWrapping == TextWrapping.Wrap)
{
_constraint = new Size(availableSize.Width, double.PositiveInfinity);
}
else
{
_constraint = Size.Infinity;
}
_formattedText = null;
return FormattedText.Bounds.Size;
}
return new Size();
}
protected override Size MeasureOverride(Size availableSize)
{
var text = Text;
if (!string.IsNullOrEmpty(text))
{
return MeasureInternal(availableSize);
}
else
{
return new FormattedText
{
Text = "X",
Typeface = new Typeface(FontFamily, FontStyle, FontWeight),
FontSize = FontSize,
TextAlignment = TextAlignment,
Constraint = availableSize,
}.Bounds.Size;
}
}
private int CoerceCaretIndex(int value)
{
var text = Text;
var length = text?.Length ?? 0;
return Math.Max(0, Math.Min(length, value));
}
private void CaretTimerTick(object sender, EventArgs e)
{
_caretBlink = !_caretBlink;
InvalidateVisual();
}
}
}
| |
// 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.Buffers;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Security;
using System.Text;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using Microsoft.Win32;
using System.IO;
using static Interop.Advapi32;
#if !netcoreapp
using MemoryMarshal = System.Diagnostics.PerformanceCounterLib;
#endif
namespace System.Diagnostics
{
internal class PerformanceCounterLib
{
internal const string PerfShimName = "netfxperf.dll";
private const string PerfShimFullNameSuffix = @"\netfxperf.dll";
private const string PerfShimPathExp = @"%systemroot%\system32\netfxperf.dll";
internal const string OpenEntryPoint = "OpenPerformanceData";
internal const string CollectEntryPoint = "CollectPerformanceData";
internal const string CloseEntryPoint = "ClosePerformanceData";
internal const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance";
private const string PerflibPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib";
internal const string ServicePath = "SYSTEM\\CurrentControlSet\\Services";
private const string CategorySymbolPrefix = "OBJECT_";
private const string ConterSymbolPrefix = "DEVICE_COUNTER_";
private const string HelpSufix = "_HELP";
private const string NameSufix = "_NAME";
private const string TextDefinition = "[text]";
private const string InfoDefinition = "[info]";
private const string LanguageDefinition = "[languages]";
private const string ObjectDefinition = "[objects]";
private const string DriverNameKeyword = "drivername";
private const string SymbolFileKeyword = "symbolfile";
private const string DefineKeyword = "#define";
private const string LanguageKeyword = "language";
private const string DllName = "netfxperf.dll";
private const int EnglishLCID = 0x009;
private static volatile string s_computerName;
private static volatile string s_iniFilePath;
private static volatile string s_symbolFilePath;
private PerformanceMonitor _performanceMonitor;
private string _machineName;
private string _perfLcid;
private static volatile Hashtable s_libraryTable;
private Hashtable _customCategoryTable;
private Hashtable _categoryTable;
private Hashtable _nameTable;
private Hashtable _helpTable;
private readonly object _categoryTableLock = new object();
private readonly object _nameTableLock = new object();
private readonly object _helpTableLock = new object();
private static object s_internalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_internalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_internalSyncObject, o, null);
}
return s_internalSyncObject;
}
}
internal PerformanceCounterLib(string machineName, string lcid)
{
_machineName = machineName;
_perfLcid = lcid;
}
/// <internalonly/>
internal static string ComputerName
{
get
{
if (s_computerName == null)
{
lock (InternalSyncObject)
{
if (s_computerName == null)
{
s_computerName = Interop.Kernel32.GetComputerName() ?? string.Empty;
}
}
}
return s_computerName;
}
}
#if !netcoreapp
internal static T Read<T>(ReadOnlySpan<byte> span) where T : struct
=> System.Runtime.InteropServices.MemoryMarshal.Read<T>(span);
internal static ref readonly T AsRef<T>(ReadOnlySpan<byte> span) where T : struct
=> ref System.Runtime.InteropServices.MemoryMarshal.Cast<byte, T>(span)[0];
#endif
private Hashtable CategoryTable
{
get
{
if (_categoryTable == null)
{
lock (_categoryTableLock)
{
if (_categoryTable == null)
{
ReadOnlySpan<byte> data = GetPerformanceData("Global");
ref readonly PERF_DATA_BLOCK dataBlock = ref MemoryMarshal.AsRef<PERF_DATA_BLOCK>(data);
int pos = dataBlock.HeaderLength;
int numPerfObjects = dataBlock.NumObjectTypes;
// on some machines MSMQ claims to have 4 categories, even though it only has 2.
// This causes us to walk past the end of our data, potentially crashing or reading
// data we shouldn't. We use dataBlock.TotalByteLength to make sure we don't go past the end
// of the perf data.
Hashtable tempCategoryTable = new Hashtable(numPerfObjects, StringComparer.OrdinalIgnoreCase);
for (int index = 0; index < numPerfObjects && pos < dataBlock.TotalByteLength; index++)
{
ref readonly PERF_OBJECT_TYPE perfObject = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
CategoryEntry newCategoryEntry = new CategoryEntry(in perfObject);
int nextPos = pos + perfObject.TotalByteLength;
pos += perfObject.HeaderLength;
int index3 = 0;
int previousCounterIndex = -1;
//Need to filter out counters that are repeated, some providers might
//return several adjacent copies of the same counter.
for (int index2 = 0; index2 < newCategoryEntry.CounterIndexes.Length; ++index2)
{
ref readonly PERF_COUNTER_DEFINITION perfCounter = ref MemoryMarshal.AsRef<PERF_COUNTER_DEFINITION>(data.Slice(pos));
if (perfCounter.CounterNameTitleIndex != previousCounterIndex)
{
newCategoryEntry.CounterIndexes[index3] = perfCounter.CounterNameTitleIndex;
newCategoryEntry.HelpIndexes[index3] = perfCounter.CounterHelpTitleIndex;
previousCounterIndex = perfCounter.CounterNameTitleIndex;
++index3;
}
pos += perfCounter.ByteLength;
}
//Lets adjust the entry counter arrays in case there were repeated copies
if (index3 < newCategoryEntry.CounterIndexes.Length)
{
int[] adjustedCounterIndexes = new int[index3];
int[] adjustedHelpIndexes = new int[index3];
Array.Copy(newCategoryEntry.CounterIndexes, adjustedCounterIndexes, index3);
Array.Copy(newCategoryEntry.HelpIndexes, adjustedHelpIndexes, index3);
newCategoryEntry.CounterIndexes = adjustedCounterIndexes;
newCategoryEntry.HelpIndexes = adjustedHelpIndexes;
}
string categoryName = (string)NameTable[newCategoryEntry.NameIndex];
if (categoryName != null)
tempCategoryTable[categoryName] = newCategoryEntry;
pos = nextPos;
}
_categoryTable = tempCategoryTable;
}
}
}
return _categoryTable;
}
}
internal Hashtable HelpTable
{
get
{
if (_helpTable == null)
{
lock (_helpTableLock)
{
if (_helpTable == null)
_helpTable = GetStringTable(true);
}
}
return _helpTable;
}
}
// Returns a temp file name
private static string IniFilePath
{
get
{
if (s_iniFilePath == null)
{
lock (InternalSyncObject)
{
if (s_iniFilePath == null)
{
try
{
s_iniFilePath = Path.GetTempFileName();
}
finally
{ }
}
}
}
return s_iniFilePath;
}
}
internal Hashtable NameTable
{
get
{
if (_nameTable == null)
{
lock (_nameTableLock)
{
if (_nameTable == null)
_nameTable = GetStringTable(false);
}
}
return _nameTable;
}
}
// Returns a temp file name
private static string SymbolFilePath
{
get
{
if (s_symbolFilePath == null)
{
lock (InternalSyncObject)
{
if (s_symbolFilePath == null)
{
string tempPath;
tempPath = Path.GetTempPath();
try
{
s_symbolFilePath = Path.GetTempFileName();
}
finally
{ }
}
}
}
return s_symbolFilePath;
}
}
internal static bool CategoryExists(string machine, string category)
{
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (library.CategoryExists(category))
return true;
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
if (library.CategoryExists(category))
return true;
culture = culture.Parent;
}
}
return false;
}
internal bool CategoryExists(string category)
{
return CategoryTable.ContainsKey(category);
}
internal static void CloseAllLibraries()
{
if (s_libraryTable != null)
{
//race with GetPerformanceCounterLib
lock (InternalSyncObject)
{
if (s_libraryTable != null)
{
foreach (PerformanceCounterLib library in s_libraryTable.Values)
library.Close();
s_libraryTable = null;
}
}
}
}
internal static void CloseAllTables()
{
if (s_libraryTable != null)
{
foreach (PerformanceCounterLib library in s_libraryTable.Values)
library.CloseTables();
}
}
internal void CloseTables()
{
_nameTable = null;
_helpTable = null;
_categoryTable = null;
_customCategoryTable = null;
}
internal void Close()
{
if (_performanceMonitor != null)
{
_performanceMonitor.Close();
_performanceMonitor = null;
}
CloseTables();
}
internal static bool CounterExists(string machine, string category, string counter)
{
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
bool counterExists = library.CounterExists(category, counter, ref categoryExists);
if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
counterExists = library.CounterExists(category, counter, ref categoryExists);
if (counterExists)
break;
culture = culture.Parent;
}
}
if (!categoryExists)
{
// Consider adding diagnostic logic here, may be we can dump the nameTable...
throw new InvalidOperationException(SR.MissingCategory);
}
return counterExists;
}
private bool CounterExists(string category, string counter, ref bool categoryExists)
{
categoryExists = false;
if (!CategoryTable.ContainsKey(category))
return false;
else
categoryExists = true;
CategoryEntry entry = (CategoryEntry)CategoryTable[category];
for (int index = 0; index < entry.CounterIndexes.Length; ++index)
{
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)NameTable[counterIndex];
if (counterName == null)
counterName = string.Empty;
if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds)
{
try
{
StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode);
try
{
//NT4 won't be able to parse Unicode ini files without this
//extra white space.
iniWriter.WriteLine("");
iniWriter.WriteLine(InfoDefinition);
iniWriter.Write(DriverNameKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
iniWriter.Write(SymbolFileKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(Path.GetFileName(SymbolFilePath));
iniWriter.WriteLine("");
iniWriter.WriteLine(LanguageDefinition);
foreach (string languageId in languageIds)
{
iniWriter.Write(languageId);
iniWriter.Write("=");
iniWriter.Write(LanguageKeyword);
iniWriter.WriteLine(languageId);
}
iniWriter.WriteLine("");
iniWriter.WriteLine(ObjectDefinition);
foreach (string languageId in languageIds)
{
iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
}
iniWriter.WriteLine("");
iniWriter.WriteLine(TextDefinition);
foreach (string languageId in languageIds)
{
iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(HelpSufix);
iniWriter.Write("=");
if (categoryHelp == null || categoryHelp == string.Empty)
iniWriter.WriteLine(SR.HelpNotAvailable);
else
iniWriter.WriteLine(categoryHelp);
int counterIndex = 0;
foreach (CounterCreationData counterData in creationData)
{
++counterIndex;
iniWriter.WriteLine("");
iniWriter.Write(ConterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(counterData.CounterName);
iniWriter.Write(ConterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
iniWriter.Write(HelpSufix);
iniWriter.Write("=");
Debug.Assert(!string.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller");
iniWriter.WriteLine(counterData.CounterHelp);
}
}
iniWriter.WriteLine("");
}
finally
{
iniWriter.Close();
}
}
finally
{ }
}
private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered)
{
RegistryKey serviceParentKey = null;
RegistryKey serviceKey = null;
RegistryKey linkageKey = null;
try
{
serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true);
if (serviceKey == null)
serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance");
serviceKey.SetValue("Open", "OpenPerformanceData");
serviceKey.SetValue("Collect", "CollectPerformanceData");
serviceKey.SetValue("Close", "ClosePerformanceData");
serviceKey.SetValue("Library", DllName);
serviceKey.SetValue("IsMultiInstance", (int)categoryType, RegistryValueKind.DWord);
serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord);
string[] counters = new string[creationData.Count];
string[] counterTypes = new string[creationData.Count];
for (int i = 0; i < creationData.Count; i++)
{
counters[i] = creationData[i].CounterName;
counterTypes[i] = ((int)creationData[i].CounterType).ToString(CultureInfo.InvariantCulture);
}
linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage", true);
if (linkageKey == null)
linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage");
linkageKey.SetValue("Export", new string[] { categoryName });
serviceKey.SetValue("Counter Types", (object)counterTypes);
serviceKey.SetValue("Counter Names", (object)counters);
object firstID = serviceKey.GetValue("First Counter");
if (firstID != null)
iniRegistered = true;
else
iniRegistered = false;
}
finally
{
if (serviceKey != null)
serviceKey.Close();
if (linkageKey != null)
linkageKey.Close();
if (serviceParentKey != null)
serviceParentKey.Close();
}
}
private static void CreateSymbolFile(CounterCreationDataCollection creationData)
{
try
{
StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
try
{
symbolWriter.Write(DefineKeyword);
symbolWriter.Write(" ");
symbolWriter.Write(CategorySymbolPrefix);
symbolWriter.WriteLine("1 0;");
for (int counterIndex = 1; counterIndex <= creationData.Count; ++counterIndex)
{
symbolWriter.Write(DefineKeyword);
symbolWriter.Write(" ");
symbolWriter.Write(ConterSymbolPrefix);
symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
symbolWriter.Write(" ");
symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture));
symbolWriter.WriteLine(";");
}
symbolWriter.WriteLine("");
}
finally
{
symbolWriter.Close();
}
}
finally
{ }
}
private static void DeleteRegistryEntry(string categoryName)
{
RegistryKey serviceKey = null;
try
{
serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
bool deleteCategoryKey = false;
using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true))
{
if (categoryKey != null)
{
if (categoryKey.GetValueNames().Length == 0)
{
deleteCategoryKey = true;
}
else
{
categoryKey.DeleteSubKeyTree("Linkage");
categoryKey.DeleteSubKeyTree("Performance");
}
}
}
if (deleteCategoryKey)
serviceKey.DeleteSubKeyTree(categoryName);
}
finally
{
if (serviceKey != null)
serviceKey.Close();
}
}
private static void DeleteTemporaryFiles()
{
try
{
File.Delete(IniFilePath);
}
catch
{
}
try
{
File.Delete(SymbolFilePath);
}
catch
{
}
}
// Ensures that the customCategoryTable is initialized and decides whether the category passed in
// 1) is a custom category
// 2) is a multi instance custom category
// The return value is whether the category is a custom category or not.
internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType)
{
RegistryKey key = null;
RegistryKey baseKey = null;
categoryType = PerformanceCounterCategoryType.Unknown;
Hashtable table =
_customCategoryTable ??
Interlocked.CompareExchange(ref _customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null) ??
_customCategoryTable;
if (table.ContainsKey(category))
{
categoryType = (PerformanceCounterCategoryType)table[category];
return true;
}
else
{
try
{
string keyPath = ServicePath + "\\" + category + "\\Performance";
if (_machineName == "." || string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase))
{
key = Registry.LocalMachine.OpenSubKey(keyPath);
}
else
{
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + _machineName);
if (baseKey != null)
{
try
{
key = baseKey.OpenSubKey(keyPath);
}
catch (SecurityException)
{
// we may not have permission to read the registry key on the remote machine. The security exception
// is thrown when RegOpenKeyEx returns ERROR_ACCESS_DENIED or ERROR_BAD_IMPERSONATION_LEVEL
//
// In this case we return an 'Unknown' category type and 'false' to indicate the category is *not* custom.
//
categoryType = PerformanceCounterCategoryType.Unknown;
lock (table)
{
table[category] = categoryType;
}
return false;
}
}
}
if (key != null)
{
object systemDllName = key.GetValue("Library", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (systemDllName != null && systemDllName is string
&& (string.Equals((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase)
|| ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase)))
{
object isMultiInstanceObject = key.GetValue("IsMultiInstance");
if (isMultiInstanceObject != null)
{
categoryType = (PerformanceCounterCategoryType)isMultiInstanceObject;
if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
categoryType = PerformanceCounterCategoryType.Unknown;
}
else
categoryType = PerformanceCounterCategoryType.Unknown;
object objectID = key.GetValue("First Counter");
if (objectID != null)
{
int firstID = (int)objectID;
lock (table)
{
table[category] = categoryType;
}
return true;
}
}
}
}
finally
{
if (key != null)
key.Close();
if (baseKey != null)
baseKey.Close();
}
}
return false;
}
internal static string[] GetCategories(string machineName)
{
PerformanceCounterLib library;
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machineName, culture);
string[] categories = library.GetCategories();
if (categories.Length != 0)
return categories;
culture = culture.Parent;
}
library = GetPerformanceCounterLib(machineName, new CultureInfo(EnglishLCID));
return library.GetCategories();
}
internal string[] GetCategories()
{
ICollection keys = CategoryTable.Keys;
string[] categories = new string[keys.Count];
keys.CopyTo(categories, 0);
return categories;
}
internal static string GetCategoryHelp(string machine, string category)
{
PerformanceCounterLib library;
string help;
//First check the current culture for the category. This will allow
//PerformanceCounterCategory.CategoryHelp to return localized strings.
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCategoryHelp(category);
if (help != null)
return help;
culture = culture.Parent;
}
}
//We did not find the category walking up the culture hierarchy. Try looking
// for the category in the default culture English.
library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
help = library.GetCategoryHelp(category);
if (help == null)
throw new InvalidOperationException(SR.MissingCategory);
return help;
}
private string GetCategoryHelp(string category)
{
CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
return (string)HelpTable[entry.HelpIndex];
}
internal static CategorySample GetCategorySample(string machine, string category)
{
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
CategorySample sample = library.GetCategorySample(category);
if (sample == null && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
sample = library.GetCategorySample(category);
if (sample != null)
return sample;
culture = culture.Parent;
}
}
if (sample == null)
throw new InvalidOperationException(SR.MissingCategory);
return sample;
}
private CategorySample GetCategorySample(string category)
{
CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
CategorySample sample = null;
byte[] dataRef = GetPerformanceData(entry.NameIndex.ToString(CultureInfo.InvariantCulture), usePool: true);
if (dataRef == null)
throw new InvalidOperationException(SR.Format(SR.CantReadCategory, category));
sample = new CategorySample(dataRef, entry, this);
return sample;
}
internal static string[] GetCounters(string machine, string category)
{
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
string[] counters = library.GetCounters(category, ref categoryExists);
if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
counters = library.GetCounters(category, ref categoryExists);
if (categoryExists)
return counters;
culture = culture.Parent;
}
}
if (!categoryExists)
throw new InvalidOperationException(SR.MissingCategory);
return counters;
}
private string[] GetCounters(string category, ref bool categoryExists)
{
categoryExists = false;
CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
else
categoryExists = true;
int index2 = 0;
string[] counters = new string[entry.CounterIndexes.Length];
for (int index = 0; index < counters.Length; ++index)
{
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)NameTable[counterIndex];
if (counterName != null && counterName != string.Empty)
{
counters[index2] = counterName;
++index2;
}
}
//Lets adjust the array in case there were null entries
if (index2 < counters.Length)
{
string[] adjustedCounters = new string[index2];
Array.Copy(counters, adjustedCounters, index2);
counters = adjustedCounters;
}
return counters;
}
internal static string GetCounterHelp(string machine, string category, string counter)
{
PerformanceCounterLib library;
bool categoryExists = false;
string help;
//First check the current culture for the counter. This will allow
//PerformanceCounter.CounterHelp to return localized strings.
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCounterHelp(category, counter, ref categoryExists);
if (categoryExists)
return help;
culture = culture.Parent;
}
}
//We did not find the counter walking up the culture hierarchy. Try looking
// for the counter in the default culture English.
library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
help = library.GetCounterHelp(category, counter, ref categoryExists);
if (!categoryExists)
throw new InvalidOperationException(SR.Format(SR.MissingCategoryDetail, category));
return help;
}
private string GetCounterHelp(string category, string counter, ref bool categoryExists)
{
categoryExists = false;
CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
else
categoryExists = true;
int helpIndex = -1;
for (int index = 0; index < entry.CounterIndexes.Length; ++index)
{
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)NameTable[counterIndex];
if (counterName == null)
counterName = string.Empty;
if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase))
{
helpIndex = entry.HelpIndexes[index];
break;
}
}
if (helpIndex == -1)
throw new InvalidOperationException(SR.Format(SR.MissingCounter, counter));
string help = (string)HelpTable[helpIndex];
if (help == null)
return string.Empty;
else
return help;
}
private static string[] GetLanguageIds()
{
RegistryKey libraryParentKey = null;
string[] ids = Array.Empty<string>();
try
{
libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath);
if (libraryParentKey != null)
ids = libraryParentKey.GetSubKeyNames();
}
finally
{
if (libraryParentKey != null)
libraryParentKey.Close();
}
return ids;
}
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
{
string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
machineName = (machineName == "." ? ComputerName : machineName).ToLowerInvariant();
//race with CloseAllLibraries
lock (InternalSyncObject)
{
if (PerformanceCounterLib.s_libraryTable == null)
PerformanceCounterLib.s_libraryTable = new Hashtable();
string libraryKey = machineName + ":" + lcidString;
if (PerformanceCounterLib.s_libraryTable.Contains(libraryKey))
return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey];
else
{
PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
PerformanceCounterLib.s_libraryTable[libraryKey] = library;
return library;
}
}
}
internal byte[] GetPerformanceData(string item, bool usePool = false)
{
if (_performanceMonitor == null)
{
lock (InternalSyncObject)
{
if (_performanceMonitor == null)
_performanceMonitor = new PerformanceMonitor(_machineName);
}
}
return _performanceMonitor.GetData(item, usePool);
}
internal void ReleasePerformanceData(byte[] data)
{
_performanceMonitor.ReleaseData(data);
}
private Hashtable GetStringTable(bool isHelp)
{
Hashtable stringTable;
RegistryKey libraryKey;
if (string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase))
libraryKey = Registry.PerformanceData;
else
{
libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
}
try
{
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// In some stress situations, querying counter values from
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009
// often returns null/empty data back. We should build fault-tolerance logic to
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
while (waitRetries > 0)
{
try
{
if (!isHelp)
names = (string[])libraryKey.GetValue("Counter " + _perfLcid);
else
names = (string[])libraryKey.GetValue("Explain " + _perfLcid);
if ((names == null) || (names.Length == 0))
{
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
else
break;
}
catch (IOException)
{
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
catch (InvalidCastException)
{
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
break;
}
}
if (names == null)
stringTable = new Hashtable();
else
{
stringTable = new Hashtable(names.Length / 2);
for (int index = 0; index < (names.Length / 2); ++index)
{
string nameString = names[(index * 2) + 1];
if (nameString == null)
nameString = string.Empty;
int key;
if (!int.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
{
if (isHelp)
{
// Category Help Table
throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2]));
}
else
{
// Counter Name Table
throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2]));
}
}
stringTable[key] = nameString;
}
}
}
finally
{
libraryKey.Close();
}
return stringTable;
}
internal static bool IsCustomCategory(string machine, string category)
{
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (library.IsCustomCategory(category))
return true;
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
if (library.IsCustomCategory(category))
return true;
culture = culture.Parent;
}
}
return false;
}
internal static bool IsBaseCounter(int type)
{
return (type == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_LARGE_RAW_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_BASE);
}
private bool IsCustomCategory(string category)
{
PerformanceCounterCategoryType categoryType;
return FindCustomCategory(category, out categoryType);
}
internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category)
{
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (!library.FindCustomCategory(category, out categoryType))
{
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
{
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
library = GetPerformanceCounterLib(machine, culture);
if (library.FindCustomCategory(category, out categoryType))
return categoryType;
culture = culture.Parent;
}
}
}
return categoryType;
}
internal static void RegisterCategory(string categoryName, PerformanceCounterCategoryType categoryType, string categoryHelp, CounterCreationDataCollection creationData)
{
try
{
bool iniRegistered = false;
CreateRegistryEntry(categoryName, categoryType, creationData, ref iniRegistered);
if (!iniRegistered)
{
string[] languageIds = GetLanguageIds();
CreateIniFile(categoryName, categoryHelp, creationData, languageIds);
CreateSymbolFile(creationData);
RegisterFiles(IniFilePath, false);
}
CloseAllTables();
CloseAllLibraries();
}
finally
{
DeleteTemporaryFiles();
}
}
private static void RegisterFiles(string arg0, bool unregister)
{
Process p;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.ErrorDialog = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.WorkingDirectory = Environment.SystemDirectory;
if (unregister)
processStartInfo.FileName = Environment.SystemDirectory + "\\unlodctr.exe";
else
processStartInfo.FileName = Environment.SystemDirectory + "\\lodctr.exe";
int res = 0;
try
{
processStartInfo.Arguments = "\"" + arg0 + "\"";
p = Process.Start(processStartInfo);
p.WaitForExit();
res = p.ExitCode;
}
finally
{
}
if (res == Interop.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException(SR.Format(SR.CantChangeCategoryRegistration, arg0));
}
// Look at Q269225, unlodctr might return 2 when WMI is not installed.
if (unregister && res == 2)
res = 0;
if (res != 0)
throw new Win32Exception(res);
}
internal static void UnregisterCategory(string categoryName)
{
RegisterFiles(categoryName, true);
DeleteRegistryEntry(categoryName);
CloseAllTables();
CloseAllLibraries();
}
}
internal class PerformanceMonitor
{
private PerformanceDataRegistryKey perfDataKey = null;
private string machineName;
internal PerformanceMonitor(string machineName)
{
this.machineName = machineName;
Init();
}
private void Init()
{
try
{
if (machineName != "." && !string.Equals(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
{
perfDataKey = PerformanceDataRegistryKey.OpenRemoteBaseKey(machineName);
}
else
perfDataKey = PerformanceDataRegistryKey.OpenLocal();
}
catch (UnauthorizedAccessException)
{
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(Interop.Errors.ERROR_ACCESS_DENIED);
}
catch (IOException e)
{
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(Marshal.GetHRForException(e));
}
}
internal void Close()
{
if (perfDataKey != null)
perfDataKey.Close();
perfDataKey = null;
}
// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
// ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the
// wait loop and switch case below). We want to wait most certainly more than a 2min window.
// The curent wait time of up to 10mins takes care of the known stress deadlock issues. In most
// cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
internal byte[] GetData(string item, bool usePool)
{
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
int error = 0;
// no need to revert here since we'll fall off the end of the method
while (waitRetries > 0)
{
try
{
data = perfDataKey.GetValue(item, usePool);
return data;
}
catch (IOException e)
{
error = Marshal.GetHRForException(e);
switch (error)
{
case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED:
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE:
Init();
goto case Interop.Kernel32.WAIT_TIMEOUT;
case Interop.Kernel32.WAIT_TIMEOUT:
case Interop.Errors.ERROR_NOT_READY:
case Interop.Errors.ERROR_LOCK_FAILED:
case Interop.Errors.ERROR_BUSY:
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
break;
default:
throw new Win32Exception(error);
}
}
catch (InvalidCastException e)
{
throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, perfDataKey.ToString()), e);
}
}
throw new Win32Exception(error);
}
internal void ReleaseData(byte[] data)
{
perfDataKey.ReleaseData(data);
}
}
internal class CategoryEntry
{
internal int NameIndex;
internal int HelpIndex;
internal int[] CounterIndexes;
internal int[] HelpIndexes;
internal CategoryEntry(in PERF_OBJECT_TYPE perfObject)
{
NameIndex = perfObject.ObjectNameTitleIndex;
HelpIndex = perfObject.ObjectHelpTitleIndex;
CounterIndexes = new int[perfObject.NumCounters];
HelpIndexes = new int[perfObject.NumCounters];
}
}
internal sealed class CategorySample : IDisposable
{
internal readonly long _systemFrequency;
internal readonly long _timeStamp;
internal readonly long _timeStamp100nSec;
internal readonly long _counterFrequency;
internal readonly long _counterTimeStamp;
internal Hashtable _counterTable;
internal Hashtable _instanceNameTable;
internal bool _isMultiInstance;
private CategoryEntry _entry;
private PerformanceCounterLib _library;
private bool _disposed;
private byte[] _data;
internal CategorySample(byte[] rawData, CategoryEntry entry, PerformanceCounterLib library)
{
_data = rawData;
ReadOnlySpan<byte> data = rawData;
_entry = entry;
_library = library;
int categoryIndex = entry.NameIndex;
ref readonly PERF_DATA_BLOCK dataBlock = ref MemoryMarshal.AsRef<PERF_DATA_BLOCK>(data);
_systemFrequency = dataBlock.PerfFreq;
_timeStamp = dataBlock.PerfTime;
_timeStamp100nSec = dataBlock.PerfTime100nSec;
int pos = dataBlock.HeaderLength;
int numPerfObjects = dataBlock.NumObjectTypes;
if (numPerfObjects == 0)
{
_counterTable = new Hashtable();
_instanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
return;
}
//Need to find the right category, GetPerformanceData might return
//several of them.
bool foundCategory = false;
for (int index = 0; index < numPerfObjects; index++)
{
ref readonly PERF_OBJECT_TYPE perfObjectType = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
if (perfObjectType.ObjectNameTitleIndex == categoryIndex)
{
foundCategory = true;
break;
}
pos += perfObjectType.TotalByteLength;
}
if (!foundCategory)
throw new InvalidOperationException(SR.Format(SR.CantReadCategoryIndex, categoryIndex.ToString()));
ref readonly PERF_OBJECT_TYPE perfObject = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
_counterFrequency = perfObject.PerfFreq;
_counterTimeStamp = perfObject.PerfTime;
int counterNumber = perfObject.NumCounters;
int instanceNumber = perfObject.NumInstances;
if (instanceNumber == -1)
_isMultiInstance = false;
else
_isMultiInstance = true;
// Move pointer forward to end of PERF_OBJECT_TYPE
pos += perfObject.HeaderLength;
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
_counterTable = new Hashtable(counterNumber);
for (int index = 0; index < samples.Length; ++index)
{
ref readonly PERF_COUNTER_DEFINITION perfCounter = ref MemoryMarshal.AsRef<PERF_COUNTER_DEFINITION>(data.Slice(pos));
samples[index] = new CounterDefinitionSample(in perfCounter, this, instanceNumber);
pos += perfCounter.ByteLength;
int currentSampleType = samples[index]._counterType;
if (!PerformanceCounterLib.IsBaseCounter(currentSampleType))
{
// We'll put only non-base counters in the table.
if (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_NODATA)
_counterTable[samples[index]._nameIndex] = samples[index];
}
else
{
// it's a base counter, try to hook it up to the main counter.
Debug.Assert(index > 0, "Index > 0 because base counters should never be at index 0");
if (index > 0)
samples[index - 1]._baseCounterDefinitionSample = samples[index];
}
}
// now set up the InstanceNameTable.
if (!_isMultiInstance)
{
_instanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
_instanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0;
for (int index = 0; index < samples.Length; ++index)
{
samples[index].SetInstanceValue(0, data.Slice(pos));
}
}
else
{
string[] parentInstanceNames = null;
_instanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < instanceNumber; i++)
{
ref readonly PERF_INSTANCE_DEFINITION perfInstance = ref MemoryMarshal.AsRef<PERF_INSTANCE_DEFINITION>(data.Slice(pos));
if (perfInstance.ParentObjectTitleIndex > 0 && parentInstanceNames == null)
parentInstanceNames = GetInstanceNamesFromIndex(perfInstance.ParentObjectTitleIndex);
string instanceName = PERF_INSTANCE_DEFINITION.GetName(in perfInstance, data.Slice(pos)).ToString();
if (parentInstanceNames != null && perfInstance.ParentObjectInstance >= 0 && perfInstance.ParentObjectInstance < parentInstanceNames.Length - 1)
instanceName = parentInstanceNames[perfInstance.ParentObjectInstance] + "/" + instanceName;
//In some cases instance names are not unique (Process), same as perfmon
//generate a unique name.
string newInstanceName = instanceName;
int newInstanceNumber = 1;
while (true)
{
if (!_instanceNameTable.ContainsKey(newInstanceName))
{
_instanceNameTable[newInstanceName] = i;
break;
}
else
{
newInstanceName = instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture);
++newInstanceNumber;
}
}
pos += perfInstance.ByteLength;
for (int index = 0; index < samples.Length; ++index)
samples[index].SetInstanceValue(i, data.Slice(pos));
pos += MemoryMarshal.AsRef<PERF_COUNTER_BLOCK>(data.Slice(pos)).ByteLength;
}
}
}
internal string[] GetInstanceNamesFromIndex(int categoryIndex)
{
CheckDisposed();
ReadOnlySpan<byte> data = _library.GetPerformanceData(categoryIndex.ToString(CultureInfo.InvariantCulture));
ref readonly PERF_DATA_BLOCK dataBlock = ref MemoryMarshal.AsRef<PERF_DATA_BLOCK>(data);
int pos = dataBlock.HeaderLength;
int numPerfObjects = dataBlock.NumObjectTypes;
bool foundCategory = false;
for (int index = 0; index < numPerfObjects; index++)
{
ref readonly PERF_OBJECT_TYPE type = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
if (type.ObjectNameTitleIndex == categoryIndex)
{
foundCategory = true;
break;
}
pos += type.TotalByteLength;
}
if (!foundCategory)
return Array.Empty<string>();
ref readonly PERF_OBJECT_TYPE perfObject = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
int counterNumber = perfObject.NumCounters;
int instanceNumber = perfObject.NumInstances;
pos += perfObject.HeaderLength;
if (instanceNumber == -1)
return Array.Empty<string>();
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
for (int index = 0; index < samples.Length; ++index)
{
pos += MemoryMarshal.AsRef<PERF_COUNTER_DEFINITION>(data.Slice(pos)).ByteLength;
}
string[] instanceNames = new string[instanceNumber];
for (int i = 0; i < instanceNumber; i++)
{
ref readonly PERF_INSTANCE_DEFINITION perfInstance = ref MemoryMarshal.AsRef<PERF_INSTANCE_DEFINITION>(data.Slice(pos));
instanceNames[i] = PERF_INSTANCE_DEFINITION.GetName(in perfInstance, data.Slice(pos)).ToString();
pos += perfInstance.ByteLength;
pos += MemoryMarshal.AsRef<PERF_COUNTER_BLOCK>(data.Slice(pos)).ByteLength;
}
return instanceNames;
}
internal CounterDefinitionSample GetCounterDefinitionSample(string counter)
{
CheckDisposed();
for (int index = 0; index < _entry.CounterIndexes.Length; ++index)
{
int counterIndex = _entry.CounterIndexes[index];
string counterName = (string)_library.NameTable[counterIndex];
if (counterName != null)
{
if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase))
{
CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex];
if (sample == null)
{
//This is a base counter and has not been added to the table
foreach (CounterDefinitionSample multiSample in _counterTable.Values)
{
if (multiSample._baseCounterDefinitionSample != null &&
multiSample._baseCounterDefinitionSample._nameIndex == counterIndex)
return multiSample._baseCounterDefinitionSample;
}
throw new InvalidOperationException(SR.CounterLayout);
}
return sample;
}
}
}
throw new InvalidOperationException(SR.Format(SR.CantReadCounter, counter));
}
internal InstanceDataCollectionCollection ReadCategory()
{
#pragma warning disable 618
InstanceDataCollectionCollection data = new InstanceDataCollectionCollection();
#pragma warning restore 618
for (int index = 0; index < _entry.CounterIndexes.Length; ++index)
{
int counterIndex = _entry.CounterIndexes[index];
string name = (string)_library.NameTable[counterIndex];
if (name != null && name != string.Empty)
{
CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex];
if (sample != null)
//If the current index refers to a counter base,
//the sample will be null
data.Add(name, sample.ReadInstanceData(name));
}
}
return data;
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_library.ReleasePerformanceData(_data);
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(SR.ObjectDisposed_CategorySampleClosed, nameof(CategorySample));
}
}
}
internal class CounterDefinitionSample
{
internal readonly int _nameIndex;
internal readonly int _counterType;
internal CounterDefinitionSample _baseCounterDefinitionSample;
private readonly int _size;
private readonly int _offset;
private long[] _instanceValues;
private CategorySample _categorySample;
internal CounterDefinitionSample(in PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber)
{
_nameIndex = perfCounter.CounterNameTitleIndex;
_counterType = perfCounter.CounterType;
_offset = perfCounter.CounterOffset;
_size = perfCounter.CounterSize;
if (instanceNumber == -1)
{
_instanceValues = new long[1];
}
else
_instanceValues = new long[instanceNumber];
_categorySample = categorySample;
}
private long ReadValue(ReadOnlySpan<byte> data)
{
if (_size == 4)
{
return (long)MemoryMarshal.Read<uint>(data.Slice(_offset));
}
else if (_size == 8)
{
return MemoryMarshal.Read<long>(data.Slice(_offset));
}
return -1;
}
internal CounterSample GetInstanceValue(string instanceName)
{
if (!_categorySample._instanceNameTable.ContainsKey(instanceName))
{
// Our native dll truncates instance names to 128 characters. If we can't find the instance
// with the full name, try truncating to 128 characters.
if (instanceName.Length > SharedPerformanceCounter.InstanceNameMaxLength)
instanceName = instanceName.Substring(0, SharedPerformanceCounter.InstanceNameMaxLength);
if (!_categorySample._instanceNameTable.ContainsKey(instanceName))
throw new InvalidOperationException(SR.Format(SR.CantReadInstance, instanceName));
}
int index = (int)_categorySample._instanceNameTable[instanceName];
long rawValue = _instanceValues[index];
long baseValue = 0;
if (_baseCounterDefinitionSample != null)
{
CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample;
int baseIndex = (int)baseCategorySample._instanceNameTable[instanceName];
baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex];
}
return new CounterSample(rawValue,
baseValue,
_categorySample._counterFrequency,
_categorySample._systemFrequency,
_categorySample._timeStamp,
_categorySample._timeStamp100nSec,
(PerformanceCounterType)_counterType,
_categorySample._counterTimeStamp);
}
internal InstanceDataCollection ReadInstanceData(string counterName)
{
#pragma warning disable 618
InstanceDataCollection data = new InstanceDataCollection(counterName);
#pragma warning restore 618
string[] keys = new string[_categorySample._instanceNameTable.Count];
_categorySample._instanceNameTable.Keys.CopyTo(keys, 0);
int[] indexes = new int[_categorySample._instanceNameTable.Count];
_categorySample._instanceNameTable.Values.CopyTo(indexes, 0);
for (int index = 0; index < keys.Length; ++index)
{
long baseValue = 0;
if (_baseCounterDefinitionSample != null)
{
CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample;
int baseIndex = (int)baseCategorySample._instanceNameTable[keys[index]];
baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex];
}
CounterSample sample = new CounterSample(_instanceValues[indexes[index]],
baseValue,
_categorySample._counterFrequency,
_categorySample._systemFrequency,
_categorySample._timeStamp,
_categorySample._timeStamp100nSec,
(PerformanceCounterType)_counterType,
_categorySample._counterTimeStamp);
data.Add(keys[index], new InstanceData(keys[index], sample));
}
return data;
}
internal CounterSample GetSingleValue()
{
long rawValue = _instanceValues[0];
long baseValue = 0;
if (_baseCounterDefinitionSample != null)
baseValue = _baseCounterDefinitionSample._instanceValues[0];
return new CounterSample(rawValue,
baseValue,
_categorySample._counterFrequency,
_categorySample._systemFrequency,
_categorySample._timeStamp,
_categorySample._timeStamp100nSec,
(PerformanceCounterType)_counterType,
_categorySample._counterTimeStamp);
}
internal void SetInstanceValue(int index, ReadOnlySpan<byte> data)
{
long rawValue = ReadValue(data);
_instanceValues[index] = rawValue;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Gdal
// Description: This is a data extension for the System.Spatial framework.
// ********************************************************************************************************
// The contents of this file are subject to the Gnu Lesser General Public License (LGPL)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from a plugin for MapWindow version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 12/10/2008 11:32:21 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// | Name | Date | Comments
// |-------------------|-------------|-------------------------------------------------------------------
// |Ben tidyup Tombs |18/11/2010 | Modified to add GDAL Helper class GdalHelper.Configure use for initialization of the GDAL Environment
// ********************************************************************************************************
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using OSGeo.GDAL;
namespace DotSpatial.Data.Rasters.GdalExtension
{
/// <summary>
/// gdalImage
/// </summary>
public class GdalImageSource : IImageSource
{
#region Private Variables
Band _alpha;
Band _blue;
private RasterBounds _bounds;
Dataset _dataset;
private string _fileName;
Band _green;
private int _numOverviews;
Band _red;
#endregion
#region Constructors
static GdalImageSource()
{
GdalConfiguration.ConfigureGdal();
}
/// <summary>
/// Creates a new instance of gdalImage, and gets much of the header information without actually
/// reading any values from the file.
/// </summary>
public GdalImageSource(string fileName)
{
Filename = fileName;
ReadHeader();
}
/// <summary>
/// Creates a new instance of gdalImage
/// </summary>
public GdalImageSource()
{
}
/// <summary>
/// Gets or sets the bounds
/// </summary>
public RasterBounds Bounds
{
get { return _bounds; }
set { _bounds = value; }
}
/// <summary>
/// Gets the number of rows
/// </summary>
public int NumRows
{
get
{
return _bounds != null ? _bounds.NumRows : 0;
}
}
/// <summary>
/// Gets the total number of columns
/// </summary>
public int NumColumns
{
get
{
return _bounds != null ? _bounds.NumColumns : 0;
}
}
#endregion
#region Methods
/// <summary>
/// Gets the number of overviews, not counting the original image.
/// </summary>
/// <returns>The number of overviews.</returns>
public int NumOverviews
{
get
{
return _numOverviews;
}
}
/// <summary>
/// Returns the data from the file in the form of ARGB bytes, regardless of how the image
/// data is actually stored in the file.
/// </summary>
/// <param name="startRow">The zero based integer index of the first row (Y)</param>
/// <param name="startColumn">The zero based integer index of the first column (X)</param>
/// <param name="numRows">The number of rows to read</param>
/// <param name="numColumns">The number of columns to read</param>
/// <param name="overview">The integer overview. 0 for the original image. Each successive index divides the length and height in half. </param>
/// <returns>A Byte of values in ARGB order and in row-major raster-scan sequence</returns>
public byte[] ReadWindow(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
EnsureDatasetOpen();
_red = _dataset.GetRasterBand(1);
byte[] result = null;
if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
{
result = ReadPaletteBuffered(startRow, startColumn, numRows, numColumns, overview);
}
if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
{
result = ReadGrayIndex(startRow, startColumn, numRows, numColumns, overview);
}
if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_RedBand)
{
result = ReadRgb(startRow, startColumn, numRows, numColumns, overview);
}
if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_AlphaBand)
{
result = ReadArgb(startRow, startColumn, numRows, numColumns, overview);
}
return result;
}
/// <summary>
/// This returns the window of data as a bitmap.
/// </summary>
/// <param name="startRow">The zero based integer index of the first row (Y).</param>
/// <param name="startColumn">The zero based integer index of the first column (X).</param>
/// <param name="numRows">The number of rows to read.</param>
/// <param name="numColumns">The number of columns to read.</param>
/// <param name="overview">The integer overview. 0 for the original image. Each successive index divides the length and height in half. </param>
/// <returns>The bitmap representation for the specified portion of the raster.</returns>
public Bitmap GetBitmap(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
byte[] vals = ReadWindow(startRow, startColumn, numRows, numColumns, overview);
Bitmap bmp = new Bitmap(numRows, numColumns);
BitmapData bData = bmp.LockBits(new Rectangle(0, 0, numColumns, numRows), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
//int stride = bData.Stride;
Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
bmp.UnlockBits(bData);
return bmp;
}
/// <summary>
/// Gets the size of the whole image, but doesn't keep the image open unless it was already open.
/// </summary>
private void ReadHeader()
{
EnsureDatasetOpen();
double[] test = new double[6];
_dataset.GetGeoTransform(test);
Bounds = new RasterBounds(_dataset.RasterYSize, _dataset.RasterXSize, test);
_red = _dataset.GetRasterBand(1);
_numOverviews = _red.GetOverviewCount();
Close();
}
/// <summary>
///
/// </summary>
public void Close()
{
_dataset.Dispose();
_dataset = null;
}
/// <summary>
/// Gets the dimensions of the original (0) plus any overlays.
/// The overlays get smaller as the index gets larger..
/// </summary>
/// <returns></returns>
public Size[] GetSizes()
{
EnsureDatasetOpen();
_red = _dataset.GetRasterBand(1);
int numOverviews = _red.GetOverviewCount();
Debug.WriteLine("Num overviews:" + numOverviews);
if (numOverviews == 0) return null;
Size[] result = new Size[numOverviews + 1];
result[0] = new Size(_red.XSize, _red.YSize);
for (int i = 0; i < numOverviews; i++)
{
Band temp = _red.GetOverview(i);
result[i + 1] = new Size(temp.XSize, temp.YSize);
}
return result;
}
private void EnsureDatasetOpen()
{
if (_dataset == null)
{
_dataset = Helpers.Open(Filename);
}
}
/// <summary>
/// Disposes the dataset
/// </summary>
public void Dispose()
{
_dataset.Dispose();
_dataset = null;
}
#endregion
#region Properties
#endregion
/// <summary>
/// Gets or sets the fileName of the image source
/// </summary>
public string Filename
{
get { return _fileName; }
set { _fileName = value; }
}
/// <summary>
/// Returns ARGB 32 bpp regardless of the fact that the original is palette buffered.
/// </summary>
private byte[] ReadPaletteBuffered(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
ColorTable ct = _red.GetRasterColorTable();
if (ct == null)
{
throw new GdalException("Image was stored with a palette interpretation but has no color table.");
}
if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
{
throw new GdalException("Only RGB palette interpreation is currently supported by this plugin, " + ct.GetPaletteInterpretation() + " is not supported.");
}
int width = numRows;
int height = numColumns;
byte[] r = new byte[width * height];
_red.ReadRaster(startColumn, startRow, numColumns, numRows, r, width, height, 0, 0);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
}
const int bpp = 4;
byte[] vals = new byte[width * height * 4];
byte[][] colorTable = new byte[256][];
for (int i = 0; i < 255; i++)
{
ColorEntry ce = ct.GetColorEntry(i);
colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 };
}
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
Array.Copy(colorTable[r[col + row * width]], 0, vals, row * width + col * bpp, 4);
}
}
return vals;
}
private byte[] ReadGrayIndex(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
int width = numColumns;
int height = numRows;
byte[] r = new byte[width * height];
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
}
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[row * width * bpp + col * bpp] = r[row * width + col];
vals[row * width * bpp + col * bpp + 1] = r[row * width + col];
vals[row * width * bpp + col * bpp + 2] = r[row * width + col];
vals[row * width * bpp + col * bpp + 3] = 255;
}
}
return vals;
}
private byte[] ReadRgb(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
if (_dataset.RasterCount < 3)
{
throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
}
_green = _dataset.GetRasterBand(2);
_blue = _dataset.GetRasterBand(3);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
_green = _green.GetOverview(overview - 1);
_blue = _blue.GetOverview(overview - 1);
}
int width = numColumns;
int height = numRows;
byte[] r = new byte[width * height];
byte[] g = new byte[width * height];
byte[] b = new byte[width * height];
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
_green.ReadRaster(startColumn, startRow, width, height, g, width, height, 0, 0);
_blue.ReadRaster(startColumn, startRow, width, height, b, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[row * width * bpp + col * bpp] = b[row * width + col];
vals[row * width * bpp + col * bpp + 1] = g[row * width + col];
vals[row * width * bpp + col * bpp + 2] = r[row * width + col];
vals[row * width * bpp + col * bpp + 3] = 255;
}
}
return vals;
}
private byte[] ReadArgb(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
if (_dataset.RasterCount < 4)
{
throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
}
_alpha = _red;
_red = _dataset.GetRasterBand(2);
_green = _dataset.GetRasterBand(3);
_blue = _dataset.GetRasterBand(4);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
_alpha = _alpha.GetOverview(overview - 1);
_green = _green.GetOverview(overview - 1);
_blue = _blue.GetOverview(overview - 1);
}
int width = numColumns;
int height = numRows;
byte[] a = new byte[width * height];
byte[] r = new byte[width * height];
byte[] g = new byte[width * height];
byte[] b = new byte[width * height];
_alpha.ReadRaster(startColumn, startRow, width, height, a, width, height, 0, 0);
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
_green.ReadRaster(startColumn, startRow, width, height, g, width, height, 0, 0);
_blue.ReadRaster(startColumn, startRow, width, height, b, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[row * width * bpp + col * bpp] = b[row * width + col];
vals[row * width * bpp + col * bpp + 1] = g[row * width + col];
vals[row * width * bpp + col * bpp + 2] = r[row * width + col];
vals[row * width * bpp + col * bpp + 3] = a[row * width + col];
}
}
return vals;
}
}
}
| |
// 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.Compute.Fluent
{
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Models;
using Network.Fluent;
using ResourceManager.Fluent.Core;
using Rest.Azure;
using Storage.Fluent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// The implementation for VirtualMachineScaleSets.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVTY2FsZVNldHNJbXBs
internal partial class VirtualMachineScaleSetsImpl :
TopLevelModifiableResources<
IVirtualMachineScaleSet,
VirtualMachineScaleSetImpl,
VirtualMachineScaleSetInner,
IVirtualMachineScaleSetsOperations,
IComputeManager>,
IVirtualMachineScaleSets
{
private IStorageManager storageManager;
private INetworkManager networkManager;
private IGraphRbacManager rbacManager;
///GENMHASH:D153EE3A7098DCC0FDE502B79387242D:20D58C6F0677BACCE2BBFE4994C6C570
internal VirtualMachineScaleSetsImpl(
IComputeManager computeManager,
IStorageManager storageManager,
INetworkManager networkManager,
IGraphRbacManager rbacManager) : base(computeManager.Inner.VirtualMachineScaleSets, computeManager)
{
this.storageManager = storageManager;
this.networkManager = networkManager;
this.rbacManager = rbacManager;
}
public RunCommandResultInner RunCommandInVMInstance(string groupName, string scaleSetName, string vmId, RunCommandInput inputCommand)
{
return Extensions.Synchronize(() => RunCommandVMInstanceAsync(groupName, scaleSetName, vmId, inputCommand));
}
public async Task<Models.RunCommandResultInner> RunCommandVMInstanceAsync(string groupName, string scaleSetName, string vmId, RunCommandInput inputCommand, CancellationToken cancellationToken = default(CancellationToken))
{
return await this.Manager.Inner.VirtualMachineScaleSetVMs.RunCommandAsync(groupName, scaleSetName, vmId, inputCommand, cancellationToken);
}
public RunCommandResultInner RunPowerShellScriptInVMInstance(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters)
{
return Extensions.Synchronize(() => RunPowerShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters));
}
public async Task<Models.RunCommandResultInner> RunPowerShellScriptInVMInstanceAsync(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken))
{
var inputCommand = new RunCommandInput
{
CommandId = "RunPowerShellScript",
Script = scriptLines,
Parameters = scriptParameters
};
return await this.RunCommandVMInstanceAsync(groupName, scaleSetName, vmId, inputCommand, cancellationToken);
}
public RunCommandResultInner RunShellScriptInVMInstance(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters)
{
return Extensions.Synchronize(() => RunShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters));
}
public async Task<Models.RunCommandResultInner> RunShellScriptInVMInstanceAsync(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken))
{
var inputCommand = new RunCommandInput
{
CommandId = "RunShellScript",
Script = scriptLines,
Parameters = scriptParameters
};
return await this.RunCommandVMInstanceAsync(groupName, scaleSetName, vmId, inputCommand, cancellationToken);
}
///GENMHASH:95834C6C7DA388E666B705A62A7D02BF:3953AC722DFFCDF40E1EEF787AFD1326
protected async override Task<IPage<VirtualMachineScaleSetInner>> ListInnerByGroupAsync(string groupName, CancellationToken cancellationToken)
{
return await Inner.ListAsync(groupName, cancellationToken);
}
protected async override Task<IPage<VirtualMachineScaleSetInner>> ListInnerByGroupNextAsync(string nextLink, CancellationToken cancellationToken)
{
return await Inner.ListNextAsync(nextLink, cancellationToken);
}
///GENMHASH:7D6013E8B95E991005ED921F493EFCE4:36E25639805611CF89054C004B22BB15
protected async override Task<IPage<VirtualMachineScaleSetInner>> ListInnerAsync(CancellationToken cancellationToken)
{
return await Inner.ListAllAsync(cancellationToken);
}
protected async override Task<IPage<VirtualMachineScaleSetInner>> ListInnerNextAsync(string nextLink, CancellationToken cancellationToken)
{
return await Inner.ListAllNextAsync(nextLink, cancellationToken);
}
///GENMHASH:0679DF8CA692D1AC80FC21655835E678:B9B028D620AC932FDF66D2783E476B0D
protected async override Task DeleteInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
{
await Inner.DeleteAsync(groupName, name, cancellationToken);
}
///GENMHASH:AB63F782DA5B8D22523A284DAD664D17:7C0A1D0C3FE28C45F35B565F4AFF751D
protected async override Task<VirtualMachineScaleSetInner> GetInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
{
return await Inner.GetAsync(groupName, name, cancellationToken);
}
///GENMHASH:2048E8AC80AC022225C462CE7FD14A6F:AB513A3D7E5B1192B76F853CB23CBB12
public async Task DeallocateAsync(string groupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner.DeallocateAsync(groupName, name, cancellationToken: cancellationToken);
}
///GENMHASH:2048E8AC80AC022225C462CE7FD14A6F:AB513A3D7E5B1192B76F853CB23CBB12
public void Deallocate(string groupName, string name)
{
Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Inner.DeallocateAsync(groupName, name));
}
///GENMHASH:9F1310A4445A183902C9AF672DA34354:F32BEF843CE33ABB858763CFD92B9A36
public async Task PowerOffAsync(string groupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner.PowerOffAsync(groupName, name, cancellationToken: cancellationToken);
}
///GENMHASH:9F1310A4445A183902C9AF672DA34354:F32BEF843CE33ABB858763CFD92B9A36
public void PowerOff(string groupName, string name)
{
Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Inner.PowerOffAsync(groupName, name));
}
///GENMHASH:CD0E967F30C27C522C0DE3E4523C6CDD:8C9B139D9CD48BE89CACA8348E2E8469
public async Task RestartAsync(string groupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner.RestartAsync(groupName, name, cancellationToken: cancellationToken);
}
///GENMHASH:CD0E967F30C27C522C0DE3E4523C6CDD:8C9B139D9CD48BE89CACA8348E2E8469
public void Restart(string groupName, string name)
{
Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Inner.RestartAsync(groupName, name));
}
///GENMHASH:F5C1D0B90DEED77EE54F7CEB164C727E:4E2B451086A707DC66F26388A688071E
public async Task StartAsync(string groupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner.StartAsync(groupName, name, cancellationToken: cancellationToken);
}
///GENMHASH:F5C1D0B90DEED77EE54F7CEB164C727E:4E2B451086A707DC66F26388A688071E
public void Start(string groupName, string name)
{
Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Inner.StartAsync(groupName, name));
}
///GENMHASH:4DBD1302C1BE61E6004FB18DA868020B:A8445E32081DE89D5D3DAD2DAAFEFB2F
public async Task ReimageAsync(string groupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner.ReimageAsync(groupName, name, cancellationToken: cancellationToken);
}
///GENMHASH:4DBD1302C1BE61E6004FB18DA868020B:A8445E32081DE89D5D3DAD2DAAFEFB2F
public void Reimage(string groupName, string name)
{
Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Inner.ReimageAsync(groupName, name));
}
///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:AD7C28D26EC1F237B93E54AD31899691
public VirtualMachineScaleSetImpl Define(string name)
{
return WrapModel(name);
}
///GENMHASH:2FE8C4C2D5EAD7E37787838DE0B47D92:223E215FD844AD43E082687C4AC79625
protected override VirtualMachineScaleSetImpl WrapModel(string name)
{
VirtualMachineScaleSetInner inner = new VirtualMachineScaleSetInner
{
VirtualMachineProfile = new VirtualMachineScaleSetVMProfile
{
StorageProfile = new VirtualMachineScaleSetStorageProfile
{
OsDisk = new VirtualMachineScaleSetOSDisk
{
VhdContainers = new List<string>()
}
},
OsProfile = new VirtualMachineScaleSetOSProfile
{
},
NetworkProfile = new VirtualMachineScaleSetNetworkProfile
{
NetworkInterfaceConfigurations = new List<VirtualMachineScaleSetNetworkConfigurationInner>()
{
new VirtualMachineScaleSetNetworkConfigurationInner
{
Primary = true,
Name = "primary-nic-cfg",
IpConfigurations = new List<VirtualMachineScaleSetIPConfigurationInner>()
{
new VirtualMachineScaleSetIPConfigurationInner
{
Name = "primary-nic-ip-cfg"
}
}
}
}
}
}
};
return new VirtualMachineScaleSetImpl(
name,
inner,
Manager,
storageManager,
networkManager,
rbacManager);
}
///GENMHASH:02DED088A2888BB795F0F3D5DD74F4BD:5D05902D26BEABDC6406C636F9FE6823
protected override IVirtualMachineScaleSet WrapModel(VirtualMachineScaleSetInner inner)
{
return new VirtualMachineScaleSetImpl(
inner.Name,
inner,
Manager,
storageManager,
networkManager,
rbacManager);
}
}
}
| |
/*
* 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 NUnit.Framework;
using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary>Similarity unit test.
///
///
/// </summary>
/// <version> $Revision: 787772 $
/// </version>
[TestFixture]
public class TestSimilarity:LuceneTestCase
{
private class AnonymousClassCollector:Collector
{
public AnonymousClassCollector(TestSimilarity enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestSimilarity enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestSimilarity enclosingInstance;
public TestSimilarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Scorer scorer;
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public override void Collect(int doc)
{
Assert.IsTrue(scorer.Score() == 1.0f);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class AnonymousClassCollector1:Collector
{
public AnonymousClassCollector1(TestSimilarity enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestSimilarity enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestSimilarity enclosingInstance;
public TestSimilarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private int base_Renamed = 0;
private Scorer scorer;
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.IsTrue(scorer.Score() == (float) doc + base_Renamed + 1);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
base_Renamed = docBase;
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class AnonymousClassCollector2:Collector
{
public AnonymousClassCollector2(TestSimilarity enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestSimilarity enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestSimilarity enclosingInstance;
public TestSimilarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Scorer scorer;
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.IsTrue(scorer.Score() == 1.0f);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class AnonymousClassCollector3:Collector
{
public AnonymousClassCollector3(TestSimilarity enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestSimilarity enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestSimilarity enclosingInstance;
public TestSimilarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Scorer scorer;
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.IsTrue(scorer.Score() == 2.0f);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
[Serializable]
public class SimpleSimilarity:Similarity
{
public override float LengthNorm(System.String field, int numTerms)
{
return 1.0f;
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1.0f;
}
public override float Tf(float freq)
{
return freq;
}
public override float SloppyFreq(int distance)
{
return 2.0f;
}
public override float Idf(System.Collections.ICollection terms, Searcher searcher)
{
return 1.0f;
}
public override float Idf(int docFreq, int numDocs)
{
return 1.0f;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1.0f;
}
}
[Test]
public virtual void TestSimilarity_Renamed()
{
RAMDirectory store = new RAMDirectory();
IndexWriter writer = new IndexWriter(store, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetSimilarity(new SimpleSimilarity());
Document d1 = new Document();
d1.Add(new Field("field", "a c", Field.Store.YES, Field.Index.ANALYZED));
Document d2 = new Document();
d2.Add(new Field("field", "a b c", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(d1);
writer.AddDocument(d2);
writer.Optimize();
writer.Close();
Searcher searcher = new IndexSearcher(store);
searcher.SetSimilarity(new SimpleSimilarity());
Term a = new Term("field", "a");
Term b = new Term("field", "b");
Term c = new Term("field", "c");
searcher.Search(new TermQuery(b), new AnonymousClassCollector(this));
BooleanQuery bq = new BooleanQuery();
bq.Add(new TermQuery(a), BooleanClause.Occur.SHOULD);
bq.Add(new TermQuery(b), BooleanClause.Occur.SHOULD);
//System.out.println(bq.toString("field"));
searcher.Search(bq, new AnonymousClassCollector1(this));
PhraseQuery pq = new PhraseQuery();
pq.Add(a);
pq.Add(c);
//System.out.println(pq.toString("field"));
searcher.Search(pq, new AnonymousClassCollector2(this));
pq.SetSlop(2);
//System.out.println(pq.toString("field"));
searcher.Search(pq, new AnonymousClassCollector3(this));
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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.
*****************************************************************************/
// Contributed by: Mitch Thompson
#define SPINE_SKELETON_ANIMATOR
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using Spine;
namespace Spine.Unity.Editor {
/// <summary>
/// [SUPPORTS]
/// Linear, Constant, and Bezier Curves*
/// Inverse Kinematics*
/// Inherit Rotation
/// Translate Timeline
/// Rotate Timeline
/// Scale Timeline**
/// Event Timeline***
/// Attachment Timeline
///
/// RegionAttachment
/// MeshAttachment
/// SkinnedMeshAttachment
///
/// [LIMITATIONS]
/// *Inverse Kinematics & Bezier Curves are baked into the animation at 60fps and are not realtime. Use bakeIncrement constant to adjust key density if desired.
/// **Non-uniform Scale Keys (ie: if ScaleX and ScaleY are not equal to eachother, it will not be accurate to Spine source)
/// ***Events may only fire 1 type of data per event in Unity safely so priority to String data if present in Spine key, otherwise a Float is sent whether the Spine key was Int or Float with priority given to Int.
///
/// [DOES NOT SUPPORT]
/// FlipX or FlipY (Maybe one day)
/// FFD (Unity does not provide access to BlendShapes with code)
/// Color Keys (Maybe one day when Unity supports full FBX standard and provides access with code)
/// InheritScale (Never. Unity and Spine do scaling very differently)
/// Draw Order Keyframes
/// </summary>
public static class SkeletonBaker {
#region SkeletonAnimator's Mecanim Clips
#if SPINE_SKELETON_ANIMATOR
public static void GenerateMecanimAnimationClips (SkeletonDataAsset skeletonDataAsset) {
//skeletonDataAsset.Clear();
var data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
Debug.LogError("SkeletonData failed!", skeletonDataAsset);
return;
}
string dataPath = AssetDatabase.GetAssetPath(skeletonDataAsset);
string controllerPath = dataPath.Replace("_SkeletonData", "_Controller").Replace(".asset", ".controller");
UnityEditor.Animations.AnimatorController controller;
if (skeletonDataAsset.controller != null) {
controller = (UnityEditor.Animations.AnimatorController)skeletonDataAsset.controller;
controllerPath = AssetDatabase.GetAssetPath(controller);
} else {
if (File.Exists(controllerPath)) {
if (EditorUtility.DisplayDialog("Controller Overwrite Warning", "Unknown Controller already exists at: " + controllerPath, "Update", "Overwrite")) {
controller = (UnityEditor.Animations.AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController));
} else {
controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
} else {
controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
}
skeletonDataAsset.controller = controller;
EditorUtility.SetDirty(skeletonDataAsset);
UnityEngine.Object[] objs = AssetDatabase.LoadAllAssetsAtPath(controllerPath);
var unityAnimationClipTable = new Dictionary<string, AnimationClip>();
var spineAnimationTable = new Dictionary<string, Spine.Animation>();
foreach (var o in objs) {
//Debug.LogFormat("({0}){1} : {3} + {2} + {4}", o.GetType(), o.name, o.hideFlags, o.GetInstanceID(), o.GetHashCode());
// There is a bug in Unity 5.3.3 (and likely before) that creates
// a duplicate AnimationClip when you duplicate a Mecanim Animator State.
// These duplicates seem to be identifiable by their HideFlags, so we'll exclude them.
if (o is AnimationClip) {
var clip = o as AnimationClip;
if (!clip.HasFlag(HideFlags.HideInHierarchy)) {
if (unityAnimationClipTable.ContainsKey(clip.name)) {
Debug.LogWarningFormat("Duplicate AnimationClips were found named {0}", clip.name);
}
unityAnimationClipTable.Add(clip.name, clip);
}
}
}
foreach (var anim in data.Animations) {
string name = anim.Name;
spineAnimationTable.Add(name, anim);
if (unityAnimationClipTable.ContainsKey(name) == false) {
//generate new dummy clip
AnimationClip newClip = new AnimationClip();
newClip.name = name;
AssetDatabase.AddObjectToAsset(newClip, controller);
unityAnimationClipTable.Add(name, newClip);
}
AnimationClip clip = unityAnimationClipTable[name];
clip.SetCurve("", typeof(GameObject), "dummy", AnimationCurve.Linear(0, 0, anim.Duration, 0));
var settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.stopTime = anim.Duration;
SetAnimationSettings(clip, settings);
AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]);
foreach (Timeline t in anim.Timelines) {
if (t is EventTimeline) {
ParseEventTimeline((EventTimeline)t, clip, SendMessageOptions.DontRequireReceiver);
}
}
EditorUtility.SetDirty(clip);
unityAnimationClipTable.Remove(name);
}
//clear no longer used animations
foreach (var clip in unityAnimationClipTable.Values) {
AnimationClip.DestroyImmediate(clip, true);
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
static bool HasFlag (this UnityEngine.Object o, HideFlags flagToCheck) {
return (o.hideFlags & flagToCheck) == flagToCheck;
}
#endif
#endregion
#region Baking
/// <summary>
/// Interval between key sampling for Bezier curves, IK controlled bones, and Inherit Rotation effected bones.
/// </summary>
const float bakeIncrement = 1 / 60f;
public static void BakeToPrefab (SkeletonDataAsset skeletonDataAsset, ExposedList<Skin> skins, string outputPath = "", bool bakeAnimations = true, bool bakeIK = true, SendMessageOptions eventOptions = SendMessageOptions.DontRequireReceiver) {
if (skeletonDataAsset == null || skeletonDataAsset.GetSkeletonData(true) == null) {
Debug.LogError("Could not export Spine Skeleton because SkeletonDataAsset is null or invalid!");
return;
}
if (outputPath == "") {
outputPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(skeletonDataAsset)) + "/Baked";
System.IO.Directory.CreateDirectory(outputPath);
}
var skeletonData = skeletonDataAsset.GetSkeletonData(true);
bool hasAnimations = bakeAnimations && skeletonData.Animations.Count > 0;
UnityEditor.Animations.AnimatorController controller = null;
if (hasAnimations) {
string controllerPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " Controller.controller";
bool newAnimContainer = false;
var runtimeController = AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController));
if (runtimeController != null) {
controller = (UnityEditor.Animations.AnimatorController)runtimeController;
} else {
controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
newAnimContainer = true;
}
var existingClipTable = new Dictionary<string, AnimationClip>();
var unusedClipNames = new List<string>();
Object[] animObjs = AssetDatabase.LoadAllAssetsAtPath(controllerPath);
foreach (Object o in animObjs) {
if (o is AnimationClip) {
var clip = (AnimationClip)o;
existingClipTable.Add(clip.name, clip);
unusedClipNames.Add(clip.name);
}
}
Dictionary<int, List<string>> slotLookup = new Dictionary<int, List<string>>();
int skinCount = skins.Count;
for (int s = 0; s < skeletonData.Slots.Count; s++) {
List<string> attachmentNames = new List<string>();
for (int i = 0; i < skinCount; i++) {
var skin = skins.Items[i];
List<string> temp = new List<string>();
skin.FindNamesForSlot(s, temp);
foreach (string str in temp) {
if (!attachmentNames.Contains(str))
attachmentNames.Add(str);
}
}
slotLookup.Add(s, attachmentNames);
}
foreach (var anim in skeletonData.Animations) {
AnimationClip clip = null;
if (existingClipTable.ContainsKey(anim.Name)) {
clip = existingClipTable[anim.Name];
}
clip = ExtractAnimation(anim.Name, skeletonData, slotLookup, bakeIK, eventOptions, clip);
if (unusedClipNames.Contains(clip.name)) {
unusedClipNames.Remove(clip.name);
} else {
AssetDatabase.AddObjectToAsset(clip, controller);
controller.AddMotion(clip);
}
}
if (newAnimContainer) {
EditorUtility.SetDirty(controller);
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
} else {
foreach (string str in unusedClipNames) {
AnimationClip.DestroyImmediate(existingClipTable[str], true);
}
EditorUtility.SetDirty(controller);
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
}
}
foreach (var skin in skins) {
bool newPrefab = false;
string prefabPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " (" + skin.Name + ").prefab";
Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
if (prefab == null) {
prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
newPrefab = true;
}
Dictionary<string, Mesh> meshTable = new Dictionary<string, Mesh>();
List<string> unusedMeshNames = new List<string>();
Object[] assets = AssetDatabase.LoadAllAssetsAtPath(prefabPath);
foreach (var obj in assets) {
if (obj is Mesh) {
meshTable.Add(obj.name, (Mesh)obj);
unusedMeshNames.Add(obj.name);
}
}
GameObject prefabRoot = new GameObject("root");
Dictionary<string, Transform> slotTable = new Dictionary<string, Transform>();
Dictionary<string, Transform> boneTable = new Dictionary<string, Transform>();
List<Transform> boneList = new List<Transform>();
//create bones
for (int i = 0; i < skeletonData.Bones.Count; i++) {
var boneData = skeletonData.Bones.Items[i];
Transform boneTransform = new GameObject(boneData.Name).transform;
boneTransform.parent = prefabRoot.transform;
boneTable.Add(boneTransform.name, boneTransform);
boneList.Add(boneTransform);
}
for (int i = 0; i < skeletonData.Bones.Count; i++) {
var boneData = skeletonData.Bones.Items[i];
Transform boneTransform = boneTable[boneData.Name];
Transform parentTransform = null;
if (i > 0)
parentTransform = boneTable[boneData.Parent.Name];
else
parentTransform = boneTransform.parent;
boneTransform.parent = parentTransform;
boneTransform.localPosition = new Vector3(boneData.X, boneData.Y, 0);
var tm = boneData.TransformMode;
if (tm.InheritsRotation())
boneTransform.localRotation = Quaternion.Euler(0, 0, boneData.Rotation);
else
boneTransform.rotation = Quaternion.Euler(0, 0, boneData.Rotation);
if (tm.InheritsScale())
boneTransform.localScale = new Vector3(boneData.ScaleX, boneData.ScaleY, 1);
}
//create slots and attachments
for (int i = 0; i < skeletonData.Slots.Count; i++) {
var slotData = skeletonData.Slots.Items[i];
Transform slotTransform = new GameObject(slotData.Name).transform;
slotTransform.parent = prefabRoot.transform;
slotTable.Add(slotData.Name, slotTransform);
List<Attachment> attachments = new List<Attachment>();
List<string> attachmentNames = new List<string>();
skin.FindAttachmentsForSlot(i, attachments);
skin.FindNamesForSlot(i, attachmentNames);
if (skin != skeletonData.DefaultSkin) {
skeletonData.DefaultSkin.FindAttachmentsForSlot(i, attachments);
skeletonData.DefaultSkin.FindNamesForSlot(i, attachmentNames);
}
for (int a = 0; a < attachments.Count; a++) {
var attachment = attachments[a];
var attachmentName = attachmentNames[a];
var attachmentMeshName = "[" + slotData.Name + "] " + attachmentName;
Vector3 offset = Vector3.zero;
float rotation = 0;
Mesh mesh = null;
Material material = null;
bool isWeightedMesh = false;
if (meshTable.ContainsKey(attachmentMeshName))
mesh = meshTable[attachmentMeshName];
if (attachment is RegionAttachment) {
var regionAttachment = (RegionAttachment)attachment;
offset.x = regionAttachment.X;
offset.y = regionAttachment.Y;
rotation = regionAttachment.Rotation;
mesh = ExtractRegionAttachment(attachmentMeshName, regionAttachment, mesh);
material = attachment.GetMaterial();
unusedMeshNames.Remove(attachmentMeshName);
if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false)
AssetDatabase.AddObjectToAsset(mesh, prefab);
} else if (attachment is MeshAttachment) {
var meshAttachment = (MeshAttachment)attachment;
isWeightedMesh = (meshAttachment.Bones != null);
offset.x = 0;
offset.y = 0;
rotation = 0;
if (isWeightedMesh)
mesh = ExtractWeightedMeshAttachment(attachmentMeshName, meshAttachment, i, skeletonData, boneList, mesh);
else
mesh = ExtractMeshAttachment(attachmentMeshName, meshAttachment, mesh);
material = attachment.GetMaterial();
unusedMeshNames.Remove(attachmentMeshName);
if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false)
AssetDatabase.AddObjectToAsset(mesh, prefab);
} else
continue;
Transform attachmentTransform = new GameObject(attachmentName).transform;
attachmentTransform.parent = slotTransform;
attachmentTransform.localPosition = offset;
attachmentTransform.localRotation = Quaternion.Euler(0, 0, rotation);
if (isWeightedMesh) {
attachmentTransform.position = Vector3.zero;
attachmentTransform.rotation = Quaternion.identity;
var skinnedMeshRenderer = attachmentTransform.gameObject.AddComponent<SkinnedMeshRenderer>();
skinnedMeshRenderer.rootBone = boneList[0];
skinnedMeshRenderer.bones = boneList.ToArray();
skinnedMeshRenderer.sharedMesh = mesh;
} else {
attachmentTransform.gameObject.AddComponent<MeshFilter>().sharedMesh = mesh;
attachmentTransform.gameObject.AddComponent<MeshRenderer>();
}
attachmentTransform.GetComponent<Renderer>().sharedMaterial = material;
attachmentTransform.GetComponent<Renderer>().sortingOrder = i;
if (attachmentName != slotData.AttachmentName)
attachmentTransform.gameObject.SetActive(false);
}
}
foreach (var slotData in skeletonData.Slots) {
Transform slotTransform = slotTable[slotData.Name];
slotTransform.parent = boneTable[slotData.BoneData.Name];
slotTransform.localPosition = Vector3.zero;
slotTransform.localRotation = Quaternion.identity;
slotTransform.localScale = Vector3.one;
}
if (hasAnimations) {
var animator = prefabRoot.AddComponent<Animator>();
animator.applyRootMotion = false;
animator.runtimeAnimatorController = (RuntimeAnimatorController)controller;
EditorGUIUtility.PingObject(controller);
}
if (newPrefab) {
PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
} else {
foreach (string str in unusedMeshNames) {
Mesh.DestroyImmediate(meshTable[str], true);
}
PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ReplaceNameBased);
}
EditorGUIUtility.PingObject(prefab);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
GameObject.DestroyImmediate(prefabRoot);
}
}
static Bone extractionBone;
static Slot extractionSlot;
static Bone GetExtractionBone () {
if (extractionBone != null)
return extractionBone;
SkeletonData skelData = new SkeletonData();
BoneData data = new BoneData(0, "temp", null);
data.ScaleX = 1;
data.ScaleY = 1;
data.Length = 100;
skelData.Bones.Add(data);
Skeleton skeleton = new Skeleton(skelData);
Bone bone = new Bone(data, skeleton, null);
bone.UpdateWorldTransform();
extractionBone = bone;
return extractionBone;
}
static Slot GetExtractionSlot () {
if (extractionSlot != null)
return extractionSlot;
Bone bone = GetExtractionBone();
SlotData data = new SlotData(0, "temp", bone.Data);
Slot slot = new Slot(data, bone);
extractionSlot = slot;
return extractionSlot;
}
static Mesh ExtractRegionAttachment (string name, RegionAttachment attachment, Mesh mesh = null) {
var bone = GetExtractionBone();
bone.X = -attachment.X;
bone.Y = -attachment.Y;
bone.UpdateWorldTransform();
Vector2[] uvs = ExtractUV(attachment.UVs);
float[] floatVerts = new float[8];
attachment.ComputeWorldVertices(bone, floatVerts, 0);
Vector3[] verts = ExtractVerts(floatVerts);
//unrotate verts now that they're centered
for (int i = 0; i < verts.Length; i++) {
verts[i] = Quaternion.Euler(0, 0, -attachment.Rotation) * verts[i];
}
int[] triangles = new int[6] { 1, 3, 0, 2, 3, 1 };
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
if (mesh == null)
mesh = new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.colors = new Color[] { color, color, color, color };
mesh.RecalculateBounds();
mesh.RecalculateNormals();
mesh.name = name;
return mesh;
}
static Mesh ExtractMeshAttachment (string name, MeshAttachment attachment, Mesh mesh = null) {
var slot = GetExtractionSlot();
slot.Bone.X = 0;
slot.Bone.Y = 0;
slot.Bone.UpdateWorldTransform();
Vector2[] uvs = ExtractUV(attachment.UVs);
float[] floatVerts = new float[attachment.WorldVerticesLength];
attachment.ComputeWorldVertices(slot, floatVerts);
Vector3[] verts = ExtractVerts(floatVerts);
int[] triangles = attachment.Triangles;
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
if (mesh == null)
mesh = new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
Color[] colors = new Color[verts.Length];
for (int i = 0; i < verts.Length; i++)
colors[i] = color;
mesh.colors = colors;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
mesh.name = name;
return mesh;
}
public class BoneWeightContainer {
public struct Pair {
public Transform bone;
public float weight;
public Pair (Transform bone, float weight) {
this.bone = bone;
this.weight = weight;
}
}
public List<Transform> bones;
public List<float> weights;
public List<Pair> pairs;
public BoneWeightContainer () {
this.bones = new List<Transform>();
this.weights = new List<float>();
this.pairs = new List<Pair>();
}
public void Add (Transform transform, float weight) {
bones.Add(transform);
weights.Add(weight);
pairs.Add(new Pair(transform, weight));
}
}
static Mesh ExtractWeightedMeshAttachment (string name, MeshAttachment attachment, int slotIndex, SkeletonData skeletonData, List<Transform> boneList, Mesh mesh = null) {
if (attachment.Bones == null)
throw new System.ArgumentException("Mesh is not weighted.", "attachment");
Skeleton skeleton = new Skeleton(skeletonData);
skeleton.UpdateWorldTransform();
float[] floatVerts = new float[attachment.WorldVerticesLength];
attachment.ComputeWorldVertices(skeleton.Slots.Items[slotIndex], floatVerts);
Vector2[] uvs = ExtractUV(attachment.UVs);
Vector3[] verts = ExtractVerts(floatVerts);
int[] triangles = attachment.Triangles;
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
mesh = mesh ?? new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
Color[] colors = new Color[verts.Length];
for (int i = 0; i < verts.Length; i++)
colors[i] = color;
mesh.colors = colors;
mesh.name = name;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
// Handle weights and binding
var weightTable = new Dictionary<int, BoneWeightContainer>();
var warningBuilder = new System.Text.StringBuilder();
int[] bones = attachment.Bones;
float[] weights = attachment.Vertices;
for (int w = 0, v = 0, b = 0, n = bones.Length; v < n; w += 2) {
int nn = bones[v++] + v;
for (; v < nn; v++, b += 3) {
Transform boneTransform = boneList[bones[v]];
int vIndex = w / 2;
BoneWeightContainer container;
if (weightTable.ContainsKey(vIndex))
container = weightTable[vIndex];
else {
container = new BoneWeightContainer();
weightTable.Add(vIndex, container);
}
float weight = weights[b + 2];
container.Add(boneTransform, weight);
}
}
BoneWeight[] boneWeights = new BoneWeight[weightTable.Count];
for (int i = 0; i < weightTable.Count; i++) {
BoneWeight bw = new BoneWeight();
var container = weightTable[i];
var pairs = container.pairs.OrderByDescending(pair => pair.weight).ToList();
for (int b = 0; b < pairs.Count; b++) {
if (b > 3) {
if (warningBuilder.Length == 0)
warningBuilder.Insert(0, "[Weighted Mesh: " + name + "]\r\nUnity only supports 4 weight influences per vertex! The 4 strongest influences will be used.\r\n");
warningBuilder.AppendFormat("{0} ignored on vertex {1}!\r\n", pairs[b].bone.name, i);
continue;
}
int boneIndex = boneList.IndexOf(pairs[b].bone);
float weight = pairs[b].weight;
switch (b) {
case 0:
bw.boneIndex0 = boneIndex;
bw.weight0 = weight;
break;
case 1:
bw.boneIndex1 = boneIndex;
bw.weight1 = weight;
break;
case 2:
bw.boneIndex2 = boneIndex;
bw.weight2 = weight;
break;
case 3:
bw.boneIndex3 = boneIndex;
bw.weight3 = weight;
break;
}
}
boneWeights[i] = bw;
}
Matrix4x4[] bindPoses = new Matrix4x4[boneList.Count];
for (int i = 0; i < boneList.Count; i++) {
bindPoses[i] = boneList[i].worldToLocalMatrix;
}
mesh.boneWeights = boneWeights;
mesh.bindposes = bindPoses;
string warningString = warningBuilder.ToString();
if (warningString.Length > 0)
Debug.LogWarning(warningString);
return mesh;
}
static Vector2[] ExtractUV (float[] floats) {
Vector2[] arr = new Vector2[floats.Length / 2];
for (int i = 0; i < floats.Length; i += 2) {
arr[i / 2] = new Vector2(floats[i], floats[i + 1]);
}
return arr;
}
static Vector3[] ExtractVerts (float[] floats) {
Vector3[] arr = new Vector3[floats.Length / 2];
for (int i = 0; i < floats.Length; i += 2) {
arr[i / 2] = new Vector3(floats[i], floats[i + 1], 0);// *scale;
}
return arr;
}
static AnimationClip ExtractAnimation (string name, SkeletonData skeletonData, Dictionary<int, List<string>> slotLookup, bool bakeIK, SendMessageOptions eventOptions, AnimationClip clip = null) {
var animation = skeletonData.FindAnimation(name);
var timelines = animation.Timelines;
if (clip == null) {
clip = new AnimationClip();
} else {
clip.ClearCurves();
AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]);
}
clip.name = name;
Skeleton skeleton = new Skeleton(skeletonData);
List<int> ignoreRotateTimelineIndexes = new List<int>();
if (bakeIK) {
foreach (IkConstraint i in skeleton.IkConstraints) {
foreach (Bone b in i.Bones) {
int index = skeleton.FindBoneIndex(b.Data.Name);
ignoreRotateTimelineIndexes.Add(index);
BakeBone(b, animation, clip);
}
}
}
foreach (Bone b in skeleton.Bones) {
if (!b.Data.TransformMode.InheritsRotation()) {
int index = skeleton.FindBoneIndex(b.Data.Name);
if (ignoreRotateTimelineIndexes.Contains(index) == false) {
ignoreRotateTimelineIndexes.Add(index);
BakeBone(b, animation, clip);
}
}
}
foreach (Timeline t in timelines) {
skeleton.SetToSetupPose();
if (t is ScaleTimeline) {
ParseScaleTimeline(skeleton, (ScaleTimeline)t, clip);
} else if (t is TranslateTimeline) {
ParseTranslateTimeline(skeleton, (TranslateTimeline)t, clip);
} else if (t is RotateTimeline) {
//bypass any rotation keys if they're going to get baked anyway to prevent localEulerAngles vs Baked collision
if (ignoreRotateTimelineIndexes.Contains(((RotateTimeline)t).BoneIndex) == false)
ParseRotateTimeline(skeleton, (RotateTimeline)t, clip);
} else if (t is AttachmentTimeline) {
ParseAttachmentTimeline(skeleton, (AttachmentTimeline)t, slotLookup, clip);
} else if (t is EventTimeline) {
ParseEventTimeline((EventTimeline)t, clip, eventOptions);
}
}
var settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.loopTime = true;
settings.stopTime = Mathf.Max(clip.length, 0.001f);
SetAnimationSettings(clip, settings);
clip.EnsureQuaternionContinuity();
EditorUtility.SetDirty(clip);
return clip;
}
static int BinarySearch (float[] values, float target) {
int low = 0;
int high = values.Length - 2;
if (high == 0) return 1;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1)] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1);
current = (int)((uint)(low + high) >> 1);
}
}
static void ParseEventTimeline (EventTimeline timeline, AnimationClip clip, SendMessageOptions eventOptions) {
float[] frames = timeline.Frames;
var events = timeline.Events;
List<AnimationEvent> animEvents = new List<AnimationEvent>();
for (int i = 0; i < frames.Length; i++) {
var ev = events[i];
AnimationEvent ae = new AnimationEvent();
//MITCH: left todo: Deal with Mecanim's zero-time missed event
ae.time = frames[i];
ae.functionName = ev.Data.Name;
ae.messageOptions = eventOptions;
if (!string.IsNullOrEmpty(ev.String)) {
ae.stringParameter = ev.String;
} else {
if (ev.Int == 0 && ev.Float == 0) {
//do nothing, raw function
} else {
if (ev.Int != 0)
ae.floatParameter = (float)ev.Int;
else
ae.floatParameter = ev.Float;
}
}
animEvents.Add(ae);
}
AnimationUtility.SetAnimationEvents(clip, animEvents.ToArray());
}
static void ParseAttachmentTimeline (Skeleton skeleton, AttachmentTimeline timeline, Dictionary<int, List<string>> slotLookup, AnimationClip clip) {
var attachmentNames = slotLookup[timeline.SlotIndex];
string bonePath = GetPath(skeleton.Slots.Items[timeline.SlotIndex].Bone.Data);
string slotPath = bonePath + "/" + skeleton.Slots.Items[timeline.SlotIndex].Data.Name;
Dictionary<string, AnimationCurve> curveTable = new Dictionary<string, AnimationCurve>();
foreach (string str in attachmentNames) {
curveTable.Add(str, new AnimationCurve());
}
float[] frames = timeline.Frames;
if (frames[0] != 0) {
string startingName = skeleton.Slots.Items[timeline.SlotIndex].Data.AttachmentName;
foreach (var pair in curveTable) {
if (startingName == "" || startingName == null) {
pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity));
} else {
if (pair.Key == startingName) {
pair.Value.AddKey(new Keyframe(0, 1, float.PositiveInfinity, float.PositiveInfinity));
} else {
pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity));
}
}
}
}
float currentTime = timeline.Frames[0];
float endTime = frames[frames.Length - 1];
int f = 0;
while (currentTime < endTime) {
float time = frames[f];
int frameIndex = (time >= frames[frames.Length - 1] ? frames.Length : BinarySearch(frames, time)) - 1;
string name = timeline.AttachmentNames[frameIndex];
foreach (var pair in curveTable) {
if (name == "") {
pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity));
} else {
if (pair.Key == name) {
pair.Value.AddKey(new Keyframe(time, 1, float.PositiveInfinity, float.PositiveInfinity));
} else {
pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity));
}
}
}
currentTime = time;
f += 1;
}
foreach (var pair in curveTable) {
string path = slotPath + "/" + pair.Key;
string prop = "m_IsActive";
clip.SetCurve(path, typeof(GameObject), prop, pair.Value);
}
}
static float GetUninheritedRotation (Bone b) {
Bone parent = b.Parent;
float angle = b.AppliedRotation;
while (parent != null) {
angle -= parent.AppliedRotation;
parent = parent.Parent;
}
return angle;
}
static void BakeBone (Bone bone, Spine.Animation animation, AnimationClip clip) {
Skeleton skeleton = bone.Skeleton;
bool inheritRotation = bone.Data.TransformMode.InheritsRotation();
animation.PoseSkeleton(skeleton, 0);
skeleton.UpdateWorldTransform();
float duration = animation.Duration;
AnimationCurve curve = new AnimationCurve();
List<Keyframe> keys = new List<Keyframe>();
float rotation = bone.AppliedRotation;
if (!inheritRotation)
rotation = GetUninheritedRotation(bone);
keys.Add(new Keyframe(0, rotation, 0, 0));
int listIndex = 1;
float r = rotation;
int steps = Mathf.CeilToInt(duration / bakeIncrement);
float currentTime = 0;
float angle = rotation;
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = duration;
animation.PoseSkeleton(skeleton, currentTime, true);
skeleton.UpdateWorldTransform();
int pIndex = listIndex - 1;
Keyframe pk = keys[pIndex];
pk = keys[pIndex];
rotation = inheritRotation ? bone.AppliedRotation : GetUninheritedRotation(bone);
angle += Mathf.DeltaAngle(angle, rotation);
r = angle;
float rOut = (r - pk.value) / (currentTime - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(currentTime, r, rOut, 0));
keys[pIndex] = pk;
listIndex++;
}
curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray()));
string path = GetPath(bone.Data);
string propertyName = "localEulerAnglesBaked";
EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x");
AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve());
EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y");
AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve());
EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z");
AnimationUtility.SetEditorCurve(clip, zBind, curve);
}
static void ParseTranslateTimeline (Skeleton skeleton, TranslateTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve xCurve = new AnimationCurve();
AnimationCurve yCurve = new AnimationCurve();
AnimationCurve zCurve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3];
float currentTime = timeline.Frames[0];
List<Keyframe> xKeys = new List<Keyframe>();
List<Keyframe> yKeys = new List<Keyframe>();
xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] + boneData.X, 0, 0));
yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] + boneData.Y, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 3;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] + boneData.X;
float y = frames[f + 2] + boneData.Y;
float xOut = (x - px.value) / (time - px.time);
float yOut = (y - py.value) / (time - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] + boneData.X;
float y = frames[f + 2] + boneData.Y;
float xOut = float.PositiveInfinity;
float yOut = float.PositiveInfinity;
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
int steps = Mathf.FloorToInt((time - px.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
px = xKeys[listIndex - 1];
py = yKeys[listIndex - 1];
float xOut = (bone.X - px.value) / (currentTime - px.time);
float yOut = (bone.Y - py.value) / (currentTime - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(currentTime, bone.X, xOut, 0));
yKeys.Add(new Keyframe(currentTime, bone.Y, yOut, 0));
xKeys[listIndex - 1] = px;
yKeys[listIndex - 1] = py;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 3;
}
xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray()));
yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray()));
string path = GetPath(boneData);
const string propertyName = "localPosition";
clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve);
}
static AnimationCurve EnsureCurveKeyCount (AnimationCurve curve) {
if (curve.length == 1)
curve.AddKey(curve.keys[0].time + 0.25f, curve.keys[0].value);
return curve;
}
static void ParseScaleTimeline (Skeleton skeleton, ScaleTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve xCurve = new AnimationCurve();
AnimationCurve yCurve = new AnimationCurve();
AnimationCurve zCurve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3];
float currentTime = timeline.Frames[0];
List<Keyframe> xKeys = new List<Keyframe>();
List<Keyframe> yKeys = new List<Keyframe>();
xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] * boneData.ScaleX, 0, 0));
yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] * boneData.ScaleY, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 3;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] * boneData.ScaleX;
float y = frames[f + 2] * boneData.ScaleY;
float xOut = (x - px.value) / (time - px.time);
float yOut = (y - py.value) / (time - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] * boneData.ScaleX;
float y = frames[f + 2] * boneData.ScaleY;
float xOut = float.PositiveInfinity;
float yOut = float.PositiveInfinity;
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
int steps = Mathf.FloorToInt((time - px.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
px = xKeys[listIndex - 1];
py = yKeys[listIndex - 1];
float xOut = (bone.ScaleX - px.value) / (currentTime - px.time);
float yOut = (bone.ScaleY - py.value) / (currentTime - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(currentTime, bone.ScaleX, xOut, 0));
yKeys.Add(new Keyframe(currentTime, bone.ScaleY, yOut, 0));
xKeys[listIndex - 1] = px;
yKeys[listIndex - 1] = py;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 3;
}
xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray()));
yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray()));
string path = GetPath(boneData);
string propertyName = "localScale";
clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve);
}
static void ParseRotateTimeline (Skeleton skeleton, RotateTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve curve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 2) - 2];
float currentTime = timeline.Frames[0];
List<Keyframe> keys = new List<Keyframe>();
float rotation = timeline.Frames[1] + boneData.Rotation;
keys.Add(new Keyframe(timeline.Frames[0], rotation, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 2;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
float angle = rotation;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe pk = keys[pIndex];
float time = frames[f];
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
float rOut = (r - pk.value) / (time - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(time, r, rOut, 0));
keys[pIndex] = pk;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe pk = keys[pIndex];
float time = frames[f];
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
float rOut = float.PositiveInfinity;
pk.outTangent = rOut;
keys.Add(new Keyframe(time, r, rOut, 0));
keys[pIndex] = pk;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe pk = keys[pIndex];
float time = frames[f];
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
skeleton.UpdateWorldTransform();
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
int steps = Mathf.FloorToInt((time - pk.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixPose.Setup, MixDirection.In);
skeleton.UpdateWorldTransform();
pk = keys[listIndex - 1];
rotation = bone.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
r = angle;
float rOut = (r - pk.value) / (currentTime - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(currentTime, r, rOut, 0));
keys[listIndex - 1] = pk;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 2;
}
curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray()));
string path = GetPath(boneData);
const string propertyName = "localEulerAnglesBaked";
EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x");
AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve());
EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y");
AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve());
EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z");
AnimationUtility.SetEditorCurve(clip, zBind, curve);
}
static string GetPath (BoneData b) {
return GetPathRecurse(b).Substring(1);
}
static string GetPathRecurse (BoneData b) {
if (b == null) {
return "";
}
return GetPathRecurse(b.Parent) + "/" + b.Name;
}
#endregion
static void SetAnimationSettings (AnimationClip clip, AnimationClipSettings settings) {
AnimationUtility.SetAnimationClipSettings(clip, settings);
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2012 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using System.Threading;
namespace ServiceStack.Text.Common
{
public static class DeserializeArrayWithElements<TSerializer>
where TSerializer : ITypeSerializer
{
private static Dictionary<Type, ParseArrayOfElementsDelegate> ParseDelegateCache
= new Dictionary<Type, ParseArrayOfElementsDelegate>();
public delegate object ParseArrayOfElementsDelegate(ReadOnlySpan<char> value, ParseStringSpanDelegate parseFn);
public static Func<string, ParseStringDelegate, object> GetParseFn(Type type)
{
var func = GetParseStringSpanFn(type);
return (s, d) => func(s.AsSpan(), v => d(v.ToString()));
}
private static readonly Type[] signature = {typeof(ReadOnlySpan<char>), typeof(ParseStringSpanDelegate)};
public static ParseArrayOfElementsDelegate GetParseStringSpanFn(Type type)
{
if (ParseDelegateCache.TryGetValue(type, out var parseFn)) return parseFn.Invoke;
var genericType = typeof(DeserializeArrayWithElements<,>).MakeGenericType(type, typeof(TSerializer));
var mi = genericType.GetStaticMethod("ParseGenericArray", signature);
parseFn = (ParseArrayOfElementsDelegate)mi.CreateDelegate(typeof(ParseArrayOfElementsDelegate));
Dictionary<Type, ParseArrayOfElementsDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseArrayOfElementsDelegate>(ParseDelegateCache);
newCache[type] = parseFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseFn.Invoke;
}
}
public static class DeserializeArrayWithElements<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
public static T[] ParseGenericArray(string value, ParseStringDelegate elementParseFn) =>
ParseGenericArray(value.AsSpan(), v => elementParseFn(v.ToString()));
public static T[] ParseGenericArray(ReadOnlySpan<char> value, ParseStringSpanDelegate elementParseFn)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : new T[0];
if (value[0] == JsWriter.MapStartChar)
{
var itemValues = new List<T>();
var i = 0;
do
{
var spanValue = Serializer.EatTypeValue(value, ref i);
itemValues.Add((T)elementParseFn(spanValue));
Serializer.EatItemSeperatorOrMapEndChar(value, ref i);
} while (i < value.Length);
return itemValues.ToArray();
}
else
{
var to = new List<T>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
var listValue = elementValue;
to.Add((T)elementParseFn(listValue));
if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i)
&& i == valueLength)
{
// If we ate a separator and we are at the end of the value,
// it means the last element is empty => add default
to.Add(default(T));
}
}
return to.ToArray();
}
}
}
internal static class DeserializeArray<TSerializer>
where TSerializer : ITypeSerializer
{
private static Dictionary<Type, ParseStringSpanDelegate> ParseDelegateCache = new Dictionary<Type, ParseStringSpanDelegate>();
public static ParseStringDelegate GetParseFn(Type type) => v => GetParseStringSpanFn(type)(v.AsSpan());
public static ParseStringSpanDelegate GetParseStringSpanFn(Type type)
{
if (ParseDelegateCache.TryGetValue(type, out var parseFn)) return parseFn;
var genericType = typeof(DeserializeArray<,>).MakeGenericType(type, typeof(TSerializer));
var mi = genericType.GetStaticMethod("GetParseStringSpanFn");
var parseFactoryFn = (Func<ParseStringSpanDelegate>)mi.MakeDelegate(
typeof(Func<ParseStringSpanDelegate>));
parseFn = parseFactoryFn();
Dictionary<Type, ParseStringSpanDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseStringSpanDelegate>(ParseDelegateCache) {[type] = parseFn};
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseFn;
}
}
internal static class DeserializeArray<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
private static readonly ParseStringSpanDelegate CacheFn;
static DeserializeArray()
{
CacheFn = GetParseStringSpanFn();
}
public static ParseStringDelegate Parse => v => CacheFn(v.AsSpan());
public static ParseStringSpanDelegate ParseStringSpan => CacheFn;
public static ParseStringDelegate GetParseFn() => v => GetParseStringSpanFn()(v.AsSpan());
public static ParseStringSpanDelegate GetParseStringSpanFn()
{
var type = typeof(T);
if (!type.IsArray)
throw new ArgumentException($"Type {type.FullName} is not an Array type");
if (type == typeof(string[]))
return ParseStringArray;
if (type == typeof(byte[]))
return v => ParseByteArray(v.ToString());
var elementType = type.GetElementType();
var elementParseFn = Serializer.GetParseStringSpanFn(elementType);
if (elementParseFn != null)
{
var parseFn = DeserializeArrayWithElements<TSerializer>.GetParseStringSpanFn(elementType);
return value => parseFn(value, elementParseFn);
}
return null;
}
public static string[] ParseStringArray(ReadOnlySpan<char> value)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : TypeConstants.EmptyStringArray;
return DeserializeListWithElements<TSerializer>.ParseStringList(value).ToArray();
}
public static string[] ParseStringArray(string value) => ParseStringArray(value.AsSpan());
public static byte[] ParseByteArray(string value) => ParseByteArray(value.AsSpan());
public static byte[] ParseByteArray(ReadOnlySpan<char> value)
{
var isArray = value.Length > 1 && value[0] == '[';
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : TypeConstants.EmptyByteArray;
if ((value = Serializer.UnescapeString(value)).IsNullOrEmpty())
return TypeConstants.EmptyByteArray;
return !isArray
? value.ParseBase64()
: DeserializeListWithElements<TSerializer>.ParseByteList(value).ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebServerOAuthFlow.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Aspose.Email.Live.Demos.UI.FileProcessing;
using Aspose.Email.Live.Demos.UI.LibraryHelpers;
using Aspose.Email.Live.Demos.UI.Models;
using Aspose.Email.Mapi;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Html;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Aspose.Email.Live.Demos.UI.Models.Common;
namespace Aspose.Email.Live.Demos.UI.Models
{
///<Summary>
/// AsposeEmailMerger class to merge email file
///</Summary>
public class AsposeEmailMerger : EmailBase
{
static string[] AllowedTypes =
{
".msg",
".ost",
".pst",
".eml",
".mbox"
};
///<Summary>
/// initialize AsposeEmailMerger class
///</Summary>
public AsposeEmailMerger()
{
Aspose.Email.Live.Demos.UI.Models.License.SetAsposeEmailLicense();
}
public Response Merge(InputFiles inputFiles, string outputType)
{
var processor = new CustomSingleOrZipFileProcessor()
{
CustomFilesProcessMethod = (string[] inputFilePaths, string outputFolderPath) =>
{
if (inputFilePaths.Length < 2)
throw new Exception("Required minimum two files for merging");
if (inputFilePaths.Length > 10)
throw new Exception("10 files is maximum for merging. Please, remove excess files");
var groupsDictionary = inputFilePaths.GroupBy(x => Path.GetExtension(x)?.ToLowerInvariant() ?? "null").Select(ShrinkKeys).ToDictionary(x => x.Item1, x => x.Item2);
if (groupsDictionary.ContainsKey("null"))
throw new Exception("All files must have extension in name");
Aspose.Email.Live.Demos.UI.Models.License.SetAsposeEmailLicense();
foreach (var item in groupsDictionary)
{
MergeFiles(item.Key, item.Value, outputFolderPath);
}
}
};
(string folder, string[] files) = (null, null);
folder = inputFiles.FolderName;
files = inputFiles.FileName;
try
{
return processor.Process(folder, files);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new Response() { Status = "200", Text = "Error on processing file" };
}
}
(string, string[]) ShrinkKeys(IGrouping<string, string> pair)
{
switch (pair.Key.ToLowerInvariant())
{
case ".eml":
case ".msg":
return (".mail", pair.ToArray());
case ".ost":
case ".pst":
case ".mbox":
return (".storage", pair.ToArray());
default:
throw new Exception("Wrong file type " + pair.Key);
}
}
void MergeFiles(string extension, string[] values, string outputFolderPath)
{
switch (extension)
{
case ".mail":
MergeMails(values, outputFolderPath);
break;
case ".storage":
MergeStorages(values, outputFolderPath);
break;
default:
break;
}
}
void MergeMails(string[] files, string outputFolderPath)
{
if (files.Length < 1)
return;
var mails = files.Select(x =>
{
var m = MapiHelper.GetMapiMessageFromFile(x);
if (m == null)
throw new Exception("Invalid file format " + Path.GetFileName(x));
return m;
}).ToArray();
var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString());
var filePath = Path.Combine(folderPath, "Merged.html");
Directory.CreateDirectory(folderPath);
var mail = mails[0];
MergeHtmlContentsAndSaveInFile(mails.Select(x => x.BodyHtml), filePath);
mail.SetBodyContent(System.IO.File.ReadAllText(filePath), BodyContentType.Html);
Directory.Delete(folderPath, true);
for (int i = 1; i < mails.Length; i++)
{
var addedMail = mails[i];
if (addedMail.Attachments != null)
foreach (var attachment in addedMail.Attachments)
mail.Attachments.Add(attachment);
}
mail.Save(Path.Combine(outputFolderPath, "MergedMessage.msg"));
}
void MergeStorages(string[] files, string outputFolderPath)
{
if (files.Length < 1)
return;
var extension = Path.GetExtension(files[0]);
if (extension.ToLowerInvariant() == ".mbox")
{
using (var writer = new MboxrdStorageWriter(Path.Combine(outputFolderPath, "MergedStorage.mbox"), false))
{
for (int i = 0; i < files.Length; i++)
AppendFile(writer, files[i]);
}
}
else
{
using (var storage = PersonalStorage.Create(Path.Combine(outputFolderPath, "MergedStorage.pst"), FileFormatVersion.Unicode))
{
for (int i = 0; i < files.Length; i++)
AppendFile(storage, files[i]);
}
}
}
///<Summary>
/// MergeHtmlContentsAndSaveInFile method to merge html contents and save in file
///</Summary>
public static void MergeHtmlContentsAndSaveInFile(IEnumerable<string> htmls, string temporaryHtmlPath)
{
var docs = htmls.Select(x => new Aspose.Html.HTMLDocument(x, "")).ToArray();
var htmlDocument1 = docs[0];
for (int i = 1; i < docs.Length; i++)
AppendDoc(htmlDocument1, docs[i]);
htmlDocument1.Save(temporaryHtmlPath);
}
private static void AppendDoc(HTMLDocument htmlDocument1, HTMLDocument htmlDocument2)
{
foreach (var item in htmlDocument2.Body.Children.ToArray())
htmlDocument1.Body.AppendChild(item);
if (htmlDocument1.Title != htmlDocument2.Title)
htmlDocument1.Title += htmlDocument2.Title;
var headElement = htmlDocument1.GetElementsByTagName("head")[0];
var metaCollection1 = htmlDocument2.QuerySelectorAll("meta[name]").Cast<Html.HTMLMetaElement>();
var metaCollection2 = htmlDocument2.QuerySelectorAll("meta[name]").Cast<Html.HTMLMetaElement>();
foreach (var metaElement1 in metaCollection1)
{
Html.HTMLMetaElement metaElement2;
try
{
metaElement2 = metaCollection2.First(e => e.Name == metaElement1.Name);
metaElement1.Content += metaElement2.Content;
}
catch (System.InvalidOperationException)
{
headElement.AppendChild(metaElement1);
}
}
}
private void AppendFile(PersonalStorage storage, string filePath)
{
var extension = Path.GetExtension(filePath);
if (extension.ToLowerInvariant() == ".mbox")
{
using (var reader = new MboxrdStorageReader(filePath, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
storage.RootFolder.AddMessage(MapiMessage.FromMailMessage(reader.ReadNextMessage()));
}
}
else
{
storage.MergeWith(new[] { filePath });
}
}
private void AppendFile(MboxrdStorageWriter writer, string filePath)
{
var extension = Path.GetExtension(filePath);
if (extension.ToLowerInvariant() == ".mbox")
{
using (var reader = new MboxrdStorageReader(filePath, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
writer.WriteMessage(reader.ReadNextMessage());
}
}
else
{
using (var storage = PersonalStorage.FromFile(filePath))
{
var options = new MailConversionOptions();
HandleFolderAndSubfolders(mapiMessage =>
{
var msg = mapiMessage.ToMailMessage(options);
writer.WriteMessage(msg);
}, storage.RootFolder, options);
}
}
}
void HandleFolderAndSubfolders(Action<MapiMessage> handler, FolderInfo folderInfo, MailConversionOptions options)
{
foreach (MapiMessage mapiMessage in folderInfo.EnumerateMapiMessages())
{
handler(mapiMessage);
}
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
HandleFolderAndSubfolders(handler, subfolderInfo, options);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Practices.Prism.Composition.Tests.Mocks;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Prism.Composition.Tests.Modularity
{
/// <summary>
/// Summary description for ModuleInitializerFixture
/// </summary>
[TestClass]
public class ModuleInitializerFixture
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullContainerThrows()
{
ModuleInitializer loader = new ModuleInitializer(null, new MockLogger());
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullLoggerThrows()
{
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), null);
}
[TestMethod]
[ExpectedException(typeof(ModuleInitializeException))]
public void InitializationExceptionsAreWrapped()
{
var moduleInfo = CreateModuleInfo(typeof(ExceptionThrowingModule));
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());
loader.Initialize(moduleInfo);
}
[TestMethod]
public void ShouldResolveModuleAndInitializeSingleModule()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var service = new ModuleInitializer(containerFacade, new MockLogger());
FirstTestModule.wasInitializedOnce = false;
var info = CreateModuleInfo(typeof(FirstTestModule));
service.Initialize(info);
Assert.IsTrue(FirstTestModule.wasInitializedOnce);
}
[TestMethod]
public void ShouldLogModuleInitializeErrorsAndContinueLoading()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var logger = new MockLogger();
var service = new CustomModuleInitializerService(containerFacade, logger);
var invalidModule = CreateModuleInfo(typeof(InvalidModule));
Assert.IsFalse(service.HandleModuleInitializerrorCalled);
service.Initialize(invalidModule);
Assert.IsTrue(service.HandleModuleInitializerrorCalled);
}
[TestMethod]
public void ShouldLogModuleInitializationError()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var logger = new MockLogger();
var service = new ModuleInitializer(containerFacade, logger);
ExceptionThrowingModule.wasInitializedOnce = false;
var exceptionModule = CreateModuleInfo(typeof(ExceptionThrowingModule));
try
{
service.Initialize(exceptionModule);
}
catch (ModuleInitializeException)
{
}
Assert.IsNotNull(logger.LastMessage);
StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
}
[TestMethod]
public void ShouldThrowExceptionIfBogusType()
{
var moduleInfo = new ModuleInfo("TestModule", "BadAssembly.BadType");
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());
try
{
loader.Initialize(moduleInfo);
Assert.Fail("Did not throw exception");
}
catch (ModuleInitializeException ex)
{
StringAssert.Contains(ex.Message, "BadAssembly.BadType");
}
catch(Exception)
{
Assert.Fail();
}
}
private static ModuleInfo CreateModuleInfo(Type type, params string[] dependsOn)
{
ModuleInfo moduleInfo = new ModuleInfo(type.Name, type.AssemblyQualifiedName);
moduleInfo.DependsOn.AddRange(dependsOn);
return moduleInfo;
}
public static class ModuleLoadTracker
{
public static readonly Stack<Type> ModuleLoadStack = new Stack<Type>();
}
public class FirstTestModule : IModule
{
public static bool wasInitializedOnce;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class SecondTestModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class DependantModule : IModule
{
public static bool wasInitializedOnce;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class DependencyModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class ExceptionThrowingModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
throw new InvalidOperationException("Intialization can't be performed");
}
}
public class InvalidModule { }
public class CustomModuleInitializerService : ModuleInitializer
{
public bool HandleModuleInitializerrorCalled;
public CustomModuleInitializerService(IServiceLocator containerFacade, ILoggerFacade logger)
: base(containerFacade, logger)
{
}
public override void HandleModuleInitializationError(ModuleInfo moduleInfo, string assemblyName, Exception exception)
{
HandleModuleInitializerrorCalled = true;
}
}
public class Module1 : IModule { void IModule.Initialize() { } }
public class Module2 : IModule { void IModule.Initialize() { } }
public class Module3 : IModule { void IModule.Initialize() { } }
public class Module4 : IModule { void IModule.Initialize() { } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using Orleans.Runtime;
namespace Orleans.AzureUtils
{
/// <summary>
/// How to use the Queue Storage Service: http://www.windowsazure.com/en-us/develop/net/how-to-guides/queue-service/
/// Windows Azure Storage Abstractions and their Scalability Targets: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/10/windows-azure-storage-abstractions-and-their-scalability-targets.aspx
/// Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx
/// Windows Azure Queues and Windows Azure Service Bus Queues - Compared and Contrasted: http://msdn.microsoft.com/en-us/library/hh767287(VS.103).aspx
/// Status and Error Codes: http://msdn.microsoft.com/en-us/library/dd179382.aspx
///
/// http://blogs.msdn.com/b/windowsazurestorage/archive/tags/scalability/
/// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/12/30/windows-azure-storage-architecture-overview.aspx
/// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx
///
/// </summary>
internal static class AzureQueueDefaultPolicies
{
public static int MaxQueueOperationRetries;
public static TimeSpan PauseBetweenQueueOperationRetries;
public static TimeSpan QueueOperationTimeout;
public static IRetryPolicy QueueOperationRetryPolicy;
static AzureQueueDefaultPolicies()
{
MaxQueueOperationRetries = 5;
PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100);
QueueOperationRetryPolicy = new LinearRetry(PauseBetweenQueueOperationRetries, MaxQueueOperationRetries); // 5 x 100ms
QueueOperationTimeout = PauseBetweenQueueOperationRetries.Multiply(MaxQueueOperationRetries).Multiply(6); // 3 sec
}
}
/// <summary>
/// Utility class to encapsulate access to Azure queue storage.
/// </summary>
/// <remarks>
/// Used by Azure queue streaming provider.
/// </remarks>
public class AzureQueueDataManager
{
/// <summary> Name of the table queue instance is managing. </summary>
public string QueueName { get; private set; }
private string connectionString { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
private readonly ILogger logger;
private readonly TimeSpan? messageVisibilityTimeout;
private readonly CloudQueueClient queueOperationsClient;
private CloudQueue queue;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="loggerFactory">logger factory to use</param>
/// <param name="queueName">Name of the queue to be connected to.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
/// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param>
public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string storageConnectionString, TimeSpan? visibilityTimeout = null)
{
AzureStorageUtils.ValidateQueueName(queueName);
logger = loggerFactory.CreateLogger<AzureQueueDataManager>();
QueueName = queueName;
connectionString = storageConnectionString;
messageVisibilityTimeout = visibilityTimeout;
queueOperationsClient = AzureStorageUtils.GetCloudQueueClient(
connectionString,
AzureQueueDefaultPolicies.QueueOperationRetryPolicy,
AzureQueueDefaultPolicies.QueueOperationTimeout,
logger);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="queueName">Name of the queue to be connected to.</param>
/// <param name="deploymentId">The deployment id of the Azure service hosting this silo. It will be concatenated to the queueName.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
/// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param>
/// <param name="loggerFactory">logger factory used to create loggers</param>
public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string deploymentId, string storageConnectionString, TimeSpan? visibilityTimeout = null)
{
AzureStorageUtils.ValidateQueueName(queueName);
logger = loggerFactory.CreateLogger<AzureQueueDataManager>();
QueueName = deploymentId + "-" + queueName;
AzureStorageUtils.ValidateQueueName(QueueName);
connectionString = storageConnectionString;
messageVisibilityTimeout = visibilityTimeout;
queueOperationsClient = AzureStorageUtils.GetCloudQueueClient(
connectionString,
AzureQueueDefaultPolicies.QueueOperationRetryPolicy,
AzureQueueDefaultPolicies.QueueOperationTimeout,
logger);
}
/// <summary>
/// Initializes the connection to the queue.
/// </summary>
public async Task InitQueueAsync()
{
var startTime = DateTime.UtcNow;
try
{
// Retrieve a reference to a queue.
// Not sure if this is a blocking call or not. Did not find an alternative async API. Should probably use BeginListQueuesSegmented.
var myQueue = queueOperationsClient.GetQueueReference(QueueName);
// Create the queue if it doesn't already exist.
bool didCreate = await myQueue.CreateIfNotExistsAsync();
queue = myQueue;
logger.Info(ErrorCode.AzureQueue_01, "{0} Azure storage queue {1}", (didCreate ? "Created" : "Attached to"), QueueName);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "CreateIfNotExist", ErrorCode.AzureQueue_02);
}
finally
{
CheckAlertSlowAccess(startTime, "InitQueue_Async");
}
}
/// <summary>
/// Deletes the queue.
/// </summary>
public async Task DeleteQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName);
if (await queueRef.DeleteIfExistsAsync())
{
logger.Info(ErrorCode.AzureQueue_03, "Deleted Azure Queue {0}", QueueName);
}
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteQueue", ErrorCode.AzureQueue_04);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueue");
}
}
/// <summary>
/// Clears the queue.
/// </summary>
public async Task ClearQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Clearing a queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName);
await queueRef.ClearAsync();
logger.Info(ErrorCode.AzureQueue_05, "Cleared Azure Queue {0}", QueueName);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "ClearQueue", ErrorCode.AzureQueue_06);
}
finally
{
CheckAlertSlowAccess(startTime, "ClearQueue");
}
}
/// <summary>
/// Adds a new message to the queue.
/// </summary>
/// <param name="message">Message to be added to the queue.</param>
public async Task AddQueueMessage(CloudQueueMessage message)
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Adding message {0} to queue: {1}", message, QueueName);
try
{
await queue.AddMessageAsync(message);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "AddQueueMessage", ErrorCode.AzureQueue_07);
}
finally
{
CheckAlertSlowAccess(startTime, "AddQueueMessage");
}
}
/// <summary>
/// Peeks in the queue for latest message, without dequeueing it.
/// </summary>
public async Task<CloudQueueMessage> PeekQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Peeking a message from queue: {0}", QueueName);
try
{
return await queue.PeekMessageAsync();
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "PeekQueueMessage", ErrorCode.AzureQueue_08);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "PeekQueueMessage");
}
}
/// <summary>
/// Gets a new message from the queue.
/// </summary>
public async Task<CloudQueueMessage> GetQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting a message from queue: {0}", QueueName);
try
{
//BeginGetMessage and EndGetMessage is not supported in netstandard, may be use GetMessageAsync
// http://msdn.microsoft.com/en-us/library/ee758456.aspx
// If no messages are visible in the queue, GetMessage returns null.
return await queue.GetMessageAsync(messageVisibilityTimeout, options: null, operationContext: null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessage", ErrorCode.AzureQueue_09);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetQueueMessage");
}
}
/// <summary>
/// Gets a number of new messages from the queue.
/// </summary>
/// <param name="count">Number of messages to get from the queue.</param>
public async Task<IEnumerable<CloudQueueMessage>> GetQueueMessages(int count = -1)
{
var startTime = DateTime.UtcNow;
if (count == -1)
{
count = CloudQueueMessage.MaxNumberOfMessagesToPeek;
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting up to {0} messages from queue: {1}", count, QueueName);
try
{
return await queue.GetMessagesAsync(count, messageVisibilityTimeout, options: null, operationContext: null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessages", ErrorCode.AzureQueue_10);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetQueueMessages");
}
}
/// <summary>
/// Deletes a messages from the queue.
/// </summary>
/// <param name="message">A message to be deleted from the queue.</param>
public async Task DeleteQueueMessage(CloudQueueMessage message)
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting a message from queue: {0}", QueueName);
try
{
await queue.DeleteMessageAsync(message.Id, message.PopReceipt);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteMessage", ErrorCode.AzureQueue_11);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueueMessage");
}
}
internal async Task GetAndDeleteQueueMessage()
{
CloudQueueMessage message = await GetQueueMessage();
await DeleteQueueMessage(message);
}
/// <summary>
/// Returns an approximate number of messages in the queue.
/// </summary>
public async Task<int> GetApproximateMessageCount()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("GetApproximateMessageCount a message from queue: {0}", QueueName);
try
{
await queue.FetchAttributesAsync();
return queue.ApproximateMessageCount.HasValue ? queue.ApproximateMessageCount.Value : 0;
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "FetchAttributes", ErrorCode.AzureQueue_12);
return 0; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetApproximateMessageCount");
}
}
private void CheckAlertSlowAccess(DateTime startOperation, string operation)
{
var timeSpan = DateTime.UtcNow - startOperation;
if (timeSpan > AzureQueueDefaultPolicies.QueueOperationTimeout)
{
logger.Warn(ErrorCode.AzureQueue_13, "Slow access to Azure queue {0} for {1}, which took {2}.", QueueName, operation, timeSpan);
}
}
private void ReportErrorAndRethrow(Exception exc, string operation, ErrorCode errorCode)
{
var errMsg = String.Format(
"Error doing {0} for Azure storage queue {1} " + Environment.NewLine
+ "Exception = {2}", operation, QueueName, exc);
logger.Error(errorCode, errMsg, exc);
throw new AggregateException(errMsg, exc);
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.Framework.Scenes.Hypergrid
{
public class HGSceneCommunicationService : SceneCommunicationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IHyperlinkService m_hg;
IHyperlinkService HyperlinkService
{
get
{
if (m_hg == null)
m_hg = m_scene.RequestModuleInterface<IHyperlinkService>();
return m_hg;
}
}
public HGSceneCommunicationService(CommunicationsManager commsMan) : base(commsMan)
{
}
/// <summary>
/// Try to teleport an agent to a new region.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="RegionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
/// <param name="flags"></param>
public override void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
Vector3 lookAt, uint teleportFlags)
{
if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
return;
bool destRegionUp = true;
IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
// Reset animations; the viewer does that in teleports.
avatar.Animator.ResetAnimations();
if (regionHandle == m_regionInfo.RegionHandle)
{
// Teleport within the same region
if (IsOutsideRegion(avatar.Scene, position) || position.Z < 0)
{
Vector3 emergencyPos = new Vector3(128, 128, 128);
m_log.WarnFormat(
"[HGSceneCommService]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
position, avatar.Name, avatar.UUID, emergencyPos);
position = emergencyPos;
}
// TODO: Get proper AVG Height
float localAVHeight = 1.56f;
float posZLimit = 22;
if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
{
posZLimit = (float) avatar.Scene.Heightmap[(int) position.X, (int) position.Y];
}
float newPosZ = posZLimit + localAVHeight;
if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
{
position.Z = newPosZ;
}
// Only send this if the event queue is null
if (eq == null)
avatar.ControllingClient.SendTeleportLocationStart();
avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
avatar.Teleport(position);
}
else
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion reg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
if (reg != null)
{
uint newRegionX = (uint)(reg.RegionHandle >> 40);
uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
///
/// Hypergrid mod start
///
///
bool isHyperLink = (HyperlinkService.GetHyperlinkRegion(reg.RegionHandle) != null);
bool isHomeUser = true;
ulong realHandle = regionHandle;
CachedUserInfo uinfo = m_commsProvider.UserProfileCacheService.GetUserDetails(avatar.UUID);
if (uinfo != null)
{
isHomeUser = HyperlinkService.IsLocalUser(uinfo.UserProfile.ID);
realHandle = m_hg.FindRegionHandle(regionHandle);
m_log.Debug("XXX ---- home user? " + isHomeUser + " --- hyperlink? " + isHyperLink + " --- real handle: " + realHandle.ToString());
}
///
/// Hypergrid mod stop
///
///
if (eq == null)
avatar.ControllingClient.SendTeleportLocationStart();
// Let's do DNS resolution only once in this process, please!
// This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
// it's actually doing a lot of work.
IPEndPoint endPoint = reg.ExternalEndPoint;
if (endPoint.Address == null)
{
// Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
destRegionUp = false;
}
if (destRegionUp)
{
// Fixing a bug where teleporting while sitting results in the avatar ending up removed from
// both regions
if (avatar.ParentID != (uint)0)
avatar.StandUp();
if (!avatar.ValidateAttachments())
{
avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
return;
}
// the avatar.Close below will clear the child region list. We need this below for (possibly)
// closing the child agents, so save it here (we need a copy as it is Clear()-ed).
//List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
// Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
// failure at this point (unlike a border crossing failure). So perhaps this can never fail
// once we reach here...
//avatar.Scene.RemoveCapsHandler(avatar.UUID);
string capsPath = String.Empty;
AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
agentCircuit.BaseFolder = UUID.Zero;
agentCircuit.InventoryFolder = UUID.Zero;
agentCircuit.startpos = position;
agentCircuit.child = true;
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
{
// brand new agent, let's create a new caps seed
agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
}
string reason = String.Empty;
//if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, teleportFlags, out reason))
{
avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
reason));
return;
}
// Let's close some agents
if (isHyperLink) // close them all except this one
{
List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
regions.Remove(avatar.Scene.RegionInfo.RegionHandle);
SendCloseChildAgentConnections(avatar.UUID, regions);
}
else // close just a few
avatar.CloseChildAgents(newRegionX, newRegionY);
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY) || isHyperLink)
{
capsPath
= "http://"
+ reg.ExternalHostName
+ ":"
+ reg.HttpPort
+ CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
if (eq != null)
{
#region IP Translation for NAT
IClientIPEndpoint ipepClient;
if (avatar.ClientView.TryGet(out ipepClient))
{
endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
}
#endregion
eq.EnableSimulator(realHandle, endPoint, avatar.UUID);
// ES makes the client send a UseCircuitCode message to the destination,
// which triggers a bunch of things there.
// So let's wait
Thread.Sleep(2000);
eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
}
else
{
avatar.ControllingClient.InformClientOfNeighbour(realHandle, endPoint);
// TODO: make Event Queue disablable!
}
}
else
{
// child agent already there
agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
+ "/CAPS/" + agentCircuit.CapsPath + "0000/";
}
//m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
// position, false);
//if (!m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
// position, false))
//{
// avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
// // We should close that agent we just created over at destination...
// List<ulong> lst = new List<ulong>();
// lst.Add(realHandle);
// SendCloseChildAgentAsync(avatar.UUID, lst);
// return;
//}
SetInTransit(avatar.UUID);
// Let's send a full update of the agent. This is a synchronous call.
AgentData agent = new AgentData();
avatar.CopyTo(agent);
agent.Position = position;
agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
"/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
m_log.DebugFormat(
"[CAPS]: Sending new CAPS seed url {0} to client {1}", agentCircuit.CapsPath, avatar.UUID);
///
/// Hypergrid mod: realHandle instead of reg.RegionHandle
///
///
if (eq != null)
{
eq.TeleportFinishEvent(realHandle, 13, endPoint,
4, teleportFlags, capsPath, avatar.UUID);
}
else
{
avatar.ControllingClient.SendRegionTeleport(realHandle, 13, endPoint, 4,
teleportFlags, capsPath);
}
///
/// Hypergrid mod stop
///
// TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
// trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
// that the client contacted the destination before we send the attachments and close things here.
if (!WaitForCallback(avatar.UUID))
{
// Client never contacted destination. Let's restore everything back
avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
ResetFromTransit(avatar.UUID);
// Yikes! We should just have a ref to scene here.
avatar.Scene.InformClientOfNeighbours(avatar);
// Finally, kill the agent we just created at the destination.
m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
return;
}
// Can't go back from here
if (KiPrimitive != null)
{
KiPrimitive(avatar.LocalId);
}
avatar.MakeChildAgent();
// CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
// Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
///
/// Hypergrid mod: extra check for isHyperLink
///
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY) || isHyperLink)
{
Thread.Sleep(5000);
avatar.Close();
CloseConnection(avatar.UUID);
}
// if (teleport success) // seems to be always success here
// the user may change their profile information in other region,
// so the userinfo in UserProfileCache is not reliable any more, delete it
if (avatar.Scene.NeedSceneCacheClear(avatar.UUID) || isHyperLink)
{
m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
m_log.DebugFormat(
"[HGSceneCommService]: User {0} is going to another region, profile cache removed",
avatar.UUID);
}
}
else
{
avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
}
}
else
{
// TP to a place that doesn't exist (anymore)
// Inform the viewer about that
avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
// and set the map-tile to '(Offline)'
uint regX, regY;
Utils.LongToUInts(regionHandle, out regX, out regY);
MapBlockData block = new MapBlockData();
block.X = (ushort)(regX / Constants.RegionSize);
block.Y = (ushort)(regY / Constants.RegionSize);
block.Access = 254; // == not there
List<MapBlockData> blocks = new List<MapBlockData>();
blocks.Add(block);
avatar.ControllingClient.SendMapBlock(blocks, 0);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Xml.Xsl.Xslt
{
using QilName = System.Xml.Xsl.Qil.QilName;
// Compiler scope manager keeps track of
// Variable declarations
// Namespace declarations
// Extension and excluded namespaces
internal sealed class CompilerScopeManager<V>
{
public enum ScopeFlags
{
BackwardCompatibility = 0x1,
ForwardCompatibility = 0x2,
CanHaveApplyImports = 0x4,
NsDecl = 0x10, // NS declaration
NsExcl = 0x20, // NS Extencion (null for ExcludeAll)
Variable = 0x40,
CompatibilityFlags = BackwardCompatibility | ForwardCompatibility,
InheritedFlags = CompatibilityFlags | CanHaveApplyImports,
ExclusiveFlags = NsDecl | NsExcl | Variable
}
public struct ScopeRecord
{
public int scopeCount;
public ScopeFlags flags;
public string ncName; // local-name for variable, prefix for namespace, null for extension or excluded namespace
public string nsUri; // namespace uri
public V value; // value for variable, null for namespace
// Exactly one of these three properties is true for every given record
public bool IsVariable { get { return (flags & ScopeFlags.Variable) != 0; } }
public bool IsNamespace { get { return (flags & ScopeFlags.NsDecl) != 0; } }
// public bool IsExNamespace { get { return (flags & ScopeFlags.NsExcl ) != 0; } }
}
// Number of predefined records minus one
private const int LastPredefRecord = 0;
private ScopeRecord[] _records = new ScopeRecord[32];
private int _lastRecord = LastPredefRecord;
// This is cache of records[lastRecord].scopeCount field;
// most often we will have PushScope()/PopScope pare over the same record.
// It has sence to avoid adresing this field through array access.
private int _lastScopes = 0;
public CompilerScopeManager()
{
// The prefix 'xml' is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace
_records[0].flags = ScopeFlags.NsDecl;
_records[0].ncName = "xml";
_records[0].nsUri = XmlReservedNs.NsXml;
}
public CompilerScopeManager(KeywordsTable atoms)
{
_records[0].flags = ScopeFlags.NsDecl;
_records[0].ncName = atoms.Xml;
_records[0].nsUri = atoms.UriXml;
}
public void EnterScope()
{
_lastScopes++;
}
public void ExitScope()
{
if (0 < _lastScopes)
{
_lastScopes--;
}
else
{
while (_records[--_lastRecord].scopeCount == 0)
{
}
_lastScopes = _records[_lastRecord].scopeCount;
_lastScopes--;
}
}
[Conditional("DEBUG")]
public void CheckEmpty()
{
ExitScope();
Debug.Assert(_lastRecord == 0 && _lastScopes == 0, "PushScope() and PopScope() calls are unbalanced");
}
// returns true if ns decls was added to scope
public bool EnterScope(NsDecl nsDecl)
{
_lastScopes++;
bool hasNamespaces = false;
bool excludeAll = false;
for (; nsDecl != null; nsDecl = nsDecl.Prev)
{
if (nsDecl.NsUri == null)
{
Debug.Assert(nsDecl.Prefix == null, "NS may be null only when prefix is null where it is used for extension-element-prefixes='#all'");
excludeAll = true;
}
else if (nsDecl.Prefix == null)
{
AddExNamespace(nsDecl.NsUri);
}
else
{
hasNamespaces = true;
AddNsDeclaration(nsDecl.Prefix, nsDecl.NsUri);
}
}
if (excludeAll)
{
// #all should be on the top of the stack, becase all NSs on this element should be excluded as well
AddExNamespace(null);
}
return hasNamespaces;
}
private void AddRecord()
{
// Store cached fields:
_records[_lastRecord].scopeCount = _lastScopes;
// Extend record buffer:
if (++_lastRecord == _records.Length)
{
ScopeRecord[] newRecords = new ScopeRecord[_lastRecord * 2];
Array.Copy(_records, 0, newRecords, 0, _lastRecord);
_records = newRecords;
}
// reset scope count:
_lastScopes = 0;
}
private void AddRecord(ScopeFlags flag, string ncName, string uri, V value)
{
Debug.Assert(flag == (flag & ScopeFlags.ExclusiveFlags) && (flag & (flag - 1)) == 0 && flag != 0, "One exclusive flag");
Debug.Assert(uri != null || ncName == null, "null, null means exclude '#all'");
ScopeFlags flags = _records[_lastRecord].flags;
bool canReuseLastRecord = (_lastScopes == 0) && (flags & ScopeFlags.ExclusiveFlags) == 0;
if (!canReuseLastRecord)
{
AddRecord();
flags &= ScopeFlags.InheritedFlags;
}
_records[_lastRecord].flags = flags | flag;
_records[_lastRecord].ncName = ncName;
_records[_lastRecord].nsUri = uri;
_records[_lastRecord].value = value;
}
private void SetFlag(ScopeFlags flag, bool value)
{
Debug.Assert(flag == (flag & ScopeFlags.InheritedFlags) && (flag & (flag - 1)) == 0 && flag != 0, "one inherited flag");
ScopeFlags flags = _records[_lastRecord].flags;
if (((flags & flag) != 0) != value)
{
// lastScopes == records[lastRecord].scopeCount; // we know this because we are cashing it.
bool canReuseLastRecord = _lastScopes == 0; // last record is from last scope
if (!canReuseLastRecord)
{
AddRecord();
flags &= ScopeFlags.InheritedFlags;
}
if (flag == ScopeFlags.CanHaveApplyImports)
{
flags ^= flag;
}
else
{
flags &= ~ScopeFlags.CompatibilityFlags;
if (value)
{
flags |= flag;
}
}
_records[_lastRecord].flags = flags;
}
Debug.Assert((_records[_lastRecord].flags & ScopeFlags.CompatibilityFlags) != ScopeFlags.CompatibilityFlags,
"BackwardCompatibility and ForwardCompatibility flags are mutually exclusive"
);
}
// Add variable to the current scope. Returns false in case of duplicates.
public void AddVariable(QilName varName, V value)
{
Debug.Assert(varName.LocalName != null && varName.NamespaceUri != null);
AddRecord(ScopeFlags.Variable, varName.LocalName, varName.NamespaceUri, value);
}
// Since the prefix might be redefined in an inner scope, we search in descending order in [to, from]
// If interval is empty (from < to), the function returns null.
private string LookupNamespace(string prefix, int from, int to)
{
Debug.Assert(prefix != null);
for (int record = from; to <= record; --record)
{
string recPrefix, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recPrefix, out recNsUri);
if (
(flags & ScopeFlags.NsDecl) != 0 &&
recPrefix == prefix
)
{
return recNsUri;
}
}
return null;
}
public string LookupNamespace(string prefix)
{
return LookupNamespace(prefix, _lastRecord, 0);
}
private static ScopeFlags GetName(ref ScopeRecord re, out string prefix, out string nsUri)
{
prefix = re.ncName;
nsUri = re.nsUri;
return re.flags;
}
public void AddNsDeclaration(string prefix, string nsUri)
{
AddRecord(ScopeFlags.NsDecl, prefix, nsUri, default(V));
}
public void AddExNamespace(string nsUri)
{
AddRecord(ScopeFlags.NsExcl, null, nsUri, default(V));
}
public bool IsExNamespace(string nsUri)
{
Debug.Assert(nsUri != null);
int exAll = 0;
for (int record = _lastRecord; 0 <= record; record--)
{
string recPrefix, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recPrefix, out recNsUri);
if ((flags & ScopeFlags.NsExcl) != 0)
{
Debug.Assert(recPrefix == null);
if (recNsUri == nsUri)
{
return true; // This namespace is excluded
}
if (recNsUri == null)
{
exAll = record; // #all namespaces below are excluded
}
}
else if (
exAll != 0 &&
(flags & ScopeFlags.NsDecl) != 0 &&
recNsUri == nsUri
)
{
// We need to check that this namespace wasn't undefined before last "#all"
bool undefined = false;
for (int prev = record + 1; prev < exAll; prev++)
{
string prevPrefix, prevNsUri;
ScopeFlags prevFlags = GetName(ref _records[prev], out prevPrefix, out prevNsUri);
if (
(flags & ScopeFlags.NsDecl) != 0 &&
prevPrefix == recPrefix
)
{
// We don't care if records[prev].nsUri == records[record].nsUri.
// In this case the namespace was already undefined above.
undefined = true;
break;
}
}
if (!undefined)
{
return true;
}
}
}
return false;
}
private int SearchVariable(string localName, string uri)
{
Debug.Assert(localName != null);
for (int record = _lastRecord; 0 <= record; --record)
{
string recLocal, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recLocal, out recNsUri);
if (
(flags & ScopeFlags.Variable) != 0 &&
recLocal == localName &&
recNsUri == uri
)
{
return record;
}
}
return -1;
}
public V LookupVariable(string localName, string uri)
{
int record = SearchVariable(localName, uri);
return (record < 0) ? default(V) : _records[record].value;
}
public bool IsLocalVariable(string localName, string uri)
{
int record = SearchVariable(localName, uri);
while (0 <= --record)
{
if (_records[record].scopeCount != 0)
{
return true;
}
}
return false;
}
public bool ForwardCompatibility
{
get { return (_records[_lastRecord].flags & ScopeFlags.ForwardCompatibility) != 0; }
set { SetFlag(ScopeFlags.ForwardCompatibility, value); }
}
public bool BackwardCompatibility
{
get { return (_records[_lastRecord].flags & ScopeFlags.BackwardCompatibility) != 0; }
set { SetFlag(ScopeFlags.BackwardCompatibility, value); }
}
public bool CanHaveApplyImports
{
get { return (_records[_lastRecord].flags & ScopeFlags.CanHaveApplyImports) != 0; }
set { SetFlag(ScopeFlags.CanHaveApplyImports, value); }
}
internal System.Collections.Generic.IEnumerable<ScopeRecord> GetActiveRecords()
{
int currentRecord = _lastRecord + 1;
// This logic comes from NamespaceEnumerator.MoveNext but also returns variables
while (LastPredefRecord < --currentRecord)
{
if (_records[currentRecord].IsNamespace)
{
// This is a namespace declaration
if (LookupNamespace(_records[currentRecord].ncName, _lastRecord, currentRecord + 1) != null)
{
continue;
}
// Its prefix has not been redefined later in [currentRecord + 1, lastRecord]
}
yield return _records[currentRecord];
}
}
public NamespaceEnumerator GetEnumerator()
{
return new NamespaceEnumerator(this);
}
internal struct NamespaceEnumerator
{
private readonly CompilerScopeManager<V> _scope;
private readonly int _lastRecord;
private int _currentRecord;
public NamespaceEnumerator(CompilerScopeManager<V> scope)
{
_scope = scope;
_lastRecord = scope._lastRecord;
_currentRecord = _lastRecord + 1;
}
public bool MoveNext()
{
while (LastPredefRecord < --_currentRecord)
{
if (_scope._records[_currentRecord].IsNamespace)
{
// This is a namespace declaration
if (_scope.LookupNamespace(_scope._records[_currentRecord].ncName, _lastRecord, _currentRecord + 1) == null)
{
// Its prefix has not been redefined later in [currentRecord + 1, lastRecord]
return true;
}
}
}
return false;
}
public ScopeRecord Current
{
get
{
Debug.Assert(LastPredefRecord <= _currentRecord && _currentRecord <= _scope._lastRecord, "MoveNext() either was not called or returned false");
Debug.Assert(_scope._records[_currentRecord].IsNamespace);
return _scope._records[_currentRecord];
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting.Indentation
{
internal abstract class AbstractSmartTokenFormatterCommandHandler :
ICommandHandler<ReturnKeyCommandArgs>
{
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
public AbstractSmartTokenFormatterCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_undoHistoryRegistry = undoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected abstract ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<IFormattingRule> formattingRules, SyntaxNode root);
protected abstract bool UseSmartTokenFormatter(SyntaxNode root, TextLine line, IEnumerable<IFormattingRule> formattingRules, OptionSet options, CancellationToken cancellationToken);
protected abstract bool IsInvalidToken(SyntaxToken token);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document, int position);
/// <returns>True if any change is made.</returns>
protected bool FormatToken(ITextView view, Document document, SyntaxToken token, IEnumerable<IFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var formatter = CreateSmartTokenFormatter(document.Options, formattingRules, root);
var changes = formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).WaitAndGetResult(cancellationToken);
if (changes.Count == 0)
{
return false;
}
using (var transaction = CreateEditTransaction(view, EditorFeaturesResources.Format_Token))
{
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance;
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, changes, cancellationToken);
transaction.Complete();
}
return true;
}
public CommandState GetCommandState(ReturnKeyCommandArgs args, Func<CommandState> nextHandler)
{
return nextHandler();
}
public void ExecuteCommand(ReturnKeyCommandArgs args, Action nextHandler)
{
var textView = args.TextView;
var oldCaretPoint = textView.GetCaretPoint(args.SubjectBuffer);
nextHandler();
// A feature like completion handled the return key but did not pass it on to the editor.
var newCaretPoint = textView.GetCaretPoint(args.SubjectBuffer);
if (textView.Selection.IsEmpty && oldCaretPoint.HasValue && newCaretPoint.HasValue &&
oldCaretPoint.Value.GetContainingLine().LineNumber == newCaretPoint.Value.GetContainingLine().LineNumber)
{
return;
}
if (args.SubjectBuffer.CanApplyChangeDocumentToWorkspace())
{
ExecuteCommandWorker(args, CancellationToken.None);
}
}
internal void ExecuteCommandWorker(ReturnKeyCommandArgs args, CancellationToken cancellationToken)
{
var textView = args.TextView;
var caretPoint = textView.GetCaretPoint(args.SubjectBuffer);
if (args.SubjectBuffer.GetOption(FormattingOptions.SmartIndent) != FormattingOptions.IndentStyle.Smart ||
!caretPoint.HasValue)
{
return;
}
var currentPosition = caretPoint.Value;
var document = currentPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var formattingRules = this.GetFormattingRules(document, currentPosition.Position);
// see whether we should use token formatter
if (TryFormatUsingTokenFormatter(textView, args.SubjectBuffer, document, formattingRules, cancellationToken))
{
return;
}
// check whether editor would have used smart indenter
if (EditorHandled(textView) && !RequireReadjustment(textView, args.SubjectBuffer))
{
// editor already took care of smart indentation.
return;
}
// check whether we can do it ourselves
if (!CanHandleOurselves(textView, args.SubjectBuffer))
{
return;
}
var indentationService = document.GetLanguageService<ISynchronousIndentationService>();
var indentation = indentationService.GetDesiredIndentation(document,
currentPosition.GetContainingLine().LineNumber, cancellationToken);
// looks like we can't.
if (!indentation.HasValue)
{
return;
}
HandleOurselves(textView, args.SubjectBuffer, indentation.Value.GetIndentation(textView, currentPosition.GetContainingLine()));
}
private bool RequireReadjustment(ITextView view, ITextBuffer subjectBuffer)
{
var caretInSubjectBuffer = view.GetCaretPoint(subjectBuffer).Value;
var lineInSubjectBuffer = caretInSubjectBuffer.GetContainingLine();
var currentOffset = caretInSubjectBuffer - lineInSubjectBuffer.Start;
var firstNonWhitespaceIndex = lineInSubjectBuffer.GetFirstNonWhitespaceOffset();
if (!firstNonWhitespaceIndex.HasValue || currentOffset >= firstNonWhitespaceIndex.Value)
{
return false;
}
// there are whitespace after caret position (which smart indentation has put),
// we might need to re-adjust indentation
return true;
}
private void HandleOurselves(ITextView view, ITextBuffer subjectBuffer, int indentation)
{
var lineInSubjectBuffer = view.GetCaretPoint(subjectBuffer).Value.GetContainingLine();
var lengthOfLine = lineInSubjectBuffer.GetColumnFromLineOffset(lineInSubjectBuffer.Length, view.Options);
// check whether we are dealing with virtual space or real space
if (indentation > lengthOfLine)
{
// we are dealing with virtual space
var caretPosition = view.GetVirtualCaretPoint(subjectBuffer);
var positionInVirtualSpace = new VirtualSnapshotPoint(caretPosition.Value.Position, indentation - lineInSubjectBuffer.Length);
view.TryMoveCaretToAndEnsureVisible(positionInVirtualSpace);
return;
}
// we are dealing with real space. check whether we need to just set caret position or move text
var firstNonWhitespaceIndex = lineInSubjectBuffer.GetFirstNonWhitespaceOffset();
if (firstNonWhitespaceIndex.HasValue)
{
// if leading whitespace is not what we expect, re-adjust indentation
var columnOfFirstNonWhitespace = lineInSubjectBuffer.GetColumnFromLineOffset(firstNonWhitespaceIndex.Value, view.Options);
if (columnOfFirstNonWhitespace != indentation)
{
ReadjustIndentation(view, subjectBuffer, firstNonWhitespaceIndex.Value, indentation);
return;
}
}
// okay, it is an empty line with some whitespaces
Contract.Requires(indentation <= lineInSubjectBuffer.Length);
var offset = GetOffsetFromIndentation(indentation, view.Options);
view.TryMoveCaretToAndEnsureVisible(lineInSubjectBuffer.Start.Add(offset));
}
private int GetOffsetFromIndentation(int indentation, IEditorOptions option)
{
int numberOfTabs = 0;
int numberOfSpaces = Math.Max(0, indentation);
if (!option.IsConvertTabsToSpacesEnabled())
{
var tabSize = option.GetTabSize();
numberOfTabs = indentation / tabSize;
numberOfSpaces -= numberOfTabs * tabSize;
}
return numberOfTabs + numberOfSpaces;
}
/// <summary>
/// re-adjust caret position to be the beginning of first text on the line. and make sure the text start at the given indentation
/// </summary>
private static void ReadjustIndentation(ITextView view, ITextBuffer subjectBuffer, int firstNonWhitespaceIndex, int indentation)
{
var lineInSubjectBuffer = view.GetCaretPoint(subjectBuffer).Value.GetContainingLine();
// first set the caret at the beginning of the text on the line
view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(lineInSubjectBuffer.Snapshot, lineInSubjectBuffer.Start + firstNonWhitespaceIndex));
var document = lineInSubjectBuffer.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var options = document.Options;
// and then, insert the text
document.Project.Solution.Workspace.ApplyTextChanges(document.Id,
new TextChange(
new TextSpan(
lineInSubjectBuffer.Start.Position, firstNonWhitespaceIndex),
indentation.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize))),
CancellationToken.None);
}
/// <summary>
/// check whether we can smart indent ourselves. we only attempt to smart indent ourselves
/// if the line in subject buffer we do smart indenting maps back to the view as it is and
/// if it starts from the beginning of the line
/// </summary>
private bool CanHandleOurselves(ITextView view, ITextBuffer subjectBuffer)
{
var lineInSubjectBuffer = view.GetCaretPoint(subjectBuffer).Value.GetContainingLine();
// first, make sure whole line is map back to the view
if (view.GetSpanInView(lineInSubjectBuffer.ExtentIncludingLineBreak).Count != 1)
{
return false;
}
// now check, start position of the line is start position in the view
var caretPosition = view.GetPositionInView(view.GetVirtualCaretPoint(subjectBuffer).Value.Position);
var containingLineCaret = caretPosition.Value.GetContainingLine();
var startPositionSubjectBuffer = view.GetPositionInView(lineInSubjectBuffer.Start);
var startPositionCaret = view.GetPositionInView(containingLineCaret.Start);
if (!startPositionSubjectBuffer.HasValue ||
!startPositionCaret.HasValue ||
startPositionCaret.Value != startPositionSubjectBuffer.Value)
{
// if start position of subject buffer is not equal to start position of view line,
// we can't use the indenter
return false;
}
// get containing line in view from start position of the caret in view
var containingLineView = startPositionCaret.Value.GetContainingLine();
// make sure line start at the beginning of the line
if (containingLineView.Start != startPositionCaret.Value)
{
return false;
}
return true;
}
/// <summary>
/// check whether editor smart indenter mechanism handled this case already
/// </summary>
private bool EditorHandled(ITextView view)
{
var caretPosition = view.Caret.Position.VirtualBufferPosition;
return caretPosition.IsInVirtualSpace || (caretPosition.Position != view.Caret.Position.BufferPosition.GetContainingLine().Start);
}
/// <summary>
/// check whether we can do automatic formatting using token formatter instead of smart indenter for the "enter" key
/// </summary>
private bool TryFormatUsingTokenFormatter(ITextView view, ITextBuffer subjectBuffer, Document document, IEnumerable<IFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var position = view.GetCaretPoint(subjectBuffer).Value;
var line = position.GetContainingLine().AsTextLine();
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var options = document.Options;
if (!UseSmartTokenFormatter(root, line, formattingRules, options, cancellationToken))
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
var token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
// when undo, make sure it undo the caret movement I did below
using (var transaction = CreateEditTransaction(view, EditorFeaturesResources.Smart_Indenting))
{
// if caret position is before the token, make sure we put caret at the beginning of the token so that caret
// is at the right position after formatting
var currentSnapshot = subjectBuffer.CurrentSnapshot;
if (position.Position < token.SpanStart)
{
view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(currentSnapshot, token.SpanStart));
}
if (FormatToken(view, document, token, formattingRules, cancellationToken))
{
transaction.Complete();
}
else
{
transaction.Cancel();
}
}
return true;
}
/// <summary>
/// create caret preserving edit transaction
/// </summary>
protected CaretPreservingEditTransaction CreateEditTransaction(ITextView view, string description)
{
return new CaretPreservingEditTransaction(description, view, _undoHistoryRegistry, _editorOperationsFactoryService);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class CopyToStrAIntTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
StringCollection sc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
string[] destination;
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] StringCollection is constructed as expected
//-----------------------------------------------------------------
sc = new StringCollection();
// [] Copy empty collection into empty array
//
destination = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
destination[i] = "";
}
sc.CopyTo(destination, 0);
if (destination.Length != values.Length)
{
Assert.False(true, string.Format("Error, altered array after copying empty collection"));
}
if (destination.Length == values.Length)
{
for (int i = 0; i < values.Length; i++)
{
if (String.Compare(destination[i], "") != 0)
{
Assert.False(true, string.Format("Error, item = \"{1}\" instead of \"{2}\" after copying empty collection", i, destination[i], ""));
}
}
}
// [] Copy empty collection into non-empty array
//
destination = values;
sc.CopyTo(destination, 0);
if (destination.Length != values.Length)
{
Assert.False(true, string.Format("Error, altered array after copying empty collection"));
}
if (destination.Length == values.Length)
{
for (int i = 0; i < values.Length; i++)
{
if (String.Compare(destination[i], values[i]) != 0)
{
Assert.False(true, string.Format("Error, altered item {0} after copying empty collection", i));
}
}
}
//
// [] add simple strings and CopyTo([], 0)
cnt = sc.Count;
sc.AddRange(values);
if (sc.Count != values.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
}
destination = new string[values.Length];
sc.CopyTo(destination, 0);
for (int i = 0; i < values.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]));
}
}
// [] add simple strings and CopyTo([], middle_index)
//
sc.Clear();
cnt = sc.Count;
sc.AddRange(values);
if (sc.Count != values.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
}
destination = new string[values.Length * 2];
sc.CopyTo(destination, values.Length);
for (int i = 0; i < values.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i + values.Length]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + values.Length], sc[i]));
}
}
//
// Intl strings
// [] add intl strings and CopyTo([], 0)
//
string[] intlValues = new string[values.Length];
// fill array with unique strings
//
for (int i = 0; i < values.Length; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
sc.Clear();
sc.AddRange(intlValues);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = new string[intlValues.Length];
sc.CopyTo(destination, 0);
for (int i = 0; i < intlValues.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]));
}
}
//
// Intl strings
// [] add intl strings and CopyTo([], middle_index)
//
sc.Clear();
sc.AddRange(intlValues);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = new string[intlValues.Length * 2];
sc.CopyTo(destination, intlValues.Length);
for (int i = 0; i < intlValues.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i + intlValues.Length]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + intlValues.Length], sc[i]));
}
}
//
// [] CopyTo(null, int)
//
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = null;
Assert.Throws<ArgumentNullException>(() => { sc.CopyTo(destination, 0); });
//
// [] CopyTo(string[], -1)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentOutOfRangeException>(() => { sc.CopyTo(destination, -1); });
//
// [] CopyTo(string[], upperBound+1)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length); });
//
// [] CopyTo(string[], upperBound+2)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length + 1))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length); });
//
// [] CopyTo(string[], not_enough_space)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length / 2); });
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
internal sealed unsafe class SocketAsyncEngine
{
//
// Encapsulates a particular SocketAsyncContext object's access to a SocketAsyncEngine.
//
public readonly struct Token
{
private readonly SocketAsyncEngine _engine;
private readonly IntPtr _handle;
public Token(SocketAsyncContext context)
{
AllocateToken(context, out _engine, out _handle);
}
public bool WasAllocated
{
get { return _engine != null; }
}
public void Free()
{
if (WasAllocated)
{
_engine.FreeHandle(_handle);
}
}
public bool TryRegister(SafeSocketHandle socket, out Interop.Error error)
{
Debug.Assert(WasAllocated, "Expected WasAllocated to be true");
return _engine.TryRegister(socket, _handle, out error);
}
}
private const int EventBufferCount =
#if DEBUG
32;
#else
1024;
#endif
private static readonly object s_lock = new object();
// In debug builds, force there to be 2 engines. In release builds, use half the number of processors when
// there are at least 6. The lower bound is to avoid using multiple engines on systems which aren't servers.
private static readonly int EngineCount =
#if DEBUG
2;
#else
Environment.ProcessorCount >= 6 ? Environment.ProcessorCount / 2 : 1;
#endif
//
// The current engines. We replace an engine when it runs out of "handle" values.
// Must be accessed under s_lock.
//
private static readonly SocketAsyncEngine[] s_currentEngines = new SocketAsyncEngine[EngineCount];
private static int s_allocateFromEngine = 0;
private readonly IntPtr _port;
private readonly Interop.Sys.SocketEvent* _buffer;
//
// The read and write ends of a native pipe, used to signal that this instance's event loop should stop
// processing events.
//
private readonly int _shutdownReadPipe;
private readonly int _shutdownWritePipe;
//
// Each SocketAsyncContext is associated with a particular "handle" value, used to identify that
// SocketAsyncContext when events are raised. These handle values are never reused, because we do not have
// a way to ensure that we will never see an event for a socket/handle that has been freed. Instead, we
// allocate monotonically increasing handle values up to some limit; when we would exceed that limit,
// we allocate a new SocketAsyncEngine (and thus a new event port) and start the handle values over at zero.
// Thus we can uniquely identify a given SocketAsyncContext by the *pair* {SocketAsyncEngine, handle},
// and avoid any issues with misidentifying the target of an event we read from the port.
//
#if DEBUG
//
// In debug builds, force rollover to new SocketAsyncEngine instances so that code doesn't go untested, since
// it's very unlikely that the "real" limits will ever be reached in test code.
//
private static readonly IntPtr MaxHandles = (IntPtr)(EventBufferCount * 2);
#else
//
// In release builds, we use *very* high limits. No 64-bit process running on release builds should ever
// reach the handle limit for a single event port, and even 32-bit processes should see this only very rarely.
//
private static readonly IntPtr MaxHandles = IntPtr.Size == 4 ? (IntPtr)int.MaxValue : (IntPtr)long.MaxValue;
#endif
private static readonly IntPtr MinHandlesForAdditionalEngine = EngineCount == 1 ? MaxHandles : (IntPtr)32;
//
// Sentinel handle value to identify events from the "shutdown pipe," used to signal an event loop to stop
// processing events.
//
private static readonly IntPtr ShutdownHandle = (IntPtr)(-1);
//
// The next handle value to be allocated for this event port.
// Must be accessed under s_lock.
//
private IntPtr _nextHandle;
//
// Count of handles that have been allocated for this event port, but not yet freed.
// Must be accessed under s_lock.
//
private IntPtr _outstandingHandles;
//
// Maps handle values to SocketAsyncContext instances.
//
private readonly ConcurrentDictionary<IntPtr, SocketAsyncContext> _handleToContextMap = new ConcurrentDictionary<IntPtr, SocketAsyncContext>();
//
// True if we've reached the handle value limit for this event port, and thus must allocate a new event port
// on the next handle allocation.
//
private bool IsFull { get { return _nextHandle == MaxHandles; } }
// True if we've don't have sufficient active sockets to allow allocating a new engine.
private bool HasLowNumberOfSockets
{
get
{
return IntPtr.Size == 4 ? _outstandingHandles.ToInt32() < MinHandlesForAdditionalEngine.ToInt32() :
_outstandingHandles.ToInt64() < MinHandlesForAdditionalEngine.ToInt64();
}
}
//
// Allocates a new {SocketAsyncEngine, handle} pair.
//
private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle)
{
lock (s_lock)
{
engine = s_currentEngines[s_allocateFromEngine];
if (engine == null)
{
// We minimize the number of engines on applications that have a low number of concurrent sockets.
for (int i = 0; i < s_allocateFromEngine; i++)
{
var previousEngine = s_currentEngines[i];
if (previousEngine == null || previousEngine.HasLowNumberOfSockets)
{
s_allocateFromEngine = i;
engine = previousEngine;
break;
}
}
if (engine == null)
{
s_currentEngines[s_allocateFromEngine] = engine = new SocketAsyncEngine();
}
}
handle = engine.AllocateHandle(context);
if (engine.IsFull)
{
// We'll need to create a new event port for the next handle.
s_currentEngines[s_allocateFromEngine] = null;
}
// Round-robin to the next engine once we have sufficient sockets on this one.
if (!engine.HasLowNumberOfSockets)
{
s_allocateFromEngine = (s_allocateFromEngine + 1) % EngineCount;
}
}
}
private IntPtr AllocateHandle(SocketAsyncContext context)
{
Debug.Assert(Monitor.IsEntered(s_lock), "Expected s_lock to be held");
Debug.Assert(!IsFull, "Expected !IsFull");
IntPtr handle = _nextHandle;
_handleToContextMap.TryAdd(handle, context);
_nextHandle = IntPtr.Add(_nextHandle, 1);
_outstandingHandles = IntPtr.Add(_outstandingHandles, 1);
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
return handle;
}
private void FreeHandle(IntPtr handle)
{
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
bool shutdownNeeded = false;
lock (s_lock)
{
if (_handleToContextMap.TryRemove(handle, out _))
{
_outstandingHandles = IntPtr.Subtract(_outstandingHandles, 1);
Debug.Assert(_outstandingHandles.ToInt64() >= 0, $"Unexpected _outstandingHandles: {_outstandingHandles}");
//
// If we've allocated all possible handles for this instance, and freed them all, then
// we don't need the event loop any more, and can reclaim resources.
//
if (IsFull && _outstandingHandles == IntPtr.Zero)
{
shutdownNeeded = true;
}
}
}
//
// Signal shutdown outside of the lock to reduce contention.
//
if (shutdownNeeded)
{
RequestEventLoopShutdown();
}
}
private SocketAsyncEngine()
{
_port = (IntPtr)(-1);
_shutdownReadPipe = -1;
_shutdownWritePipe = -1;
try
{
//
// Create the event port and buffer
//
Interop.Error err = Interop.Sys.CreateSocketEventPort(out _port);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException(err);
}
err = Interop.Sys.CreateSocketEventBuffer(EventBufferCount, out _buffer);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException(err);
}
//
// Create the pipe for signaling shutdown, and register for "read" events for the pipe. Now writing
// to the pipe will send an event to the event loop.
//
int* pipeFds = stackalloc int[2];
int pipeResult = Interop.Sys.Pipe(pipeFds, Interop.Sys.PipeFlags.O_CLOEXEC);
if (pipeResult != 0)
{
throw new InternalException(pipeResult);
}
_shutdownReadPipe = pipeFds[Interop.Sys.ReadEndOfPipe];
_shutdownWritePipe = pipeFds[Interop.Sys.WriteEndOfPipe];
err = Interop.Sys.TryChangeSocketEventRegistration(_port, (IntPtr)_shutdownReadPipe, Interop.Sys.SocketEvents.None, Interop.Sys.SocketEvents.Read, ShutdownHandle);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException(err);
}
//
// Start the event loop on its own thread.
//
bool suppressFlow = !ExecutionContext.IsFlowSuppressed();
try
{
if (suppressFlow) ExecutionContext.SuppressFlow();
Task.Factory.StartNew(
s => ((SocketAsyncEngine)s).EventLoop(),
this,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
finally
{
if (suppressFlow) ExecutionContext.RestoreFlow();
}
}
catch
{
FreeNativeResources();
throw;
}
}
private void EventLoop()
{
try
{
bool shutdown = false;
while (!shutdown)
{
int numEvents = EventBufferCount;
Interop.Error err = Interop.Sys.WaitForSocketEvents(_port, _buffer, &numEvents);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException(err);
}
// The native shim is responsible for ensuring this condition.
Debug.Assert(numEvents > 0, $"Unexpected numEvents: {numEvents}");
for (int i = 0; i < numEvents; i++)
{
IntPtr handle = _buffer[i].Data;
if (handle == ShutdownHandle)
{
shutdown = true;
}
else
{
Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}");
_handleToContextMap.TryGetValue(handle, out SocketAsyncContext context);
if (context != null)
{
context.HandleEvents(_buffer[i].Events);
context = null;
}
}
}
}
FreeNativeResources();
}
catch (Exception e)
{
Environment.FailFast("Exception thrown from SocketAsyncEngine event loop: " + e.ToString(), e);
}
}
private void RequestEventLoopShutdown()
{
//
// Write to the pipe, which will wake up the event loop and cause it to exit.
//
byte b = 1;
int bytesWritten = Interop.Sys.Write(_shutdownWritePipe, &b, 1);
if (bytesWritten != 1)
{
throw new InternalException(bytesWritten);
}
}
private void FreeNativeResources()
{
if (_shutdownReadPipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownReadPipe);
}
if (_shutdownWritePipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownWritePipe);
}
if (_buffer != null)
{
Interop.Sys.FreeSocketEventBuffer(_buffer);
}
if (_port != (IntPtr)(-1))
{
Interop.Sys.CloseSocketEventPort(_port);
}
}
private bool TryRegister(SafeSocketHandle socket, IntPtr handle, out Interop.Error error)
{
error = Interop.Sys.TryChangeSocketEventRegistration(_port, socket, Interop.Sys.SocketEvents.None,
Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write, handle);
return error == Interop.Error.SUCCESS;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="SearchMailboxesRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the SearchMailboxesRequest class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a SearchMailboxesRequest request.
/// </summary>
internal sealed class SearchMailboxesRequest : MultiResponseServiceRequest<SearchMailboxesResponse>, IJsonSerializable, IDiscoveryVersionable
{
private List<MailboxQuery> searchQueries = new List<MailboxQuery>();
private SearchResultType searchResultType = SearchResultType.PreviewOnly;
private SortDirection sortOrder = SortDirection.Ascending;
private string sortByProperty;
private bool performDeduplication;
private int pageSize;
private string pageItemReference;
private SearchPageDirection pageDirection = SearchPageDirection.Next;
private PreviewItemResponseShape previewItemResponseShape;
/// <summary>
/// Initializes a new instance of the <see cref="SearchMailboxesRequest"/> class.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="errorHandlingMode"> Indicates how errors should be handled.</param>
internal SearchMailboxesRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode)
: base(service, errorHandlingMode)
{
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="responseIndex">Index of the response.</param>
/// <returns>Service response.</returns>
internal override SearchMailboxesResponse CreateServiceResponse(ExchangeService service, int responseIndex)
{
return new SearchMailboxesResponse();
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.SearchMailboxesResponse;
}
/// <summary>
/// Gets the name of the response message XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseMessageXmlElementName()
{
return XmlElementNames.SearchMailboxesResponseMessage;
}
/// <summary>
/// Gets the expected response message count.
/// </summary>
/// <returns>Number of expected response messages.</returns>
internal override int GetExpectedResponseMessageCount()
{
return 1;
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.SearchMailboxes;
}
/// <summary>
/// Validate request.
/// </summary>
internal override void Validate()
{
base.Validate();
if (this.SearchQueries == null || this.SearchQueries.Count == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
foreach (MailboxQuery searchQuery in this.SearchQueries)
{
if (searchQuery.MailboxSearchScopes == null || searchQuery.MailboxSearchScopes.Length == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
foreach (MailboxSearchScope searchScope in searchQuery.MailboxSearchScopes)
{
if (searchScope.ExtendedAttributes != null && searchScope.ExtendedAttributes.Count > 0 && !DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this))
{
throw new ServiceVersionException(
string.Format(
Strings.ClassIncompatibleWithRequestVersion,
typeof(ExtendedAttribute).Name,
DiscoverySchemaChanges.SearchMailboxesExtendedData.MinimumServerVersion));
}
if (searchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN && (!DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this) || !DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this)))
{
throw new ServiceVersionException(
string.Format(
Strings.EnumValueIncompatibleWithRequestVersion,
searchScope.SearchScopeType.ToString(),
typeof(MailboxSearchScopeType).Name,
DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.MinimumServerVersion));
}
}
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
PropertyDefinitionBase prop = null;
try
{
prop = ServiceObjectSchema.FindPropertyDefinition(this.SortByProperty);
}
catch (KeyNotFoundException)
{
}
if (prop == null)
{
throw new ServiceValidationException(string.Format(Strings.InvalidSortByPropertyForMailboxSearch, this.SortByProperty));
}
}
}
/// <summary>
/// Parses the response.
/// See O15:324151 on why we need to override ParseResponse here instead of calling the one in MultiResponseServiceRequest.cs
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Service response collection.</returns>
internal override object ParseResponse(EwsServiceXmlReader reader)
{
ServiceResponseCollection<SearchMailboxesResponse> serviceResponses = new ServiceResponseCollection<SearchMailboxesResponse>();
reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
while (true)
{
// Read ahead to see if we've reached the end of the response messages early.
reader.Read();
if (reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages))
{
break;
}
SearchMailboxesResponse response = new SearchMailboxesResponse();
response.LoadFromXml(reader, this.GetResponseMessageXmlElementName());
serviceResponses.Add(response);
}
reader.ReadEndElementIfNecessary(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
return serviceResponses;
}
/// <summary>
/// Parses the response.
/// See O15:324151 on why we need to override ParseResponse here instead of calling the one in MultiResponseServiceRequest.cs
/// </summary>
/// <param name="jsonBody">The json body.</param>
/// <returns>Response object.</returns>
internal override object ParseResponse(JsonObject jsonBody)
{
ServiceResponseCollection<SearchMailboxesResponse> serviceResponses = new ServiceResponseCollection<SearchMailboxesResponse>();
object[] jsonResponseMessages = jsonBody.ReadAsJsonObject(XmlElementNames.ResponseMessages).ReadAsArray(XmlElementNames.Items);
foreach (object jsonResponseObject in jsonResponseMessages)
{
SearchMailboxesResponse response = new SearchMailboxesResponse();
response.LoadFromJson(jsonResponseObject as JsonObject, this.Service);
serviceResponses.Add(response);
}
return serviceResponses;
}
/// <summary>
/// Writes XML elements.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SearchQueries);
foreach (MailboxQuery mailboxQuery in this.SearchQueries)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxQuery);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Query, mailboxQuery.Query);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScopes);
foreach (MailboxSearchScope mailboxSearchScope in mailboxQuery.MailboxSearchScopes)
{
// The checks here silently downgrade the schema based on compatability checks, to recieve errors use the validate method
if (mailboxSearchScope.SearchScopeType == MailboxSearchScopeType.LegacyExchangeDN || DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScope);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Mailbox, mailboxSearchScope.Mailbox);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SearchScope, mailboxSearchScope.SearchScope);
if (DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttributes);
if (mailboxSearchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, XmlElementNames.SearchScopeType);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, mailboxSearchScope.SearchScopeType);
writer.WriteEndElement();
}
if (mailboxSearchScope.ExtendedAttributes != null && mailboxSearchScope.ExtendedAttributes.Count > 0)
{
foreach (ExtendedAttribute attribute in mailboxSearchScope.ExtendedAttributes)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, attribute.Name);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, attribute.Value);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // ExtendedData
}
writer.WriteEndElement(); // MailboxSearchScope
}
}
writer.WriteEndElement(); // MailboxSearchScopes
writer.WriteEndElement(); // MailboxQuery
}
writer.WriteEndElement(); // SearchQueries
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.ResultType, this.ResultType);
if (this.PreviewItemResponseShape != null)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.PreviewItemResponseShape);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.BaseShape, this.PreviewItemResponseShape.BaseShape);
if (this.PreviewItemResponseShape.AdditionalProperties != null && this.PreviewItemResponseShape.AdditionalProperties.Length > 0)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties);
foreach (ExtendedPropertyDefinition additionalProperty in this.PreviewItemResponseShape.AdditionalProperties)
{
additionalProperty.WriteToXml(writer);
}
writer.WriteEndElement(); // AdditionalProperties
}
writer.WriteEndElement(); // PreviewItemResponseShape
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SortBy);
writer.WriteAttributeValue(XmlElementNames.Order, this.SortOrder.ToString());
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.FieldURI);
writer.WriteAttributeValue(XmlElementNames.FieldURI, this.sortByProperty);
writer.WriteEndElement(); // FieldURI
writer.WriteEndElement(); // SortBy
}
// Language
if (!string.IsNullOrEmpty(this.Language))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Language, this.Language);
}
// Dedupe
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Deduplication, this.performDeduplication);
if (this.PageSize > 0)
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageSize, this.PageSize.ToString());
}
if (!string.IsNullOrEmpty(this.PageItemReference))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageItemReference, this.PageItemReference);
}
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageDirection, this.PageDirection.ToString());
}
/// <summary>
/// Gets the request version.
/// </summary>
/// <returns>Earliest Exchange version in which this request is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2013;
}
/// <summary>
/// Creates a JSON representation of this object.
/// </summary>
/// <param name="service">The service.</param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
object IJsonSerializable.ToJson(ExchangeService service)
{
JsonObject jsonObject = new JsonObject();
return jsonObject;
}
/// <summary>
/// Collection of query + mailboxes
/// </summary>
public List<MailboxQuery> SearchQueries
{
get { return this.searchQueries; }
set { this.searchQueries = value; }
}
/// <summary>
/// Search result type
/// </summary>
public SearchResultType ResultType
{
get { return this.searchResultType; }
set { this.searchResultType = value; }
}
/// <summary>
/// Preview item response shape
/// </summary>
public PreviewItemResponseShape PreviewItemResponseShape
{
get { return this.previewItemResponseShape; }
set { this.previewItemResponseShape = value; }
}
/// <summary>
/// Sort order
/// </summary>
public SortDirection SortOrder
{
get { return this.sortOrder; }
set { this.sortOrder = value; }
}
/// <summary>
/// Sort by property name
/// </summary>
public string SortByProperty
{
get { return this.sortByProperty; }
set { this.sortByProperty = value; }
}
/// <summary>
/// Query language
/// </summary>
public string Language
{
get;
set;
}
/// <summary>
/// Perform deduplication or not
/// </summary>
public bool PerformDeduplication
{
get { return this.performDeduplication; }
set { this.performDeduplication = value; }
}
/// <summary>
/// Page size
/// </summary>
public int PageSize
{
get { return this.pageSize; }
set { this.pageSize = value; }
}
/// <summary>
/// Page item reference
/// </summary>
public string PageItemReference
{
get { return this.pageItemReference; }
set { this.pageItemReference = value; }
}
/// <summary>
/// Page direction
/// </summary>
public SearchPageDirection PageDirection
{
get { return this.pageDirection; }
set { this.pageDirection = value; }
}
/// <summary>
/// Gets or sets the server version.
/// </summary>
/// <value>
/// The server version.
/// </value>
long IDiscoveryVersionable.ServerVersion
{
get;
set;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.DataAccessLib.Cart;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Products.BackOffice;
using Vevo.Shared.SystemServices;
using Vevo.Shared.Utilities;
using Vevo.WebUI;
using Vevo.Domain.Stores;
public partial class AdminAdvanced_Components_Products_ImageList : AdminAdvancedBaseUserControl
{
#region Private
private const int ImageIDIndex = 0;
private const int AltTagIndex = 1;
private const int TitleTagIndex = 2;
private const int ZoomCheckBoxIndex = 5;
private const int EnlargeCheckBoxIndex = 6;
private DataTable _imageSource = new DataTable( "ProductImage" );
private DataTable _tempImageSource = new DataTable( "TempProductImage" );
private DataTable CreateTable( string name )
{
DataTable table = new DataTable( name );
table.Columns.Add( "ProductImageID", typeof( string ) );
table.Columns.Add( "ProductID", typeof( Int32 ) );
table.Columns.Add( "RegularImage", typeof( string ) );
table.Columns.Add( "LargeImage", typeof( string ) );
table.Columns.Add( "ThumbnailImage", typeof( string ) );
table.Columns.Add( "Imagesize", typeof( Int32 ) );
table.Columns.Add( "SortOrder", typeof( Int32 ) );
table.Columns.Add( "IsZoom", typeof( Boolean ) );
table.Columns.Add( "IsEnlarge", typeof( Boolean ) );
table.Columns.Add( "ImageWidth", typeof( Int32 ) );
table.Columns.Add( "ImageHeight", typeof( Int32 ) );
table.Columns.Add( "AltTag", typeof( string ) );
table.Columns.Add( "TitleTag", typeof( string ) );
return table;
}
private GridViewHelper GridHelper
{
get
{
if (ViewState["GridHelper"] == null)
ViewState["GridHelper"] = new GridViewHelper( uxGridProductImage, "SortOrder" );
return (GridViewHelper) ViewState["GridHelper"];
}
}
private void RefreshGrid()
{
CrateDataSource();
SortDataBySortOrder();
PopulateThumbnail();
uxGridProductImage.DataSource = _imageSource;
uxGridProductImage.DataBind();
}
private void CrateDataSource()
{
_imageSource = CreateTable( "ProductImage" );
_tempImageSource = CreateTable( "TempProductImage" );
if (ProductID == "0")
{
uxSecondaryImageHidden.Value = ProductImageData.SecondaryImagePath;
foreach (ImageItem item in ProductImageData.GetAllItems())
{
CreateRow(
_tempImageSource, item.ProductImageID, 0,
item.RegularImage, item.LargeImage, item.ThumbnailImage,
item.ImageSize, item.SortOrder, item.IsZoom, item.IsEnlarge,
item.ImageWidth, item.ImageHeight, item.Locales[CurrentCulture].AltTag, item.Locales[CurrentCulture].TitleTag );
}
}
else
{
Product product = DataAccessContext.ProductRepository.GetOne( CurrentCulture, ProductID, new StoreRetriever().GetCurrentStoreID() );
uxSecondaryImageHidden.Value = product.ImageSecondary;
foreach (ProductImage productImage in product.ProductImages)
{
ProductImageLocale locale = productImage.Locales[CurrentCulture];
using (ProductImageFile imageFile =
ProductImageFile.Load( new FileManager(), Path.GetFileName( productImage.LargeImage ) ))
{
CreateRow( _tempImageSource, productImage.ProductImageID,
ConvertUtilities.ToInt32( product.ProductID ),
productImage.RegularImage,
productImage.LargeImage,
productImage.ThumbnailImage,
ProductImageFile.GetImageSize( new FileManager(), productImage.LargeImage ),
productImage.SortOrder,
productImage.IsZoom,
productImage.IsEnlarge,
imageFile.LargeImageWidth,
imageFile.LargeImageHeight,
locale.AltTag,
locale.TitleTag );
}
}
}
}
private void CreateRow(
DataTable table, string imageID, int productID, string regularImage, string largeImage,
string thumbnailImage, int imageSize, int SortOrder, bool isZoom, bool isEnlarge,
int imageWidth, int imageHeight, string altTag, string titleTag )
{
DataRow row;
row = table.NewRow();
row["ProductImageID"] = imageID;
row["ProductID"] = productID;
row["RegularImage"] = regularImage;
row["LargeImage"] = largeImage;
row["ThumbnailImage"] = thumbnailImage;
row["imageSize"] = imageSize;
row["SortOrder"] = SortOrder;
row["IsZoom"] = isZoom;
row["IsEnlarge"] = isEnlarge;
row["ImageWidth"] = imageWidth;
row["ImageHeight"] = imageHeight;
row["AltTag"] = altTag;
row["TitleTag"] = titleTag;
table.Rows.Add( row );
}
private void SortDataBySortOrder()
{
DataRow[] dataRows = _tempImageSource.Select( "", "SortOrder" );
for (int i = 0; i < dataRows.Length; i++)
{
CreateRow(
_imageSource,
dataRows[i]["ProductImageID"].ToString(), ConvertUtilities.ToInt32( dataRows[i]["ProductID"] ),
dataRows[i]["RegularImage"].ToString(), dataRows[i]["LargeImage"].ToString(),
dataRows[i]["ThumbnailImage"].ToString(), ConvertUtilities.ToInt32( dataRows[i]["ImageSize"] ),
ConvertUtilities.ToInt32( dataRows[i]["SortOrder"] ),
ConvertUtilities.ToBoolean( dataRows[i]["IsZoom"] ),
ConvertUtilities.ToBoolean( dataRows[i]["IsEnlarge"] ),
ConvertUtilities.ToInt32( dataRows[i]["ImageWidth"] ),
ConvertUtilities.ToInt32( dataRows[i]["ImageHeight"] ),
dataRows[i]["AltTag"].ToString(),
dataRows[i]["TitleTag"].ToString()
);
}
}
private void SaveSecondaryNoProduct( ProductImageFile imageFile )
{
imageFile.SaveSecondary();
if (!String.IsNullOrEmpty( ProductImageData.SecondaryImagePath )
&& String.Compare( imageFile.SecondaryFilePath, ProductImageData.SecondaryImagePath, true ) != 0)
{
DeleteFile( ProductImageData.SecondaryImagePath );
}
ProductImageData.SecondaryImagePath = imageFile.SecondaryFilePath;
uxSecondaryImageHidden.Value = ProductImageData.SecondaryImagePath;
}
private void SaveSecondary( Product product, ProductImageFile imageFile )
{
imageFile.SaveSecondary();
string secondaryImage = product.ImageSecondary;
if (!String.IsNullOrEmpty( secondaryImage )
&& String.Compare( imageFile.SecondaryFilePath, secondaryImage, true ) != 0)
{
DeleteFile( secondaryImage );
}
product.ImageSecondary = imageFile.SecondaryFilePath;
uxSecondaryImageHidden.Value = product.ImageSecondary;
}
private bool IsZoomable( ProductImageFile imageFile )
{
return IsZoomableSize( imageFile.LargeImageWidth, imageFile.LargeImageHeight );
}
private void DisplayUploadMessage( ProductImageFile imageFile )
{
if (IsZoomable( imageFile ))
uxMessage.DisplayMessage( Resources.ProductImageMessages.UploadSuccess );
else
uxMessage.DisplayMessage( Resources.ProductImageMessages.UploadSuccessNoZoom );
}
private int TotalImageSize()
{
int total = 0;
for (int i = 0; i < _imageSource.Rows.Count; i++)
{
total += ConvertUtilities.ToInt32( _imageSource.Rows[i]["ImageSize"] );
}
return total;
}
private bool VerifyInput( out string message )
{
int zeroCount = 0;
foreach (DataListItem item in uxThumbnailDataList.Items)
{
int sortOrder = ConvertUtilities.ToInt32( ((TextBox) item.FindControl( "uxSortOrderText" )).Text );
if (sortOrder == 0)
zeroCount++;
if (sortOrder < 0 ||
zeroCount > 1)
{
message = Resources.ProductImageMessages.UpdateErrorSortOrder;
return false;
}
}
message = String.Empty;
return true;
}
private bool GetZoomValue( GridViewRow row )
{
CheckBox checkBox = (CheckBox) row.Cells[ZoomCheckBoxIndex].FindControl( "uxZoomCheck" );
if (checkBox.Enabled)
return checkBox.Checked;
else
return false;
}
private void DeleteFile( string filePath )
{
string localPath = Server.MapPath( "~/" + filePath );
System.IO.FileInfo deleteFile = new System.IO.FileInfo( localPath );
if (deleteFile.Exists)
deleteFile.Delete();
}
private void DeleteImage( string regularImage, string largeImage, string thumbnailImage )
{
DeleteFile( regularImage );
DeleteFile( largeImage );
DeleteFile( thumbnailImage );
}
private void SetNewPrimaryImageAfterDelete( string imageID )
{
ProductImageData.SetPrimary( imageID );
ImageItem item1 = ProductImageData.FindItem( imageID );
string originalFilePath = item1.LargeImage;
using (ProductImageFile imageFile = ProductImageFile.Load( new FileManager(), Path.GetFileName( originalFilePath ) ))
{
SaveSecondaryNoProduct( imageFile );
}
}
private void RemoveNewProductImage( string imageID )
{
ImageItem item = ProductImageData.FindItem( imageID );
if (item.SortOrder == 0)
{
DeleteFile( ProductImageData.SecondaryImagePath );
ProductImageData.SecondaryImagePath = "";
if (uxGridProductImage.Rows.Count > 1)
{
string[] gridImageIDArray = new string[uxGridProductImage.Rows.Count - 1];
for (int i = 1; i < uxGridProductImage.Rows.Count; i++)
{
gridImageIDArray[i - 1] = ((HiddenField) uxGridProductImage.Rows[i].FindControl( "uxImageIDHidden" )).Value;
}
Array.Sort( gridImageIDArray );
SetNewPrimaryImageAfterDelete( gridImageIDArray[0] );
}
}
DeleteImage( item.RegularImage, item.LargeImage, item.ThumbnailImage );
ProductImageData.RemoveItem( imageID );
}
private void RemoveExistingProductImage( Product product, string imageID )
{
bool deletePrimary = false;
ProductImage productImageToDelete = new ProductImage();
foreach (ProductImage productimage in product.ProductImages)
{
if (productimage.ProductImageID == imageID)
{
DeleteImage( productimage.RegularImage, productimage.LargeImage, productimage.ThumbnailImage );
if (productimage.SortOrder == 0)
{
DeleteFile( product.ImageSecondary );
deletePrimary = true;
}
productImageToDelete = productimage;
}
}
product.ProductImages.Remove( productImageToDelete );
if (deletePrimary)
{
foreach (ProductImage productimage in product.ProductImages)
{
productimage.SortOrder = productimage.SortOrder - 1;
if (productimage.SortOrder == 0)
{
using (ProductImageFile imageFile = ProductImageFile.Load( new FileManager(), Path.GetFileName( productimage.LargeImage ) ))
{
SaveSecondary( product, imageFile );
}
}
}
}
}
private void SetProductImageOrder( Product product, string productImageID, int sortOrder )
{
foreach (ProductImage productImage in product.ProductImages)
{
if (productImage.ProductImageID == productImageID)
productImage.SortOrder = sortOrder;
}
}
private void UpdateProductImageFromGrid( Product product, string productImageID, bool isZoom, bool isEnlarge, Culture culture, string altTag, string titleTag )
{
foreach (ProductImage productImage in product.ProductImages)
{
if (productImage.ProductImageID == productImageID)
{
productImage.IsZoom = isZoom;
productImage.IsEnlarge = isEnlarge;
productImage.Locales[culture].AltTag = altTag;
productImage.Locales[culture].TitleTag = titleTag;
}
}
}
private void UpdateImage()
{
string message;
if (!VerifyInput( out message ))
{
uxMessage.DisplayError( message );
return;
}
Product product = DataAccessContext.ProductRepository.GetOne( CurrentCulture, ProductID, new StoreRetriever().GetCurrentStoreID() );
foreach (GridViewRow row in uxGridProductImage.Rows)
{
ProductImage productImage = new ProductImage();
string id = ((HiddenField) row.Cells[ImageIDIndex].FindControl( "uxImageIDHidden" )).Value.Trim();
bool isZoom = GetZoomValue( row );
bool isEnlarge = ((CheckBox) row.Cells[EnlargeCheckBoxIndex].FindControl( "uxEnlargeCheck" )).Checked;
string altTag = ((TextBox) row.Cells[AltTagIndex].FindControl( "uxAltTag" )).Text;
string titleTag = ((TextBox) row.Cells[TitleTagIndex].FindControl( "uxTitleTag" )).Text;
if (ProductID == "0")
{
ProductImageData.UpdateItem( id, isZoom, isEnlarge, CurrentCulture, altTag, titleTag );
}
else
{
UpdateProductImageFromGrid( product, id, isZoom, isEnlarge, CurrentCulture, altTag, titleTag );
}
}
foreach (DataListItem item in uxThumbnailDataList.Items)
{
string id = ((HiddenField) item.FindControl( "uxImageIDHidden" )).Value.Trim();
int SortOrder = ConvertUtilities.ToInt32( ((TextBox) item.FindControl( "uxSortOrderText" )).Text );
if (ProductID == "0")
ProductImageData.UpdateSortOrder( id, SortOrder );
else
SetProductImageOrder( product, id, SortOrder );
}
}
#endregion
#region Protected
protected void Page_Load( object sender, EventArgs e )
{
uxUpload.ProductID = ProductID;
uxUpload.GridViewControlID = uxGridProductImage.ClientID;
uxUpload.MessageControlID = uxMessage.MessageControlID;
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!String.IsNullOrEmpty( uxUpload.ErrorFileList ))
uxMessage.DisplayError( uxUpload.ErrorFileList );
uxUpload.Visible = true;
PopulateControls();
}
protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e )
{
GridHelper.SelectSorting( e.SortExpression );
}
protected string GetImageName( string largeImage )
{
return largeImage.Substring( largeImage.LastIndexOf( "/" ) + 1 );
}
protected bool IsPrimaryImage( object SortOrder )
{
if (ConvertUtilities.ToInt32( SortOrder ) == 0)
return true;
else
return false;
}
protected bool IsSorting()
{
if (ProductID == "0")
return false;
else
return true;
}
protected bool IsZoomableSize( object largeImageWidth, object largeImageHeight )
{
return (ConvertUtilities.ToInt32( largeImageWidth ) > SystemConst.ProductMagnifierSize) &&
(ConvertUtilities.ToInt32( largeImageHeight ) > SystemConst.ProductMagnifierSize);
}
protected string ImageUrl( string imageName )
{
imageName = "~/" + imageName;
return imageName;
}
protected void PopulateThumbnail()
{
uxThumbnailDataList.DataSource = _imageSource;
uxThumbnailDataList.DataBind();
}
protected void uxRemoveImageButton_PreRender( object sender, EventArgs e )
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
LinkButton button = (LinkButton) sender;
button.Attributes.Add(
"onclick",
"if (confirm('" + Resources.ProductImageMessages.DeleteConfirmation + "')) {} else {return false}" );
}
}
protected void uxRemoveImageButton_Click( object sender, EventArgs e )
{
LinkButton myButton = (LinkButton) sender;
string imageID = myButton.CommandArgument;
if (ProductID == "0")
{
RemoveNewProductImage( imageID );
}
else
{
string storeID = new StoreRetriever().GetCurrentStoreID();
Product product = DataAccessContext.ProductRepository.GetOne( Culture.Null, ProductID, storeID );
RemoveExistingProductImage( product, imageID );
DataAccessContext.ProductRepository.Save( product );
}
}
protected void uxSetAsPrimayImageButton_Click( object sender, EventArgs e )
{
string storeID = new StoreRetriever().GetCurrentStoreID();
LinkButton myButton = (LinkButton) sender;
string imageID = myButton.CommandArgument;
Product product = DataAccessContext.ProductRepository.GetOne( Culture.Null, ProductID, storeID );
string originalFilePath;
if (ProductID == "0")
{
ProductImageData.SetPrimary( imageID );
ImageItem item = ProductImageData.FindItem( imageID );
originalFilePath = item.LargeImage;
}
else
{
ProductImage oldPrimaryImage = new ProductImage();
ProductImage newPrimaryImage = new ProductImage();
foreach (ProductImage productImage in product.ProductImages)
{
if (productImage.ProductImageID == imageID)
newPrimaryImage = productImage;
if (productImage.SortOrder == 0)
oldPrimaryImage = productImage;
}
SetProductImageOrder( product, oldPrimaryImage.ProductImageID, newPrimaryImage.SortOrder );
SetProductImageOrder( product, newPrimaryImage.ProductImageID, 0 );
originalFilePath = newPrimaryImage.LargeImage;
}
using (ProductImageFile imageFile = ProductImageFile.Load( new FileManager(), Path.GetFileName( originalFilePath ) ))
{
if (ProductID == "0")
SaveSecondaryNoProduct( imageFile );
else
SaveSecondary( product, imageFile );
}
if (!product.IsNull)
DataAccessContext.ProductRepository.Save( product );
uxMessage.DisplayMessage( Resources.ProductImageMessages.SetPrimarySuccess );
uxStatusHidden.Value = "SetPrimary";
}
#endregion
#region Public Methods
public void PopulateControls()
{
RefreshGrid();
if (uxGridProductImage.Rows.Count > 0)
{
uxPrimarImage.Visible = true;
lcPrimaryImageMessageLabel.Visible = true;
}
else
{
uxPrimarImage.Visible = false;
lcPrimaryImageMessageLabel.Visible = false;
}
}
public Culture CurrentCulture
{
get
{
if (ViewState["Culture"] == null)
return null;
else
return (Culture) ViewState["Culture"];
}
set
{
ViewState["Culture"] = value;
}
}
public void SetFooter( Object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TableCellCollection cells = e.Row.Cells;
cells[2].Text = "Total";
cells[2].HorizontalAlign = HorizontalAlign.Center;
cells[2].Font.Bold = true;
cells[3].Text = String.Format( "{0:0,0}", (TotalImageSize()) ).ToString() + " KB.";
cells[3].HorizontalAlign = HorizontalAlign.Right;
cells[3].Font.Bold = true;
}
}
public string ProductID
{
get
{
if (string.IsNullOrEmpty( MainContext.QueryString["ProductID"] ))
return "0";
else
return MainContext.QueryString["ProductID"];
}
}
public void Update()
{
UpdateImage();
}
public string SecondaryImage()
{
return uxSecondaryImageHidden.Value;
}
public void HideUploadImageButton()
{
uxProductImageUploadPanel.Style["display"] = "none";
}
public Product Update( Product product )
{
string message;
if (!VerifyInput( out message ))
{
uxMessage.DisplayError( message );
return null;
}
foreach (GridViewRow row in uxGridProductImage.Rows)
{
ProductImage productImage = new ProductImage();
string id = ((HiddenField) row.Cells[ImageIDIndex].FindControl( "uxImageIDHidden" )).Value.Trim();
bool isZoom = GetZoomValue( row );
bool isEnlarge = ((CheckBox) row.Cells[EnlargeCheckBoxIndex].FindControl( "uxEnlargeCheck" )).Checked;
string altTag = ((TextBox) row.Cells[AltTagIndex].FindControl( "uxAltTag" )).Text;
string titleTag = ((TextBox) row.Cells[TitleTagIndex].FindControl( "uxTitleTag" )).Text;
if (ProductID == "0")
{
ProductImageData.UpdateItem( id, isZoom, isEnlarge, CurrentCulture, altTag, titleTag );
}
else
{
UpdateProductImageFromGrid( product, id, isZoom, isEnlarge, CurrentCulture, altTag, titleTag );
}
}
foreach (DataListItem item in uxThumbnailDataList.Items)
{
string id = ((HiddenField) item.FindControl( "uxImageIDHidden" )).Value.Trim();
int SortOrder = ConvertUtilities.ToInt32( ((TextBox) item.FindControl( "uxSortOrderText" )).Text );
if (ProductID == "0")
ProductImageData.UpdateSortOrder( id, SortOrder );
else
SetProductImageOrder( product, id, SortOrder );
}
return product;
}
#endregion
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class SessionOpenEventEncoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 21;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private SessionOpenEventEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public SessionOpenEventEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public SessionOpenEventEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public SessionOpenEventEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public SessionOpenEventEncoder LeadershipTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public SessionOpenEventEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int ClusterSessionIdEncodingOffset()
{
return 16;
}
public static int ClusterSessionIdEncodingLength()
{
return 8;
}
public static long ClusterSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ClusterSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ClusterSessionIdMaxValue()
{
return 9223372036854775807L;
}
public SessionOpenEventEncoder ClusterSessionId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int TimestampEncodingOffset()
{
return 24;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public SessionOpenEventEncoder Timestamp(long value)
{
_buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public static int ResponseStreamIdEncodingOffset()
{
return 32;
}
public static int ResponseStreamIdEncodingLength()
{
return 4;
}
public static int ResponseStreamIdNullValue()
{
return -2147483648;
}
public static int ResponseStreamIdMinValue()
{
return -2147483647;
}
public static int ResponseStreamIdMaxValue()
{
return 2147483647;
}
public SessionOpenEventEncoder ResponseStreamId(int value)
{
_buffer.PutInt(_offset + 32, value, ByteOrder.LittleEndian);
return this;
}
public static int ResponseChannelId()
{
return 7;
}
public static string ResponseChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseChannelHeaderLength()
{
return 4;
}
public SessionOpenEventEncoder PutResponseChannel(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public SessionOpenEventEncoder PutResponseChannel(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public SessionOpenEventEncoder ResponseChannel(string value)
{
int length = value.Length;
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutStringWithoutLengthAscii(limit + headerLength, value);
return this;
}
public static int EncodedPrincipalId()
{
return 8;
}
public static string EncodedPrincipalMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedPrincipalHeaderLength()
{
return 4;
}
public SessionOpenEventEncoder PutEncodedPrincipal(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public SessionOpenEventEncoder PutEncodedPrincipal(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
SessionOpenEventDecoder writer = new SessionOpenEventDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using UnityEngine;
namespace UniRx
{
public static partial class Scheduler
{
static IScheduler mainThread;
/// <summary>
/// Unity native MainThread Queue Scheduler. Run on mainthread and delayed on coroutine update loop, elapsed time is calculated based on Time.time.
/// </summary>
public static IScheduler MainThread
{
get
{
return mainThread ?? (mainThread = new MainThreadScheduler());
}
}
static IScheduler mainThreadIgnoreTimeScale;
/// <summary>
/// Another MainThread scheduler, delay elapsed time is calculated based on Time.realtimeSinceStartup.
/// </summary>
public static IScheduler MainThreadIgnoreTimeScale
{
get
{
return mainThreadIgnoreTimeScale ?? (mainThreadIgnoreTimeScale = new IgnoreTimeScaleMainThreadScheduler());
}
}
class MainThreadScheduler : IScheduler
{
public MainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
// delay action is run in StartCoroutine
// Okay to action run synchronous and guaranteed run on MainThread
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = DateTimeOffset.UtcNow - startTime;
if (elapsed >= dueTime)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
};
yield break;
}
#endif
if (dueTime == TimeSpan.Zero)
{
yield return null; // not immediately, run next frame
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else if (dueTime.TotalMilliseconds % 1000 == 0)
{
yield return new WaitForSeconds((float)dueTime.TotalSeconds);
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var startTime = Time.time;
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = Time.time - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(() =>
{
if (!d.IsDisposed)
{
action();
}
});
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, () =>
{
if (!d.IsDisposed)
{
action();
}
}, d));
return d;
}
}
class IgnoreTimeScaleMainThreadScheduler : IScheduler
{
public IgnoreTimeScaleMainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = DateTimeOffset.UtcNow - startTime;
if (elapsed >= dueTime)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
};
yield break;
}
#endif
if (dueTime == TimeSpan.Zero)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var startTime = Time.realtimeSinceStartup; // this is difference
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = Time.realtimeSinceStartup - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(() =>
{
if (!d.IsDisposed)
{
action();
}
});
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, () =>
{
if (!d.IsDisposed)
{
action();
}
}, d));
return d;
}
}
}
}
| |
//
// CGContextPDF.cs: Implements the managed CGContextPDF
//
// Authors: Mono Team
//
// Copyright 2009-2010 Novell, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
namespace MonoMac.CoreGraphics {
public class CGPDFPageInfo {
static IntPtr kCGPDFContextMediaBox;
static IntPtr kCGPDFContextCropBox;
static IntPtr kCGPDFContextBleedBox;
static IntPtr kCGPDFContextTrimBox;
static IntPtr kCGPDFContextArtBox;
static CGPDFPageInfo ()
{
IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0);
try {
kCGPDFContextMediaBox = Dlfcn.GetIndirect (h, "kCGPDFContextMediaBox");
kCGPDFContextCropBox = Dlfcn.GetIndirect (h, "kCGPDFContextCropBox");
kCGPDFContextBleedBox = Dlfcn.GetIndirect (h, "kCGPDFContextBleedBox");
kCGPDFContextTrimBox = Dlfcn.GetIndirect (h, "kCGPDFContextTrimBox");
kCGPDFContextArtBox = Dlfcn.GetIndirect (h, "kCGPDFContextArtBox");
} finally {
Dlfcn.dlclose (h);
}
}
public RectangleF? MediaBox { get; set; }
public RectangleF? CropBox { get; set; }
public RectangleF? BleedBox { get; set; }
public RectangleF? TrimBox { get; set; }
public RectangleF? ArtBox { get; set; }
static void Add (NSMutableDictionary dict, IntPtr key, RectangleF? val)
{
if (!val.HasValue)
return;
NSData data;
unsafe {
RectangleF f = val.Value;
RectangleF *pf = &f;
data = NSData.FromBytes ((IntPtr) pf, 16);
}
dict.LowlevelSetObject (data, key);
}
internal virtual NSMutableDictionary ToDictionary ()
{
var ret = new NSMutableDictionary ();
Add (ret, kCGPDFContextMediaBox, MediaBox);
Add (ret, kCGPDFContextCropBox, CropBox);
Add (ret, kCGPDFContextBleedBox, BleedBox);
Add (ret, kCGPDFContextTrimBox, TrimBox);
Add (ret, kCGPDFContextArtBox, ArtBox);
return ret;
}
}
public class CGPDFInfo : CGPDFPageInfo {
static IntPtr kCGPDFContextTitle;
static IntPtr kCGPDFContextAuthor;
static IntPtr kCGPDFContextSubject;
static IntPtr kCGPDFContextKeywords;
static IntPtr kCGPDFContextCreator;
static IntPtr kCGPDFContextOwnerPassword;
static IntPtr kCGPDFContextUserPassword;
static IntPtr kCGPDFContextEncryptionKeyLength;
static IntPtr kCGPDFContextAllowsPrinting;
static IntPtr kCGPDFContextAllowsCopying;
#if false
static IntPtr kCGPDFContextOutputIntent;
static IntPtr kCGPDFXOutputIntentSubtype;
static IntPtr kCGPDFXOutputConditionIdentifier;
static IntPtr kCGPDFXOutputCondition;
static IntPtr kCGPDFXRegistryName;
static IntPtr kCGPDFXInfo;
static IntPtr kCGPDFXDestinationOutputProfile;
static IntPtr kCGPDFContextOutputIntents;
#endif
static CGPDFInfo ()
{
IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0);
try {
kCGPDFContextTitle = Dlfcn.GetIndirect (h, "kCGPDFContextTitle");
kCGPDFContextAuthor = Dlfcn.GetIndirect (h, "kCGPDFContextAuthor");
kCGPDFContextSubject = Dlfcn.GetIndirect (h, "kCGPDFContextSubject");
kCGPDFContextKeywords = Dlfcn.GetIndirect (h, "kCGPDFContextKeywords");
kCGPDFContextCreator = Dlfcn.GetIndirect (h, "kCGPDFContextCreator");
kCGPDFContextOwnerPassword = Dlfcn.GetIndirect (h, "kCGPDFContextOwnerPassword");
kCGPDFContextUserPassword = Dlfcn.GetIndirect (h, "kCGPDFContextUserPassword");
kCGPDFContextEncryptionKeyLength = Dlfcn.GetIndirect (h, "kCGPDFContextEncryptionKeyLength");
kCGPDFContextAllowsPrinting = Dlfcn.GetIndirect (h, "kCGPDFContextAllowsPrinting");
kCGPDFContextAllowsCopying = Dlfcn.GetIndirect (h, "kCGPDFContextAllowsCopying");
#if false
kCGPDFContextOutputIntent = Dlfcn.GetIndirect (h, "kCGPDFContextOutputIntent");
kCGPDFXOutputIntentSubtype = Dlfcn.GetIndirect (h, "kCGPDFXOutputIntentSubtype");
kCGPDFXOutputConditionIdentifier = Dlfcn.GetIndirect (h, "kCGPDFXOutputConditionIdentifier");
kCGPDFXOutputCondition = Dlfcn.GetIndirect (h, "kCGPDFXOutputCondition");
kCGPDFXRegistryName = Dlfcn.GetIndirect (h, "kCGPDFXRegistryName");
kCGPDFXInfo = Dlfcn.GetIndirect (h, "kCGPDFXInfo");
kCGPDFXDestinationOutputProfile = Dlfcn.GetIndirect (h, "kCGPDFXDestinationOutputProfile");
kCGPDFContextOutputIntents = Dlfcn.GetIndirect (h, "kCGPDFContextOutputIntents");
#endif
} finally {
Dlfcn.dlclose (h);
}
}
public string Title { get; set; }
public string Author { get; set; }
public string Subject { get; set; }
public string [] Keywords { get; set; }
public string Creator { get; set; }
public string OwnerPassword { get; set; }
public string UserPassword { get; set; }
public int? EncryptionKeyLength { get; set; }
public bool? AllowsPrinting { get; set; }
public bool? AllowsCopying { get; set; }
//public NSDictionary OutputIntent { get; set; }
internal override NSMutableDictionary ToDictionary ()
{
var ret = base.ToDictionary ();
if (Title != null)
ret.LowlevelSetObject ((NSString) Title, kCGPDFContextTitle);
if (Author != null)
ret.LowlevelSetObject ((NSString) Author, kCGPDFContextAuthor);
if (Subject != null)
ret.LowlevelSetObject ((NSString) Subject, kCGPDFContextSubject);
if (Keywords != null && Keywords.Length > 0){
if (Keywords.Length == 1)
ret.LowlevelSetObject ((NSString) Keywords [0], kCGPDFContextKeywords);
else
ret.LowlevelSetObject (NSArray.FromStrings (Keywords), kCGPDFContextKeywords);
}
if (Creator != null)
ret.LowlevelSetObject ((NSString) Creator, kCGPDFContextCreator);
if (OwnerPassword != null)
ret.LowlevelSetObject ((NSString) OwnerPassword, kCGPDFContextOwnerPassword);
if (UserPassword != null)
ret.LowlevelSetObject ((NSString) UserPassword, kCGPDFContextUserPassword);
if (EncryptionKeyLength.HasValue)
ret.LowlevelSetObject (NSNumber.FromInt32 (EncryptionKeyLength.Value), kCGPDFContextEncryptionKeyLength);
if (AllowsPrinting.HasValue && AllowsPrinting.Value == false)
ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsPrinting);
if (AllowsCopying.HasValue && AllowsCopying.Value == false)
ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsCopying);
return ret;
}
}
public class CGContextPDF : CGContext {
bool closed;
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, ref RectangleF rect, IntPtr dictionary);
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, IntPtr rect, IntPtr dictionary);
public CGContextPDF (NSUrl url, RectangleF mediaBox, CGPDFInfo info)
{
if (url == null)
throw new ArgumentNullException ("url");
handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, info == null ? IntPtr.Zero : info.ToDictionary ().Handle);
}
public CGContextPDF (NSUrl url, RectangleF mediaBox)
{
if (url == null)
throw new ArgumentNullException ("url");
handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, IntPtr.Zero);
}
public CGContextPDF (NSUrl url, CGPDFInfo info)
{
if (url == null)
throw new ArgumentNullException ("url");
handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, info == null ? IntPtr.Zero : info.ToDictionary ().Handle);
}
public CGContextPDF (NSUrl url)
{
if (url == null)
throw new ArgumentNullException ("url");
handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, IntPtr.Zero);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextClose(IntPtr handle);
public void Close ()
{
if (closed)
return;
CGPDFContextClose (handle);
closed = true;
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextBeginPage (IntPtr handle, IntPtr dict);
public void BeginPage (CGPDFPageInfo info)
{
CGPDFContextBeginPage (handle, info == null ? IntPtr.Zero : info.ToDictionary ().Handle);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextEndPage (IntPtr handle);
public void EndPage ()
{
CGPDFContextEndPage (handle);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextAddDocumentMetadata (IntPtr handle, IntPtr nsDataHandle);
public void AddDocumentMetadata (NSData data)
{
if (data == null)
return;
CGPDFContextAddDocumentMetadata (handle, data.Handle);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextSetURLForRect (IntPtr handle, IntPtr urlh, RectangleF rect);
public void SetUrl (NSUrl url, RectangleF region)
{
if (url == null)
throw new ArgumentNullException ("url");
CGPDFContextSetURLForRect (handle, url.Handle, region);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextAddDestinationAtPoint (IntPtr handle, IntPtr cfstring, PointF point);
public void AddDestination (string name, PointF point)
{
if (name == null)
throw new ArgumentNullException ("name");
CGPDFContextAddDestinationAtPoint (handle, new NSString (name).Handle, point);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGPDFContextSetDestinationForRect (IntPtr handle, IntPtr cfstr, RectangleF rect);
public void SetDestination (string name, RectangleF rect)
{
if (name == null)
throw new ArgumentNullException ("name");
CGPDFContextSetDestinationForRect (handle, new NSString (name).Handle, rect);
}
protected override void Dispose (bool disposing)
{
if (disposing)
Close ();
base.Dispose (disposing);
}
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC 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.Data;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
using MySql.Data.MySqlClient;
namespace Tiraggo.MySqlClientProvider
{
class Shared
{
static public MySqlCommand BuildDynamicInsertCommand(tgDataRequest request, List<string> modifiedColumns)
{
string sql = String.Empty;
string defaults = String.Empty;
string into = String.Empty;
string values = String.Empty;
string comma = String.Empty;
string defaultComma = String.Empty;
string where = String.Empty;
string whereComma = String.Empty;
PropertyCollection props = new PropertyCollection();
MySqlParameter p = null;
Dictionary<string, MySqlParameter> types = Cache.GetParameters(request);
MySqlCommand cmd = new MySqlCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = modifiedColumns == null ? false : modifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + p.ParameterName;
comma = ", ";
}
else if (col.IsAutoIncrement)
{
props["AutoInc"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
}
else if (col.IsTiraggoConcurrency)
{
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + "1";
comma = ", ";
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
p.Value = 1; // Seems to work, We'll take it ...
cmd.Parameters.Add(p);
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
defaultComma = ",";
}
if (col.IsInPrimaryKey)
{
where += whereComma + col.Name;
whereComma = ",";
}
}
#region Special Columns
if (cols.DateAdded != null && cols.DateAdded.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateAdded.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateModified.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.AddedBy != null && cols.AddedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["AddedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
#endregion
if (defaults.Length > 0)
{
comma = String.Empty;
props["Defaults"] = defaults;
props["Where"] = where;
}
sql += " INSERT INTO " + CreateFullName(request);
if (into.Length != 0)
{
sql += "(" + into + ") VALUES (" + values + ")";
}
else
{
sql += "DEFAULT VALUES";
}
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public MySqlCommand BuildDynamicUpdateCommand(tgDataRequest request, List<string> modifiedColumns)
{
string where = String.Empty;
string scomma = String.Empty;
string wcomma = String.Empty;
string defaults = String.Empty;
string defaultsWhere = String.Empty;
string defaultsComma = String.Empty;
string defaultsWhereComma = String.Empty;
string sql = "UPDATE " + CreateFullName(request) + " SET ";
PropertyCollection props = new PropertyCollection();
MySqlParameter p = null;
Dictionary<string, MySqlParameter> types = Cache.GetParameters(request);
MySqlCommand cmd = new MySqlCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = modifiedColumns == null ? false : modifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = CloneParameter(types[col.Name]);
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
scomma = ", ";
}
else if (col.IsAutoIncrement)
{
// Nothing to do but leave this here
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
p.Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
p.Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " + 1";
scomma = ", ";
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
// defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
// defaultsComma = ",";
}
if (col.IsInPrimaryKey)
{
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
defaultsWhere += defaultsWhereComma + col.Name;
defaultsWhereComma = ",";
}
}
#region Special Columns
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
#endregion
if (defaults.Length > 0)
{
props["Defaults"] = defaults;
props["Where"] = defaultsWhere;
}
sql += " WHERE " + where + ";";
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public MySqlCommand BuildDynamicDeleteCommand(tgDataRequest request, List<string> modifiedColumns)
{
Dictionary<string, MySqlParameter> types = Cache.GetParameters(request);
MySqlCommand cmd = new MySqlCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
string sql = "DELETE FROM " + CreateFullName(request) + " ";
string comma = String.Empty;
comma = String.Empty;
sql += " WHERE ";
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey || col.IsTiraggoConcurrency)
{
MySqlParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
sql += comma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
comma = " AND ";
}
}
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public MySqlCommand BuildStoredProcInsertCommand(tgDataRequest request)
{
MySqlCommand cmd = new MySqlCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spInsert + Delimiters.StoredProcNameClose;
PopulateStoredProcParameters(cmd, request);
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsComputed || col.IsAutoIncrement || col.IsTiraggoConcurrency)
{
MySqlParameter p = cmd.Parameters["?p" + (col.Name).Replace(" ", String.Empty)];
p.Direction = ParameterDirection.Output;
}
}
return cmd;
}
static public MySqlCommand BuildStoredProcUpdateCommand(tgDataRequest request)
{
MySqlCommand cmd = new MySqlCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spUpdate + Delimiters.StoredProcNameClose;
PopulateStoredProcParameters(cmd, request);
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsComputed || col.IsTiraggoConcurrency)
{
MySqlParameter p = cmd.Parameters["?p" + (col.Name).Replace(" ", String.Empty)];
p.SourceVersion = DataRowVersion.Original;
p.Direction = ParameterDirection.InputOutput;
}
}
return cmd;
}
static public MySqlCommand BuildStoredProcDeleteCommand(tgDataRequest request)
{
MySqlCommand cmd = new MySqlCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spDelete + Delimiters.StoredProcNameClose;
Dictionary<string, MySqlParameter> types = Cache.GetParameters(request);
MySqlParameter p;
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey || col.IsTiraggoConcurrency)
{
p = types[col.Name];
p = CloneParameter(p);
p.ParameterName = p.ParameterName.Replace("?", "?p");
p.SourceVersion = DataRowVersion.Current;
cmd.Parameters.Add(p);
}
}
return cmd;
}
static public void PopulateStoredProcParameters(MySqlCommand cmd, tgDataRequest request)
{
Dictionary<string, MySqlParameter> types = Cache.GetParameters(request);
MySqlParameter p;
foreach (tgColumnMetadata col in request.Columns)
{
p = types[col.Name];
p = CloneParameter(p);
p.ParameterName = p.ParameterName.Replace("?", "?p");
p.SourceVersion = DataRowVersion.Current;
if (p.MySqlDbType == MySqlDbType.Timestamp)
{
p.Direction = ParameterDirection.InputOutput;
}
cmd.Parameters.Add(p);
}
}
static private MySqlParameter CloneParameter(MySqlParameter p)
{
ICloneable param = p as ICloneable;
return param.Clone() as MySqlParameter;
}
static public bool HasUpdates(DataRowCollection rows, out bool insert, out bool update, out bool delete)
{
insert = false;
update = false;
delete = false;
for (int i = 0; i < rows.Count; i++)
{
switch (rows[i].RowState)
{
case DataRowState.Added:
insert = true;
break;
case DataRowState.Modified:
update = true;
break;
case DataRowState.Deleted:
delete = true;
break;
}
}
return (insert || update || delete) ? true : false;
}
static public bool HasUpdate(DataRow row, out bool insert, out bool update, out bool delete)
{
insert = false;
update = false;
delete = false;
switch (row.RowState)
{
case DataRowState.Added:
insert = true;
break;
case DataRowState.Modified:
update = true;
break;
case DataRowState.Deleted:
delete = true;
break;
}
return (insert || update || delete) ? true : false;
}
static public string CreateFullName(tgDataRequest request, tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata;
string name = String.Empty;
string catalog = iQuery.Catalog ?? request.Catalog ?? providerMetadata.Catalog;
string schema = iQuery.Schema ?? request.Schema ?? providerMetadata.Schema;
if (catalog != null)
{
name += Delimiters.TableOpen + catalog + Delimiters.TableClose + ".";
}
name += Delimiters.TableOpen;
if (query.tg.QuerySource != null)
name += query.tg.QuerySource;
else
name += providerMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgDataRequest request)
{
string name = String.Empty;
string catalog = request.Catalog ?? request.ProviderMetadata.Catalog;
if (catalog != null)
{
name += Delimiters.TableOpen + catalog + Delimiters.TableClose + ".";
}
name += Delimiters.TableOpen;
if(request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null)
name += request.DynamicQuery.tg.QuerySource;
else
name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public tgConcurrencyException CheckForConcurrencyException(MySqlException ex)
{
tgConcurrencyException ce = null;
if (ex != null)
{
if (ex.Number == 532)
{
ce = new tgConcurrencyException(ex.Message, ex);
ce.Source = ex.Source;
}
}
return ce;
}
static public void AddParameters(MySqlCommand cmd, tgDataRequest request)
{
if (request.QueryType == tgQueryType.Text && request.QueryText != null && request.QueryText.Contains("{0}"))
{
int i = 0;
string token = String.Empty;
string sIndex = String.Empty;
string param = String.Empty;
foreach (tgParameter esParam in request.Parameters)
{
sIndex = i.ToString();
token = '{' + sIndex + '}';
param = Delimiters.Param + "p" + sIndex;
request.QueryText = request.QueryText.Replace(token, param);
i++;
cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value);
}
}
else
{
MySqlParameter param;
string paramPrefix = request.ProviderMetadata.spLoadByPrimaryKey == cmd.CommandText ? Delimiters.Param + "p" : Delimiters.Param;
foreach (tgParameter esParam in request.Parameters)
{
param = cmd.Parameters.AddWithValue(paramPrefix + esParam.Name, esParam.Value);
// The default is ParameterDirection.Input
switch (esParam.Direction)
{
case tgParameterDirection.InputOutput:
param.Direction = ParameterDirection.InputOutput;
break;
case tgParameterDirection.Output:
param.Direction = ParameterDirection.Output;
param.DbType = esParam.DbType;
param.Size = esParam.Size;
param.Scale = esParam.Scale;
param.Precision = esParam.Precision;
break;
case tgParameterDirection.ReturnValue:
param.Direction = ParameterDirection.ReturnValue;
break;
}
}
}
}
static public void GatherReturnParameters(MySqlCommand cmd, tgDataRequest request, tgDataResponse response)
{
if (cmd.Parameters.Count > 0)
{
if (request.Parameters != null && request.Parameters.Count > 0)
{
string paramPrefix = request.ProviderMetadata.spLoadByPrimaryKey == cmd.CommandText ? Delimiters.Param + "p" : Delimiters.Param;
response.Parameters = new tgParameters();
foreach (tgParameter esParam in request.Parameters)
{
if (esParam.Direction != tgParameterDirection.Input)
{
response.Parameters.Add(esParam);
MySqlParameter p = cmd.Parameters[paramPrefix + esParam.Name];
esParam.Value = p.Value;
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using RestSharp.Authenticators.OAuth.Extensions;
#if !WINDOWS_PHONE && !SILVERLIGHT
using RestSharp.Contrib;
#endif
namespace RestSharp.Authenticators.OAuth
{
/// <summary>
/// A class to encapsulate OAuth authentication flow.
/// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
/// </summary>
internal class OAuthWorkflow
{
public virtual string Version { get; set; }
public virtual string ConsumerKey { get; set; }
public virtual string ConsumerSecret { get; set; }
public virtual string Token { get; set; }
public virtual string TokenSecret { get; set; }
public virtual string CallbackUrl { get; set; }
public virtual string Verifier { get; set; }
public virtual string SessionHandle { get; set; }
public virtual OAuthSignatureMethod SignatureMethod { get; set; }
public virtual OAuthSignatureTreatment SignatureTreatment { get; set; }
public virtual OAuthParameterHandling ParameterHandling { get; set; }
public virtual string ClientUsername { get; set; }
public virtual string ClientPassword { get; set; }
/// <seealso cref="http://oauth.net/core/1.0#request_urls"/>
public virtual string RequestTokenUrl { get; set; }
/// <seealso cref="http://oauth.net/core/1.0#request_urls"/>
public virtual string AccessTokenUrl { get; set; }
/// <seealso cref="http://oauth.net/core/1.0#request_urls"/>
public virtual string AuthorizationUrl { get; set; }
/// <summary>
/// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
/// <see cref="IAuthenticator" /> for the purpose of requesting an
/// unauthorized request token.
/// </summary>
/// <param name="method">The HTTP method for the intended request</param>
/// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
/// <returns></returns>
public OAuthWebQueryInfo BuildRequestTokenInfo(string method)
{
return BuildRequestTokenInfo(method, null);
}
/// <summary>
/// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
/// <see cref="IAuthenticator" /> for the purpose of requesting an
/// unauthorized request token.
/// </summary>
/// <param name="method">The HTTP method for the intended request</param>
/// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
/// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
/// <returns></returns>
public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters)
{
ValidateTokenRequestState();
if (parameters == null)
{
parameters = new WebParameterCollection();
}
var timestamp = OAuthTools.GetTimestamp();
var nonce = OAuthTools.GetNonce();
AddAuthParameters(parameters, timestamp, nonce);
var signatureBase = OAuthTools.ConcatenateRequestElements(method, RequestTokenUrl, parameters);
var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret);
var info = new OAuthWebQueryInfo
{
WebMethod = method,
ParameterHandling = ParameterHandling,
ConsumerKey = ConsumerKey,
SignatureMethod = SignatureMethod.ToRequestValue(),
SignatureTreatment = SignatureTreatment,
Signature = signature,
Timestamp = timestamp,
Nonce = nonce,
Version = Version ?? "1.0",
Callback = OAuthTools.UrlEncodeRelaxed(CallbackUrl ?? ""),
TokenSecret = TokenSecret,
ConsumerSecret = ConsumerSecret
};
return info;
}
/// <summary>
/// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
/// <see cref="IAuthenticator" /> for the purpose of exchanging a request token
/// for an access token authorized by the user at the Service Provider site.
/// </summary>
/// <param name="method">The HTTP method for the intended request</param>
/// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method)
{
return BuildAccessTokenInfo(method, null);
}
/// <summary>
/// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
/// <see cref="IAuthenticator" /> for the purpose of exchanging a request token
/// for an access token authorized by the user at the Service Provider site.
/// </summary>
/// <param name="method">The HTTP method for the intended request</param>
/// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
/// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParameterCollection parameters)
{
ValidateAccessRequestState();
if (parameters == null)
{
parameters = new WebParameterCollection();
}
var uri = new Uri(AccessTokenUrl);
var timestamp = OAuthTools.GetTimestamp();
var nonce = OAuthTools.GetNonce();
AddAuthParameters(parameters, timestamp, nonce);
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret);
var info = new OAuthWebQueryInfo
{
WebMethod = method,
ParameterHandling = ParameterHandling,
ConsumerKey = ConsumerKey,
Token = Token,
SignatureMethod = SignatureMethod.ToRequestValue(),
SignatureTreatment = SignatureTreatment,
Signature = signature,
Timestamp = timestamp,
Nonce = nonce,
Version = Version ?? "1.0",
Verifier = Verifier,
Callback = CallbackUrl,
TokenSecret = TokenSecret,
ConsumerSecret = ConsumerSecret,
};
return info;
}
/// <summary>
/// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
/// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials
/// for an access token authorized by the user at the Service Provider site.
/// </summary>
/// <param name="method">The HTTP method for the intended request</param>
/// <seealso cref="http://tools.ietf.org/html/draft-dehora-farrell-oauth-accesstoken-creds-00#section-4"/>
/// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
public virtual OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters)
{
ValidateClientAuthAccessRequestState();
if (parameters == null)
{
parameters = new WebParameterCollection();
}
var uri = new Uri(AccessTokenUrl);
var timestamp = OAuthTools.GetTimestamp();
var nonce = OAuthTools.GetNonce();
AddXAuthParameters(parameters, timestamp, nonce);
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret);
var info = new OAuthWebQueryInfo
{
WebMethod = method,
ParameterHandling = ParameterHandling,
ClientMode = "client_auth",
ClientUsername = ClientUsername,
ClientPassword = ClientPassword,
ConsumerKey = ConsumerKey,
SignatureMethod = SignatureMethod.ToRequestValue(),
SignatureTreatment = SignatureTreatment,
Signature = signature,
Timestamp = timestamp,
Nonce = nonce,
Version = Version ?? "1.0",
TokenSecret = TokenSecret,
ConsumerSecret = ConsumerSecret
};
return info;
}
public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url)
{
ValidateProtectedResourceState();
if (parameters == null)
{
parameters = new WebParameterCollection();
}
// Include url parameters in query pool
var uri = new Uri(url);
#if !SILVERLIGHT && !WINDOWS_PHONE
var urlParameters = HttpUtility.ParseQueryString(uri.Query);
#else
var urlParameters = uri.Query.ParseQueryString();
#endif
#if !SILVERLIGHT && !WINDOWS_PHONE
foreach (var parameter in urlParameters.AllKeys)
#else
foreach (var parameter in urlParameters.Keys)
#endif
{
switch (method.ToUpperInvariant())
{
case "POST":
parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter]));
break;
default:
parameters.Add(parameter, urlParameters[parameter]);
break;
}
}
var timestamp = OAuthTools.GetTimestamp();
var nonce = OAuthTools.GetNonce();
AddAuthParameters(parameters, timestamp, nonce);
var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters);
var signature = OAuthTools.GetSignature(
SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret
);
var info = new OAuthWebQueryInfo
{
WebMethod = method,
ParameterHandling = ParameterHandling,
ConsumerKey = ConsumerKey,
Token = Token,
SignatureMethod = SignatureMethod.ToRequestValue(),
SignatureTreatment = SignatureTreatment,
Signature = signature,
Timestamp = timestamp,
Nonce = nonce,
Version = Version ?? "1.0",
Callback = CallbackUrl,
ConsumerSecret = ConsumerSecret,
TokenSecret = TokenSecret
};
return info;
}
private void ValidateTokenRequestState()
{
if (RequestTokenUrl.IsNullOrBlank())
{
throw new ArgumentException("You must specify a request token URL");
}
if (ConsumerKey.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer key");
}
if (ConsumerSecret.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer secret");
}
}
private void ValidateAccessRequestState()
{
if (AccessTokenUrl.IsNullOrBlank())
{
throw new ArgumentException("You must specify an access token URL");
}
if (ConsumerKey.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer key");
}
if (ConsumerSecret.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer secret");
}
if (Token.IsNullOrBlank())
{
throw new ArgumentException("You must specify a token");
}
}
private void ValidateClientAuthAccessRequestState()
{
if (AccessTokenUrl.IsNullOrBlank())
{
throw new ArgumentException("You must specify an access token URL");
}
if (ConsumerKey.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer key");
}
if (ConsumerSecret.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer secret");
}
if (ClientUsername.IsNullOrBlank() || ClientPassword.IsNullOrBlank())
{
throw new ArgumentException("You must specify user credentials");
}
}
private void ValidateProtectedResourceState()
{
if (ConsumerKey.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer key");
}
if (ConsumerSecret.IsNullOrBlank())
{
throw new ArgumentException("You must specify a consumer secret");
}
}
private void AddAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce)
{
var authParameters = new WebParameterCollection
{
new WebPair("oauth_consumer_key", ConsumerKey),
new WebPair("oauth_nonce", nonce),
new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
new WebPair("oauth_timestamp", timestamp),
new WebPair("oauth_version", Version ?? "1.0")
};
if (!Token.IsNullOrBlank())
{
authParameters.Add(new WebPair("oauth_token", Token));
}
if (!CallbackUrl.IsNullOrBlank())
{
authParameters.Add(new WebPair("oauth_callback", CallbackUrl));
}
if (!Verifier.IsNullOrBlank())
{
authParameters.Add(new WebPair("oauth_verifier", Verifier));
}
if (!SessionHandle.IsNullOrBlank())
{
authParameters.Add(new WebPair("oauth_session_handle", SessionHandle));
}
foreach (var authParameter in authParameters)
{
parameters.Add(authParameter);
}
}
private void AddXAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce)
{
var authParameters = new WebParameterCollection
{
new WebPair("x_auth_username", ClientUsername),
new WebPair("x_auth_password", ClientPassword),
new WebPair("x_auth_mode", "client_auth"),
new WebPair("oauth_consumer_key", ConsumerKey),
new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
new WebPair("oauth_timestamp", timestamp),
new WebPair("oauth_nonce", nonce),
new WebPair("oauth_version", Version ?? "1.0")
};
foreach (var authParameter in authParameters)
{
parameters.Add(authParameter);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_dvec2 swizzle(dvec2 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static double[] Values(dvec2 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<double> GetEnumerator(dvec2 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(dvec2 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(dvec2 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(dvec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(dvec2 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(dvec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (2).
/// </summary>
public static int Count(dvec2 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(dvec2 v, dvec2 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(dvec2 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(dvec2 v) => v.GetHashCode();
/// <summary>
/// Returns true iff distance between lhs and rhs is less than or equal to epsilon
/// </summary>
public static bool ApproxEqual(dvec2 lhs, dvec2 rhs, double eps = 0.1d) => dvec2.ApproxEqual(lhs, rhs, eps);
/// <summary>
/// Returns a bvec2 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec2 Equal(dvec2 lhs, dvec2 rhs) => dvec2.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec2 NotEqual(dvec2 lhs, dvec2 rhs) => dvec2.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec2 GreaterThan(dvec2 lhs, dvec2 rhs) => dvec2.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec2 GreaterThanEqual(dvec2 lhs, dvec2 rhs) => dvec2.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec2 LesserThan(dvec2 lhs, dvec2 rhs) => dvec2.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec2 LesserThanEqual(dvec2 lhs, dvec2 rhs) => dvec2.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of IsInfinity (double.IsInfinity(v)).
/// </summary>
public static bvec2 IsInfinity(dvec2 v) => dvec2.IsInfinity(v);
/// <summary>
/// Returns a bvec2 from component-wise application of IsFinite (!double.IsNaN(v) && !double.IsInfinity(v)).
/// </summary>
public static bvec2 IsFinite(dvec2 v) => dvec2.IsFinite(v);
/// <summary>
/// Returns a bvec2 from component-wise application of IsNaN (double.IsNaN(v)).
/// </summary>
public static bvec2 IsNaN(dvec2 v) => dvec2.IsNaN(v);
/// <summary>
/// Returns a bvec2 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)).
/// </summary>
public static bvec2 IsNegativeInfinity(dvec2 v) => dvec2.IsNegativeInfinity(v);
/// <summary>
/// Returns a bvec2 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)).
/// </summary>
public static bvec2 IsPositiveInfinity(dvec2 v) => dvec2.IsPositiveInfinity(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static dvec2 Abs(dvec2 v) => dvec2.Abs(v);
/// <summary>
/// Returns a dvec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static dvec2 HermiteInterpolationOrder3(dvec2 v) => dvec2.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a dvec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static dvec2 HermiteInterpolationOrder5(dvec2 v) => dvec2.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Sqr (v * v).
/// </summary>
public static dvec2 Sqr(dvec2 v) => dvec2.Sqr(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Pow2 (v * v).
/// </summary>
public static dvec2 Pow2(dvec2 v) => dvec2.Pow2(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static dvec2 Pow3(dvec2 v) => dvec2.Pow3(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Step (v >= 0.0 ? 1.0 : 0.0).
/// </summary>
public static dvec2 Step(dvec2 v) => dvec2.Step(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Sqrt ((double)Math.Sqrt((double)v)).
/// </summary>
public static dvec2 Sqrt(dvec2 v) => dvec2.Sqrt(v);
/// <summary>
/// Returns a dvec2 from component-wise application of InverseSqrt ((double)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static dvec2 InverseSqrt(dvec2 v) => dvec2.InverseSqrt(v);
/// <summary>
/// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec2 Sign(dvec2 v) => dvec2.Sign(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static dvec2 Max(dvec2 lhs, dvec2 rhs) => dvec2.Max(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static dvec2 Min(dvec2 lhs, dvec2 rhs) => dvec2.Min(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Pow ((double)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static dvec2 Pow(dvec2 lhs, dvec2 rhs) => dvec2.Pow(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Log ((double)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static dvec2 Log(dvec2 lhs, dvec2 rhs) => dvec2.Log(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static dvec2 Clamp(dvec2 v, dvec2 min, dvec2 max) => dvec2.Clamp(v, min, max);
/// <summary>
/// Returns a dvec2 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static dvec2 Mix(dvec2 min, dvec2 max, dvec2 a) => dvec2.Mix(min, max, a);
/// <summary>
/// Returns a dvec2 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static dvec2 Lerp(dvec2 min, dvec2 max, dvec2 a) => dvec2.Lerp(min, max, a);
/// <summary>
/// Returns a dvec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static dvec2 Smoothstep(dvec2 edge0, dvec2 edge1, dvec2 v) => dvec2.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a dvec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static dvec2 Smootherstep(dvec2 edge0, dvec2 edge1, dvec2 v) => dvec2.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a dvec2 from component-wise application of Fma (a * b + c).
/// </summary>
public static dvec2 Fma(dvec2 a, dvec2 b, dvec2 c) => dvec2.Fma(a, b, c);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static dmat2 OuterProduct(dvec2 c, dvec2 r) => dvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static dmat3x2 OuterProduct(dvec2 c, dvec3 r) => dvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static dmat4x2 OuterProduct(dvec2 c, dvec4 r) => dvec2.OuterProduct(c, r);
/// <summary>
/// Returns a dvec2 from component-wise application of Add (lhs + rhs).
/// </summary>
public static dvec2 Add(dvec2 lhs, dvec2 rhs) => dvec2.Add(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static dvec2 Sub(dvec2 lhs, dvec2 rhs) => dvec2.Sub(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static dvec2 Mul(dvec2 lhs, dvec2 rhs) => dvec2.Mul(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Div (lhs / rhs).
/// </summary>
public static dvec2 Div(dvec2 lhs, dvec2 rhs) => dvec2.Div(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Modulo (lhs % rhs).
/// </summary>
public static dvec2 Modulo(dvec2 lhs, dvec2 rhs) => dvec2.Modulo(lhs, rhs);
/// <summary>
/// Returns a dvec2 from component-wise application of Degrees (Radians-To-Degrees Conversion).
/// </summary>
public static dvec2 Degrees(dvec2 v) => dvec2.Degrees(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Radians (Degrees-To-Radians Conversion).
/// </summary>
public static dvec2 Radians(dvec2 v) => dvec2.Radians(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Acos ((double)Math.Acos((double)v)).
/// </summary>
public static dvec2 Acos(dvec2 v) => dvec2.Acos(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Asin ((double)Math.Asin((double)v)).
/// </summary>
public static dvec2 Asin(dvec2 v) => dvec2.Asin(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Atan ((double)Math.Atan((double)v)).
/// </summary>
public static dvec2 Atan(dvec2 v) => dvec2.Atan(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Cos ((double)Math.Cos((double)v)).
/// </summary>
public static dvec2 Cos(dvec2 v) => dvec2.Cos(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Cosh ((double)Math.Cosh((double)v)).
/// </summary>
public static dvec2 Cosh(dvec2 v) => dvec2.Cosh(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Exp ((double)Math.Exp((double)v)).
/// </summary>
public static dvec2 Exp(dvec2 v) => dvec2.Exp(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Log ((double)Math.Log((double)v)).
/// </summary>
public static dvec2 Log(dvec2 v) => dvec2.Log(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Log2 ((double)Math.Log((double)v, 2)).
/// </summary>
public static dvec2 Log2(dvec2 v) => dvec2.Log2(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Log10 ((double)Math.Log10((double)v)).
/// </summary>
public static dvec2 Log10(dvec2 v) => dvec2.Log10(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Floor ((double)Math.Floor(v)).
/// </summary>
public static dvec2 Floor(dvec2 v) => dvec2.Floor(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Ceiling ((double)Math.Ceiling(v)).
/// </summary>
public static dvec2 Ceiling(dvec2 v) => dvec2.Ceiling(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Round ((double)Math.Round(v)).
/// </summary>
public static dvec2 Round(dvec2 v) => dvec2.Round(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Sin ((double)Math.Sin((double)v)).
/// </summary>
public static dvec2 Sin(dvec2 v) => dvec2.Sin(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Sinh ((double)Math.Sinh((double)v)).
/// </summary>
public static dvec2 Sinh(dvec2 v) => dvec2.Sinh(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Tan ((double)Math.Tan((double)v)).
/// </summary>
public static dvec2 Tan(dvec2 v) => dvec2.Tan(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Tanh ((double)Math.Tanh((double)v)).
/// </summary>
public static dvec2 Tanh(dvec2 v) => dvec2.Tanh(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Truncate ((double)Math.Truncate((double)v)).
/// </summary>
public static dvec2 Truncate(dvec2 v) => dvec2.Truncate(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Fract ((double)(v - Math.Floor(v))).
/// </summary>
public static dvec2 Fract(dvec2 v) => dvec2.Fract(v);
/// <summary>
/// Returns a dvec2 from component-wise application of Trunc ((long)(v)).
/// </summary>
public static dvec2 Trunc(dvec2 v) => dvec2.Trunc(v);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static double MinElement(dvec2 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static double MaxElement(dvec2 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static double Length(dvec2 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static double LengthSqr(dvec2 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static double Sum(dvec2 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static double Norm(dvec2 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static double Norm1(dvec2 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static double Norm2(dvec2 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static double NormMax(dvec2 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(dvec2 v, double p) => v.NormP(p);
/// <summary>
/// Returns a copy of this vector with length one (undefined if this has zero length).
/// </summary>
public static dvec2 Normalized(dvec2 v) => v.Normalized;
/// <summary>
/// Returns a copy of this vector with length one (returns zero if length is zero).
/// </summary>
public static dvec2 NormalizedSafe(dvec2 v) => v.NormalizedSafe;
/// <summary>
/// Returns the vector angle (atan2(y, x)) in radians.
/// </summary>
public static double Angle(dvec2 v) => v.Angle;
/// <summary>
/// Returns a 2D vector that was rotated by a given angle in radians (CAUTION: result is casted and may be truncated).
/// </summary>
public static dvec2 Rotated(dvec2 v, double angleInRad) => v.Rotated(angleInRad);
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static double Dot(dvec2 lhs, dvec2 rhs) => dvec2.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static double Distance(dvec2 lhs, dvec2 rhs) => dvec2.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static double DistanceSqr(dvec2 lhs, dvec2 rhs) => dvec2.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static dvec2 Reflect(dvec2 I, dvec2 N) => dvec2.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static dvec2 Refract(dvec2 I, dvec2 N, double eta) => dvec2.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static dvec2 FaceForward(dvec2 N, dvec2 I, dvec2 Nref) => dvec2.FaceForward(N, I, Nref);
/// <summary>
/// Returns the length of the outer product (cross product, vector product) of the two vectors.
/// </summary>
public static double Cross(dvec2 l, dvec2 r) => dvec2.Cross(l, r);
/// <summary>
/// Returns a dvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static dvec2 Random(Random random, dvec2 minValue, dvec2 maxValue) => dvec2.Random(random, minValue, maxValue);
/// <summary>
/// Returns a dvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static dvec2 RandomUniform(Random random, dvec2 minValue, dvec2 maxValue) => dvec2.RandomUniform(random, minValue, maxValue);
/// <summary>
/// Returns a dvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static dvec2 RandomNormal(Random random, dvec2 mean, dvec2 variance) => dvec2.RandomNormal(random, mean, variance);
/// <summary>
/// Returns a dvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static dvec2 RandomGaussian(Random random, dvec2 mean, dvec2 variance) => dvec2.RandomGaussian(random, mean, variance);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using Zenject;
namespace Zenject
{
public abstract class FactoryProviderBase<TValue, TFactory> : IProvider
where TFactory : IFactory
{
public FactoryProviderBase(DiContainer container)
{
Container = container;
}
protected DiContainer Container
{
get;
private set;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public abstract IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args);
}
// Zero parameters
public class FactoryProvider<TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEmpty(args);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
// Do this even when validating in case it has its own dependencies
var factory = Container.Instantiate(typeof(TFactory));
if (Container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>() { ((TFactory)factory).Create() };
}
}
}
// One parameters
public class FactoryProvider<TParam1, TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TParam1, TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 1);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.IsEqual(args[0].Type, typeof(TParam1));
if (Container.IsValidating)
{
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
Container.Instantiate<TFactory>().Create((TParam1)args[0].Value)
};
}
}
}
// Two parameters
public class FactoryProvider<TParam1, TParam2, TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TParam1, TParam2, TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 2);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.IsEqual(args[0].Type, typeof(TParam1));
Assert.IsEqual(args[1].Type, typeof(TParam2));
if (Container.IsValidating)
{
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
Container.Instantiate<TFactory>().Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value)
};
}
}
}
// Three parameters
public class FactoryProvider<TParam1, TParam2, TParam3, TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TParam1, TParam2, TParam3, TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 3);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.IsEqual(args[0].Type, typeof(TParam1));
Assert.IsEqual(args[1].Type, typeof(TParam2));
Assert.IsEqual(args[2].Type, typeof(TParam3));
if (Container.IsValidating)
{
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
Container.Instantiate<TFactory>().Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value)
};
}
}
}
// Four parameters
public class FactoryProvider<TParam1, TParam2, TParam3, TParam4, TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 4);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.IsEqual(args[0].Type, typeof(TParam1));
Assert.IsEqual(args[1].Type, typeof(TParam2));
Assert.IsEqual(args[2].Type, typeof(TParam3));
Assert.IsEqual(args[3].Type, typeof(TParam4));
if (Container.IsValidating)
{
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
Container.Instantiate<TFactory>().Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value)
};
}
}
}
// Five parameters
public class FactoryProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TValue, TFactory> : FactoryProviderBase<TValue, TFactory>
where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>
{
public FactoryProvider(DiContainer container)
: base(container)
{
}
public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 5);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.IsEqual(args[0].Type, typeof(TParam1));
Assert.IsEqual(args[1].Type, typeof(TParam2));
Assert.IsEqual(args[2].Type, typeof(TParam3));
Assert.IsEqual(args[3].Type, typeof(TParam4));
Assert.IsEqual(args[4].Type, typeof(TParam5));
if (Container.IsValidating)
{
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
Container.Instantiate<TFactory>().Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
(TParam5)args[4].Value)
};
}
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization;
using SharpMap.Data;
using SharpMap.Data.Providers;
using NetTopologySuite.Geometries;
using SharpMap.Rendering;
using SharpMap.Rendering.Thematics;
using SharpMap.Styles;
using Transform = SharpMap.Utilities.Transform;
using SharpMap.Rendering.Symbolizer;
namespace SharpMap.Layers
{
/// <summary>
/// Label layer class
/// </summary>
/// <example>
/// Creates a new label layer and sets the label text to the "Name" column in the FeatureDataTable of the datasource
/// <code lang="C#">
/// //Set up a label layer
/// SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels");
/// layLabel.DataSource = layCountries.DataSource;
/// layLabel.Enabled = true;
/// layLabel.LabelColumn = "Name";
/// layLabel.Style = new SharpMap.Styles.LabelStyle();
/// layLabel.Style.CollisionDetection = true;
/// layLabel.Style.CollisionBuffer = new SizeF(20, 20);
/// layLabel.Style.ForeColor = Color.White;
/// layLabel.Style.Font = new Font(FontFamily.GenericSerif, 8);
/// layLabel.MaxVisible = 90;
/// layLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
/// </code>
/// </example>
[Serializable]
public class LabelLayer : Layer
{
#region Delegates
/// <summary>
/// Delegate method for creating advanced label texts
/// </summary>
/// <param name="fdr">the <see cref="FeatureDataRow"/> to build the label for</param>
/// <returns>the label</returns>
public delegate string GetLabelMethod(FeatureDataRow fdr);
/// <summary>
/// Delegate method for calculating the priority of label rendering
/// </summary>
/// <param name="fdr">the <see cref="FeatureDataRow"/> to compute the priority value from</param>
/// <returns>the priority value</returns>
public delegate int GetPriorityMethod(FeatureDataRow fdr);
/// <summary>
/// Delegate method for advanced placement of the label position
/// </summary>
/// <param name="fdr">the <see cref="FeatureDataRow"/> to compute the label position from</param>
/// <returns>the priority value</returns>
public delegate Coordinate GetLocationMethod(FeatureDataRow fdr);
#endregion
#region MultipartGeometryBehaviourEnum enum
/// <summary>
/// Labelling behaviour for Multipart geometry collections
/// </summary>
public enum MultipartGeometryBehaviourEnum
{
/// <summary>
/// Place label on all parts (default)
/// </summary>
All,
/// <summary>
/// Place label on object which the greatest length or area.
/// </summary>
/// <remarks>
/// MultiPoint geometries will default to <see cref="First"/>
/// </remarks>
Largest,
/// <summary>
/// The center of the combined geometries
/// </summary>
CommonCenter,
/// <summary>
/// Center of the first geometry in the collection (fastest method)
/// </summary>
First
}
#endregion
private IBaseProvider _dataSource;
private GetLabelMethod _getLabelMethod;
private GetPriorityMethod _getPriorityMethod;
private GetLocationMethod _getLocationMethod;
private Envelope _envelope;
/// <summary>
/// Name of the column that holds the value for the label.
/// </summary>
private string _labelColumn;
/// <summary>
/// Delegate for custom Label Collision Detection
/// </summary>
private LabelCollisionDetection.LabelFilterMethod _labelFilter;
/// <summary>
/// A value indication the priority of the label in cases of label-collision detection
/// </summary>
private int _priority;
/// <summary>
/// Name of the column that contains the value indicating the priority of the label in case of label-collision detection
/// </summary>
private string _priorityColumn = "";
/// <summary>
/// Name of the column that contains the value indicating the rotation value of the label
/// </summary>
private string _rotationColumn;
private TextRenderingHint _textRenderingHint;
private ITheme _theme;
/// <summary>
/// Creates a new instance of a LabelLayer
/// </summary>
public LabelLayer(string layername)
:base(new LabelStyle())
{
//_Style = new LabelStyle();
LayerName = layername;
SmoothingMode = SmoothingMode.AntiAlias;
TextRenderingHint = TextRenderingHint.AntiAlias;
MultipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
_labelFilter = LabelCollisionDetection.SimpleCollisionDetection;
}
/// <summary>
/// Gets or sets labelling behavior on multipart geometries
/// </summary>
/// <remarks>Default value is <see cref="MultipartGeometryBehaviourEnum.All"/></remarks>
public MultipartGeometryBehaviourEnum MultipartGeometryBehaviour { get; set; }
/// <summary>
/// Filtermethod delegate for performing filtering
/// </summary>
/// <remarks>
/// Default method is <see cref="SharpMap.Rendering.LabelCollisionDetection.SimpleCollisionDetection"/>
/// </remarks>
public LabelCollisionDetection.LabelFilterMethod LabelFilter
{
get { return _labelFilter; }
set { _labelFilter = value; }
}
/// <summary>
/// Render whether smoothing (antialiasing) is applied to lines and curves and the edges of filled areas
/// </summary>
public SmoothingMode SmoothingMode { get; set; }
/// <summary>
/// Specifies the quality of text rendering
/// </summary>
public TextRenderingHint TextRenderingHint
{
get { return _textRenderingHint; }
set { _textRenderingHint = value; }
}
/// <summary>
/// Gets or sets the datasource
/// </summary>
public IBaseProvider DataSource
{
get { return _dataSource; }
set
{
_dataSource = value;
_envelope = null;
}
}
/// <summary>
/// Gets or sets the rendering style of the label layer.
/// </summary>
public new LabelStyle Style
{
get { return base.Style as LabelStyle; }
set { base.Style = value; }
}
/// <summary>
/// Gets or sets thematic settings for the layer. Set to null to ignore thematics
/// </summary>
public ITheme Theme
{
get { return _theme; }
set { _theme = value; }
}
/// <summary>
/// Data column or expression where label text is extracted from.
/// </summary>
/// <remarks>
/// This property is overridden by the <see cref="LabelStringDelegate"/>.
/// </remarks>
public string LabelColumn
{
get { return _labelColumn; }
set { _labelColumn = value; }
}
/// <summary>
/// Gets or sets the method for creating a custom label string based on a feature.
/// </summary>
/// <remarks>
/// <para>If this method is not null, it will override the <see cref="LabelColumn"/> value.</para>
/// <para>The label delegate must take a <see cref="SharpMap.Data.FeatureDataRow"/> and return a string.</para>
/// <example>
/// Creating a label-text by combining attributes "ROADNAME" and "STATE" into one string, using
/// an anonymous delegate:
/// <code lang="C#">
/// myLabelLayer.LabelStringDelegate = delegate(SharpMap.Data.FeatureDataRow fdr)
/// { return fdr["ROADNAME"].ToString() + ", " + fdr["STATE"].ToString(); };
/// </code>
/// </example>
/// </remarks>
public GetLabelMethod LabelStringDelegate
{
get { return _getLabelMethod; }
set { _getLabelMethod = value; }
}
/// <summary>
/// Gets or sets the method for creating a custom position based on a feature.
/// </summary>
/// <remarks>
/// <para>If this method is not null, it will override the position based on the centroid of the boundingbox of the feature </para>
/// <para>The label delegate must take a <see cref="SharpMap.Data.FeatureDataRow"/> and return a NetTopologySuite.Geometries.Coordinate.</para>
/// <para>If the delegate returns a null, the centroid of the feature will be used</para>
/// <example>
/// Creating a custom position by using X and Y values from the FeatureDataRow attributes "LabelX" and "LabelY", using
/// an anonymous delegate:
/// <code lang="C#">
/// myLabelLayer.LabelPositionDelegate = delegate(SharpMap.Data.FeatureDataRow fdr)
/// { return new NetTopologySuite.Geometries.Coordinate(Convert.ToDouble(fdr["LabelX"]), Convert.ToDouble(fdr["LabelY"]));};
/// </code>
/// </example>
/// </remarks>
public GetLocationMethod LabelPositionDelegate
{
get { return _getLocationMethod; }
set { _getLocationMethod = value; }
}
/// <summary>
/// Gets or sets the method for calculating the render priority of a label based on a feature.
/// </summary>
/// <remarks>
/// <para>If this method is not null, it will override the <see cref="PriorityColumn"/> value.</para>
/// <para>The label delegate must take a <see cref="SharpMap.Data.FeatureDataRow"/> and return an Int32.</para>
/// <example>
/// Creating a priority by combining attributes "capital" and "population" into one value, using
/// an anonymous delegate:
/// <code lang="C#">
/// myLabelLayer.PriorityDelegate = delegate(SharpMap.Data.FeatureDataRow fdr)
/// {
/// Int32 retVal = 100000000 * (Int32)( (String)fdr["capital"] == "Y" ? 1 : 0 );
/// return retVal + Convert.ToInt32(fdr["population"]);
/// };
/// </code>
/// </example>
/// </remarks>
public GetPriorityMethod PriorityDelegate
{
get { return _getPriorityMethod; }
set { _getPriorityMethod = value; }
}
/// <summary>
/// Data column from where the label rotation is derived.
/// If this is empty, rotation will be zero, or aligned to a linestring.
/// Rotation are in degrees (positive = clockwise).
/// </summary>
public string RotationColumn
{
get { return _rotationColumn; }
set { _rotationColumn = value; }
}
/// <summary>
/// A value indication the priority of the label in cases of label-collision detection
/// </summary>
public int Priority
{
get { return _priority; }
set { _priority = value; }
}
/// <summary>
/// Name of the column that holds the value indicating the priority of the label in cases of label-collision detection
/// </summary>
public string PriorityColumn
{
get { return _priorityColumn; }
set { _priorityColumn = value; }
}
/// <summary>
/// Gets the boundingbox of the entire layer
/// </summary>
public override Envelope Envelope
{
get
{
if (DataSource == null)
throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'"));
if (_envelope != null && CacheExtent)
return ToTarget(_envelope.Copy());
var wasOpen = DataSource.IsOpen;
if (!wasOpen)
DataSource.Open();
var box = DataSource.GetExtents();
if (!wasOpen) //Restore state
DataSource.Close();
if (CacheExtent)
_envelope = box;
return ToTarget(box);
}
}
/// <summary>
/// Gets or sets a value indicating whether the layer envelope should be treated as static or not.
/// </summary>
/// <remarks>
/// When CacheExtent is enabled the layer Envelope will be calculated only once from DataSource, this
/// helps to speed up the Envelope calculation with some DataProviders. Default is false for backward
/// compatibility.
/// </remarks>
public virtual bool CacheExtent { get; set; }
/// <summary>
/// Gets or sets the SRID of this VectorLayer's data source
/// </summary>
public override int SRID
{
get
{
if (DataSource == null)
throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'"));
return DataSource.SRID;
}
set { DataSource.SRID = value; }
}
#region IDisposable Members
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (DataSource != null)
DataSource.Dispose();
base.ReleaseManagedResources();
}
#endregion
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="g">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
public override void Render(Graphics g, MapViewport map)
{
if (DataSource == null)
throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'"));
g.TextRenderingHint = TextRenderingHint;
g.SmoothingMode = SmoothingMode;
var mapEnvelope = map.Envelope;
var layerEnvelope = ToSource(mapEnvelope); //View to render
var lineClipping = new CohenSutherlandLineClipping(mapEnvelope.MinX, mapEnvelope.MinY,
mapEnvelope.MaxX, mapEnvelope.MaxY);
var ds = new FeatureDataSet();
DataSource.Open();
DataSource.ExecuteIntersectionQuery(layerEnvelope, ds);
DataSource.Close();
if (ds.Tables.Count == 0)
{
base.Render(g, map);
return;
}
var features = ds.Tables[0];
//Initialize label collection
var labels = new List<BaseLabel>();
//List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection
//Render labels
for (int i = 0; i < features.Count; i++)
{
var feature = features[i];
feature.Geometry = ToTarget(feature.Geometry);
LabelStyle style;
if (Theme != null) //If thematics is enabled, lets override the style
style = Theme.GetStyle(feature) as LabelStyle;
else
style = Style;
// Do we need to render at all?
if (!style.Enabled) continue;
// Rotation
float rotationStyle = style != null ? style.Rotation : 0f;
float rotationColumn = 0f;
if (!string.IsNullOrEmpty(RotationColumn))
Single.TryParse(feature[RotationColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs,
out rotationColumn);
float rotation = rotationStyle + rotationColumn;
// Priority
int priority = Priority;
if (_getPriorityMethod != null)
priority = _getPriorityMethod(feature);
else if (!string.IsNullOrEmpty(PriorityColumn))
Int32.TryParse(feature[PriorityColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs,
out priority);
// Text
string text;
if (_getLabelMethod != null)
text = _getLabelMethod(feature);
else
text = feature[LabelColumn].ToString();
if (!string.IsNullOrEmpty(text))
{
// for lineal geometries, try clipping to ensure proper labeling
if (feature.Geometry is ILineal)
{
if (feature.Geometry is LineString)
feature.Geometry = lineClipping.ClipLineString(feature.Geometry as LineString);
else if (feature.Geometry is MultiLineString)
feature.Geometry = lineClipping.ClipLineString(feature.Geometry as MultiLineString);
}
if (feature.Geometry is GeometryCollection)
{
if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All)
{
foreach (var geom in (feature.Geometry as GeometryCollection))
{
BaseLabel lbl = CreateLabel(feature, geom, text, rotation, priority, style, map, g, _getLocationMethod);
if (lbl != null)
labels.Add(lbl);
}
}
else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter)
{
BaseLabel lbl = CreateLabel(feature, feature.Geometry, text, rotation, priority, style, map, g, _getLocationMethod);
if (lbl != null)
labels.Add(lbl);
}
else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First)
{
if ((feature.Geometry as GeometryCollection).NumGeometries > 0)
{
BaseLabel lbl = CreateLabel(feature, (feature.Geometry as GeometryCollection).GetGeometryN(0), text,
rotation, style, map, g);
if (lbl != null)
labels.Add(lbl);
}
}
else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest)
{
var coll = (feature.Geometry as GeometryCollection);
if (coll.NumGeometries > 0)
{
var largestVal = 0d;
var idxOfLargest = 0;
for (var j = 0; j < coll.NumGeometries; j++)
{
var geom = coll.GetGeometryN(j);
if (geom is LineString && ((LineString) geom).Length > largestVal)
{
largestVal = ((LineString) geom).Length;
idxOfLargest = j;
}
if (geom is MultiLineString && ((MultiLineString) geom).Length > largestVal)
{
largestVal = ((MultiLineString) geom).Length;
idxOfLargest = j;
}
if (geom is Polygon && ((Polygon) geom).Area > largestVal)
{
largestVal = ((Polygon) geom).Area;
idxOfLargest = j;
}
if (geom is MultiPolygon && ((MultiPolygon) geom).Area > largestVal)
{
largestVal = ((MultiPolygon) geom).Area;
idxOfLargest = j;
}
}
BaseLabel lbl = CreateLabel(feature, coll.GetGeometryN(idxOfLargest), text, rotation, priority, style,
map, g, _getLocationMethod);
if (lbl != null)
labels.Add(lbl);
}
}
}
else
{
BaseLabel lbl = CreateLabel(feature, feature.Geometry, text, rotation, priority, style, map, g, _getLocationMethod);
if (lbl != null)
labels.Add(lbl);
}
}
}
if (labels.Count > 0) //We have labels to render...
{
if (Style.CollisionDetection && _labelFilter != null)
_labelFilter(labels);
for (int i = 0; i < labels.Count; i++)
{
// Don't show the label if not necessary
if (!labels[i].Show)
{
continue;
}
if (labels[i] is Label)
{
var label = labels[i] as Label;
if (label.Style.IsTextOnPath == false || label.TextOnPathLabel == null)
{
VectorRenderer.DrawLabel(g, label.Location, label.Style.Offset,
label.Style.GetFontForGraphics(g), label.Style.ForeColor,
label.Style.BackColor, label.Style.Halo, label.Rotation,
label.Text, map, label.Style.HorizontalAlignment,
label.LabelPoint);
}
else
{
if (label.Style.BackColor != null && label.Style.BackColor != System.Drawing.Brushes.Transparent)
{
//draw background
if (label.TextOnPathLabel.RegionList.Count > 0)
{
g.FillRectangles(labels[i].Style.BackColor, labels[i].TextOnPathLabel.RegionList.ToArray());
//g.FillPolygon(labels[i].Style.BackColor, labels[i].TextOnPathLabel.PointsText.ToArray());
}
}
label.TextOnPathLabel.DrawTextOnPath();
}
}
else if (labels[i] is PathLabel)
{
var plbl = labels[i] as PathLabel;
var lblStyle = plbl.Style;
g.DrawString(lblStyle.Halo, new SolidBrush(lblStyle.ForeColor), plbl.Text,
lblStyle.Font.FontFamily, (int) lblStyle.Font.Style, lblStyle.Font.Size,
lblStyle.GetStringFormat(), lblStyle.IgnoreLength, plbl.Location);
}
}
}
base.Render(g, map);
}
private BaseLabel CreateLabel(FeatureDataRow fdr, Geometry feature, string text, float rotation, LabelStyle style, MapViewport map, Graphics g)
{
return CreateLabel(fdr, feature, text, rotation, Priority, style, map, g, _getLocationMethod);
}
private static BaseLabel CreateLabel(FeatureDataRow fdr, Geometry feature, string text, float rotation, int priority, LabelStyle style, MapViewport map, Graphics g, GetLocationMethod _getLocationMethod)
{
if (feature == null) return null;
BaseLabel lbl = null;
var font = style.GetFontForGraphics(g);
SizeF size = VectorRenderer.SizeOfString(g, text, font);
if (feature is ILineal)
{
if (feature is LineString line)
{
if (style.IsTextOnPath == false)
{
if (size.Width < 0.95 * line.Length / map.PixelWidth || style.IgnoreLength)
{
var positiveLineString = PositiveLineString(line, false);
var lineStringPath = LineStringToPath(positiveLineString, map /*, false*/);
var rect = lineStringPath.GetBounds();
if (style.CollisionDetection && !style.CollisionBuffer.IsEmpty)
{
var cbx = style.CollisionBuffer.Width;
var cby = style.CollisionBuffer.Height;
rect.Inflate(2 * cbx, 2 * cby);
rect.Offset(-cbx, -cby);
}
var labelBox = new LabelBox(rect);
lbl = new PathLabel(text, lineStringPath, 0, priority, labelBox, style);
}
}
else
{
//get centriod
System.Drawing.PointF position2 = map.WorldToImage(feature.EnvelopeInternal.Centre);
lbl = new Label(text, position2, rotation, priority, style);
if (size.Width < 0.95 * line.Length / map.PixelWidth || !style.IgnoreLength)
{
CalculateLabelAroundOnLineString(line, ref lbl, map, g, size);
}
}
}
return lbl;
}
var worldPosition = _getLocationMethod == null
? feature.EnvelopeInternal.Centre
: _getLocationMethod(fdr);
if (worldPosition == null) return null;
var position = map.WorldToImage(worldPosition);
var location = new PointF(
position.X - size.Width*(short) style.HorizontalAlignment*0.5f,
position.Y - size.Height*(short) (2 - (int) style.VerticalAlignment)*0.5f);
if (location.X - size.Width > map.Size.Width || location.X + size.Width < 0 ||
location.Y - size.Height > map.Size.Height || location.Y + size.Height < 0)
return null;
if (!style.CollisionDetection)
lbl = new Label(text, location, rotation, priority, null, style)
{LabelPoint = position};
else
{
//Collision detection is enabled so we need to measure the size of the string
lbl = new Label(text, location, rotation, priority,
new LabelBox(location.X - style.CollisionBuffer.Width,
location.Y - style.CollisionBuffer.Height,
size.Width + 2f*style.CollisionBuffer.Width,
size.Height + 2f*style.CollisionBuffer.Height), style)
{ LabelPoint = position };
}
/*
if (feature is LineString)
{
var line = feature as LineString;
//Only label feature if it is long enough, or it is definately wanted
if (line.Length / map.PixelSize > size.Width || style.IgnoreLength)
{
CalculateLabelOnLinestring(line, ref lbl, map);
}
else
return null;
}
*/
return lbl;
}
/// <summary>
/// Very basic test to check for positive direction of Linestring
/// </summary>
/// <param name="line">The linestring to test</param>
/// <param name="isRightToLeft">Value indicating whether labels are to be printed right to left</param>
/// <returns>The positively directed linestring</returns>
private static LineString PositiveLineString(LineString line, bool isRightToLeft)
{
var s = line.StartPoint;
var e = line.EndPoint;
var dx = e.X - s.X;
if (isRightToLeft && dx < 0)
return line;
if (!isRightToLeft && dx >= 0)
return line;
var revCoord = new Stack<Coordinate>(line.Coordinates);
return line.Factory.CreateLineString(revCoord.ToArray());
}
//private static void WarpedLabel(MultiLineString line, ref BaseLabel baseLabel, Map map)
//{
// var path = MultiLineStringToPath(line, map, true);
// var pathLabel = new PathLabel(baseLabel.Text, path, 0f, baseLabel.Priority, new LabelBox(path.GetBounds()), baseLabel.Style);
// baseLabel = pathLabel;
//}
//private static void WarpedLabel(LineString line, ref BaseLabel baseLabel, Map map)
//{
// var path = LineStringToPath(line, map, false);
// var pathLabel = new PathLabel(baseLabel.Text, path, 0f, baseLabel.Priority, new LabelBox(path.GetBounds()), baseLabel.Style);
// baseLabel = pathLabel;
//}
/// <summary>
/// Function to transform a linestring to a graphics path for further processing
/// </summary>
/// <param name="lineString">The Linestring</param>
/// <param name="map">The map</param>
/// <!--<param name="useClipping">A value indicating whether clipping should be applied or not</param>-->
/// <returns>A GraphicsPath</returns>
public static GraphicsPath LineStringToPath(LineString lineString, MapViewport map/*, bool useClipping*/)
{
var gp = new GraphicsPath(FillMode.Alternate);
//if (!useClipping)
gp.AddLines(lineString.TransformToImage(map));
//else
//{
// var bb = map.Envelope;
// var cohenSutherlandLineClipping = new CohenSutherlandLineClipping(bb.Left, bb.Bottom, bb.Right, bb.Top);
// var clippedLineStrings = cohenSutherlandLineClipping.ClipLineString(lineString);
// foreach (var clippedLineString in clippedLineStrings.LineStrings)
// {
// var s = clippedLineString.StartPoint;
// var e = clippedLineString.EndPoint;
// var dx = e.X - s.X;
// //var dy = e.Y - s.Y;
// LineString revcls = null;
// if (dx < 0)
// revcls = ReverseLineString(clippedLineString);
// gp.StartFigure();
// gp.AddLines(revcls == null ? clippedLineString.TransformToImage(map) : revcls.TransformToImage(map));
// }
//}
return gp;
}
//private static LineString ReverseLineString(LineString clippedLineString)
//{
// var coords = new Stack<Point>(clippedLineString.Vertices);
// return new LineString(coords.ToArray());
//}
///// <summary>
///// Function to transform a linestring to a graphics path for further processing
///// </summary>
///// <param name="MultiLineString">The Linestring</param>
///// <param name="map">The map</param>
///// <param name="useClipping">A value indicating whether clipping should be applied or not</param>
///// <returns>A GraphicsPath</returns>
//public static GraphicsPath MultiLineStringToPath(MultiLineString MultiLineString, Map map, bool useClipping)
//{
// var gp = new GraphicsPath(FillMode.Alternate);
// foreach (var lineString in MultiLineString.LineStrings)
// gp.AddPath(LineStringToPath(lineString, map, useClipping), false);
// return gp;
//}
//private static GraphicsPath LineToGraphicsPath(LineString line, Map map)
//{
// GraphicsPath path = new GraphicsPath();
// path.AddLines(line.TransformToImage(map));
// return path;
//}
static void CalculateLabelOnLinestring(LineString line, ref BaseLabel baseLabel, Map map)
{
double dx, dy;
var label = baseLabel as Label;
// first find the middle segment of the line
var vertices = line.Coordinates;
int midPoint = (vertices.Length - 1)/2;
if (vertices.Length > 2)
{
dx = vertices[midPoint + 1].X - vertices[midPoint].X;
dy = vertices[midPoint + 1].Y - vertices[midPoint].Y;
}
else
{
midPoint = 0;
dx = vertices[1].X - vertices[0].X;
dy = vertices[1].Y - vertices[0].Y;
}
if (dy == 0)
label.Rotation = 0;
else if (dx == 0)
label.Rotation = 90;
else
{
// calculate angle of line
double angle = -Math.Atan(dy/dx) + Math.PI*0.5;
angle *= (180d/Math.PI); // convert radians to degrees
label.Rotation = (float) angle - 90; // -90 text orientation
}
var tmpx = vertices[midPoint].X + (dx*0.5);
var tmpy = vertices[midPoint].Y + (dy*0.5);
label.Location = map.WorldToImage(new Coordinate(tmpx, tmpy));
}
private static void CalculateLabelAroundOnLineString(LineString line, ref BaseLabel label, MapViewport map, System.Drawing.Graphics g, SizeF textSize)
{
var sPoints = line.Coordinates;
// only get point in enverlop of map
var colPoint = new Collection<PointF>();
var bCheckStarted = false;
//var testEnvelope = map.Envelope.Grow(map.PixelSize*10);
for (var j = 0; j < sPoints.Length; j++)
{
if (map.Envelope.Contains(sPoints[j]))
{
//points[j] = map.WorldToImage(sPoints[j]);
colPoint.Add(map.WorldToImage(sPoints[j]));
bCheckStarted = true;
}
else if (bCheckStarted)
{
// fix bug curved line out of map in center segment of line
break;
}
}
if (colPoint.Count > 1)
{
label.TextOnPathLabel = new TextOnPath();
switch (label.Style.HorizontalAlignment)
{
case LabelStyle.HorizontalAlignmentEnum.Left:
label.TextOnPathLabel.TextPathAlignTop = TextPathAlign.Left;
break;
case LabelStyle.HorizontalAlignmentEnum.Right:
label.TextOnPathLabel.TextPathAlignTop = TextPathAlign.Right;
break;
case LabelStyle.HorizontalAlignmentEnum.Center:
label.TextOnPathLabel.TextPathAlignTop = TextPathAlign.Center;
break;
default:
label.TextOnPathLabel.TextPathAlignTop = TextPathAlign.Center;
break;
}
switch (label.Style.VerticalAlignment)
{
case LabelStyle.VerticalAlignmentEnum.Bottom:
label.TextOnPathLabel.TextPathPathPosition = TextPathPosition.UnderPath;
break;
case LabelStyle.VerticalAlignmentEnum.Top:
label.TextOnPathLabel.TextPathPathPosition = TextPathPosition.OverPath;
break;
case LabelStyle.VerticalAlignmentEnum.Middle:
label.TextOnPathLabel.TextPathPathPosition = TextPathPosition.CenterPath;
break;
default:
label.TextOnPathLabel.TextPathPathPosition = TextPathPosition.CenterPath;
break;
}
var idxStartPath = 0;
var numberPoint = colPoint.Count;
// start Optimzes Path points
var step = 100;
if (colPoint.Count >= step * 2)
{
numberPoint = step * 2; ;
switch (label.Style.HorizontalAlignment)
{
case LabelStyle.HorizontalAlignmentEnum.Left:
//label.TextOnPathLabel.TextPathAlignTop = SharpMap.Rendering.TextPathAlign.Left;
idxStartPath = 0;
break;
case LabelStyle.HorizontalAlignmentEnum.Right:
//label.TextOnPathLabel.TextPathAlignTop = SharpMap.Rendering.TextPathAlign.Right;
idxStartPath = colPoint.Count - step;
break;
case LabelStyle.HorizontalAlignmentEnum.Center:
//label.TextOnPathLabel.TextPathAlignTop = SharpMap.Rendering.TextPathAlign.Center;
idxStartPath = (int)colPoint.Count / 2 - step;
break;
default:
//label.TextOnPathLabel.TextPathAlignTop = SharpMap.Rendering.TextPathAlign.Center;
idxStartPath = (int)colPoint.Count / 2 - step;
break;
}
}
// end optimize path point
var points = new PointF[numberPoint];
var count = 0;
if (colPoint[0].X <= colPoint[colPoint.Count - 1].X)
{
for (var l = idxStartPath; l < numberPoint + idxStartPath; l++)
{
points[count] = colPoint[l];
count++;
}
}
else
{
//reverse the path
for (var k = numberPoint - 1 + idxStartPath; k >= idxStartPath; k--)
{
points[count] = colPoint[k];
count++;
}
}
/*
//get text size in page units ie pixels
float textheight = label.Style.Font.Size;
switch (label.Style.Font.Unit)
{
case GraphicsUnit.Display:
textheight = textheight * g.DpiY / 75;
break;
case GraphicsUnit.Document:
textheight = textheight * g.DpiY / 300;
break;
case GraphicsUnit.Inch:
textheight = textheight * g.DpiY;
break;
case GraphicsUnit.Millimeter:
textheight = (float)(textheight / 25.4 * g.DpiY);
break;
case GraphicsUnit.Pixel:
//do nothing
break;
case GraphicsUnit.Point:
textheight = textheight * g.DpiY / 72;
break;
}
var topFont = new Font(label.Style.Font.FontFamily, textheight, label.Style.Font.Style, GraphicsUnit.Pixel);
*/
var topFont = label.Style.GetFontForGraphics(g);
//
var path = new GraphicsPath();
path.AddLines(points);
label.TextOnPathLabel.PathColorTop = System.Drawing.Color.Transparent;
label.TextOnPathLabel.Text = label.Text;
label.TextOnPathLabel.LetterSpacePercentage = 90;
label.TextOnPathLabel.FillColorTop = new System.Drawing.SolidBrush(label.Style.ForeColor);
label.TextOnPathLabel.Font = topFont;
label.TextOnPathLabel.PathDataTop = path.PathData;
label.TextOnPathLabel.Graphics = g;
//label.TextOnPathLabel.ShowPath=true;
//label.TextOnPathLabel.PathColorTop = System.Drawing.Color.YellowGreen;
if (label.Style.Halo != null)
{
label.TextOnPathLabel.ColorHalo = label.Style.Halo;
}
else
{
label.TextOnPathLabel.ColorHalo = null;// new System.Drawing.Pen(label.Style.ForeColor, (float)0.5);
}
path.Dispose();
// MeasureString to get region
label.TextOnPathLabel.MeasureString = true;
label.TextOnPathLabel.DrawTextOnPath();
label.TextOnPathLabel.MeasureString = false;
// Get Region label for CollissionDetection here.
var pathRegion = new GraphicsPath();
if (label.TextOnPathLabel.RegionList.Count > 0)
{
//int idxCenter = (int)label.TextOnPathLabel.PointsText.Count / 2;
//System.Drawing.Drawing2D.Matrix rotationMatrix = g.Transform.Clone();// new Matrix();
//rotationMatrix.RotateAt(label.TextOnPathLabel.Angles[idxCenter], label.TextOnPathLabel.PointsText[idxCenter]);
//if (label.TextOnPathLabel.PointsTextUp.Count > 0)
//{
// for (int up = label.TextOnPathLabel.PointsTextUp.Count - 1; up >= 0; up--)
// {
// label.TextOnPathLabel.PointsText.Add(label.TextOnPathLabel.PointsTextUp[up]);
// }
//}
pathRegion.AddRectangles(label.TextOnPathLabel.RegionList.ToArray());
// get box for detect colission here
label.Box = new LabelBox(pathRegion.GetBounds());
//g.FillRectangle(System.Drawing.Brushes.YellowGreen, label.Box);
}
pathRegion.Dispose();
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a Reserved Instance offering.
/// </summary>
public partial class ReservedInstancesOffering
{
private string _availabilityZone;
private CurrencyCodeValues _currencyCode;
private long? _duration;
private float? _fixedPrice;
private Tenancy _instanceTenancy;
private InstanceType _instanceType;
private bool? _marketplace;
private OfferingTypeValues _offeringType;
private List<PricingDetail> _pricingDetails = new List<PricingDetail>();
private RIProductDescription _productDescription;
private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>();
private string _reservedInstancesOfferingId;
private float? _usagePrice;
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone in which the Reserved Instance can be used.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property CurrencyCode.
/// <para>
/// The currency of the Reserved Instance offering you are purchasing. It's specified
/// using ISO 4217 standard currency codes. At this time, the only supported currency
/// is <code>USD</code>.
/// </para>
/// </summary>
public CurrencyCodeValues CurrencyCode
{
get { return this._currencyCode; }
set { this._currencyCode = value; }
}
// Check to see if CurrencyCode property is set
internal bool IsSetCurrencyCode()
{
return this._currencyCode != null;
}
/// <summary>
/// Gets and sets the property Duration.
/// <para>
/// The duration of the Reserved Instance, in seconds.
/// </para>
/// </summary>
public long Duration
{
get { return this._duration.GetValueOrDefault(); }
set { this._duration = value; }
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this._duration.HasValue;
}
/// <summary>
/// Gets and sets the property FixedPrice.
/// <para>
/// The purchase price of the Reserved Instance.
/// </para>
/// </summary>
public float FixedPrice
{
get { return this._fixedPrice.GetValueOrDefault(); }
set { this._fixedPrice = value; }
}
// Check to see if FixedPrice property is set
internal bool IsSetFixedPrice()
{
return this._fixedPrice.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceTenancy.
/// <para>
/// The tenancy of the reserved instance.
/// </para>
/// </summary>
public Tenancy InstanceTenancy
{
get { return this._instanceTenancy; }
set { this._instanceTenancy = value; }
}
// Check to see if InstanceTenancy property is set
internal bool IsSetInstanceTenancy()
{
return this._instanceTenancy != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type on which the Reserved Instance can be used.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property Marketplace.
/// <para>
/// Indicates whether the offering is available through the Reserved Instance Marketplace
/// (resale) or AWS. If it's a Reserved Instance Marketplace offering, this is <code>true</code>.
/// </para>
/// </summary>
public bool Marketplace
{
get { return this._marketplace.GetValueOrDefault(); }
set { this._marketplace = value; }
}
// Check to see if Marketplace property is set
internal bool IsSetMarketplace()
{
return this._marketplace.HasValue;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The Reserved Instance offering type.
/// </para>
/// </summary>
public OfferingTypeValues OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property PricingDetails.
/// <para>
/// The pricing details of the Reserved Instance offering.
/// </para>
/// </summary>
public List<PricingDetail> PricingDetails
{
get { return this._pricingDetails; }
set { this._pricingDetails = value; }
}
// Check to see if PricingDetails property is set
internal bool IsSetPricingDetails()
{
return this._pricingDetails != null && this._pricingDetails.Count > 0;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The Reserved Instance product platform description.
/// </para>
/// </summary>
public RIProductDescription ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property RecurringCharges.
/// <para>
/// The recurring charge tag assigned to the resource.
/// </para>
/// </summary>
public List<RecurringCharge> RecurringCharges
{
get { return this._recurringCharges; }
set { this._recurringCharges = value; }
}
// Check to see if RecurringCharges property is set
internal bool IsSetRecurringCharges()
{
return this._recurringCharges != null && this._recurringCharges.Count > 0;
}
/// <summary>
/// Gets and sets the property ReservedInstancesOfferingId.
/// <para>
/// The ID of the Reserved Instance offering.
/// </para>
/// </summary>
public string ReservedInstancesOfferingId
{
get { return this._reservedInstancesOfferingId; }
set { this._reservedInstancesOfferingId = value; }
}
// Check to see if ReservedInstancesOfferingId property is set
internal bool IsSetReservedInstancesOfferingId()
{
return this._reservedInstancesOfferingId != null;
}
/// <summary>
/// Gets and sets the property UsagePrice.
/// <para>
/// The usage price of the Reserved Instance, per hour.
/// </para>
/// </summary>
public float UsagePrice
{
get { return this._usagePrice.GetValueOrDefault(); }
set { this._usagePrice = value; }
}
// Check to see if UsagePrice property is set
internal bool IsSetUsagePrice()
{
return this._usagePrice.HasValue;
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Text;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using PHP.Core;
using PHP.Core.Reflection;
using System.Diagnostics;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Library.SPL
{
/// <summary>
/// Base class for PHP user exceptions.
/// </summary>
/// <remarks>
/// <para>
/// The class implements PHP5 class Exception which PHP "header" declaration follows:
/// <code>
/// class Exception
/// {
/// protected $message = 'Unknown exception'; // exception message
/// protected $code = 0; // user defined exception code
/// protected $file; // source filename of exception
/// protected $line; // source line of exception
/// protected $column; // source column of exception
/// private $trace; // an array containing the trace
///
/// function __construct($message = null, $code = 0);
///
/// final function getMessage(); // message of exception
/// final function getCode(); // code of exception
/// final function getFile(); // source file name
/// final function getLine(); // source file line
/// final function getColumn(); // source file column
/// final function getTrace(); // the PhpArray representation of the trace
/// final function getTraceAsString(); // formated string of trace
///
/// function __toString(); // formated string for display
/// }
/// </code>
/// </para>
/// <para>
/// The stack trace is captured in the constructor (as in Java) not by throw statement (as in C#).
/// </para>
/// </remarks>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class Exception : PhpObject
{
/// <summary>
/// Contains a trace formatted to the string or a <B>null</B> reference.
/// Needn't to be serialized.
/// </summary>
private string stringTraceCache;
private object previous;
/// <summary>
/// Invoked when the instance is created (not called when unserialized).
/// </summary>
protected override void InstanceCreated(ScriptContext context)
{
base.InstanceCreated(context);
PhpStackTrace trace = new PhpStackTrace(context, 1);
PhpStackFrame frame = trace.GetFrame(0);
Debug.Assert(frame != null);
this.file.Value = frame.File;
this.line.Value = frame.Line;
this.column.Value = frame.Column;
this.trace.Value = trace.GetUserTrace();
}
/// <summary>
/// Gets the default string representation of the exception.
/// </summary>
internal string BaseToString()
{
string type_name = DTypeDesc.GetFullName(this.GetType(), new StringBuilder()).ToString();
int int_line = Core.Convert.ObjectToInteger(line.Value);
int int_column = Core.Convert.ObjectToInteger(column.Value);
string str_file = Core.Convert.ObjectToString(file.Value);
if (int_line > 0 && int_column > 0 && str_file != String.Empty)
{
return CoreResources.GetString("stringified_exception_debug",
type_name,
Core.Convert.ObjectToString(message.Value),
str_file, int_line, int_column,
getTraceAsString(null));
}
else
{
return CoreResources.GetString("stringified_exception",
type_name,
Core.Convert.ObjectToString(message.Value),
getTraceAsString(null));
}
}
#region Throw helpers
/// <summary>
/// Throws <see cref="PhpUserException"/>. Internal <see cref="Exception"/> is created using given <paramref name="factory"/>.
/// </summary>
/// <param name="factory">Factory to create new instance of <see cref="Exception"/>.</param>
/// <param name="context">Current <see cref="ScriptContext"/> provided to factory and <see cref="Exception.__construct"/>.</param>
/// <param name="message">First parameter to be passed to <see cref="Exception.__construct"/>.</param>
/// <param name="code">Second parameter to be passed to <see cref="Exception.__construct"/>.</param>
/// <param name="previous">Thhird parameter to be passed to <see cref="Exception.__construct"/>.</param>
public static void ThrowSplException(Func<ScriptContext, Exception>/*!*/factory, ScriptContext/*!*/context, object message, object code, object previous)
{
Debug.Assert(context != null);
var e = factory(context);
e.__construct(context, message, code, previous);
//
throw new PhpUserException(e);
}
#endregion
#region PHP Fields
/// <summary>
/// A message.
/// </summary>
protected PhpReference message = new PhpSmartReference();
/// <summary>
/// A code.
/// </summary>
protected PhpReference code = new PhpSmartReference();
/// <summary>
/// A source file where the exception has been thrown.
/// </summary>
protected PhpReference file = new PhpSmartReference();
/// <summary>
/// A line in the source file where the exception has been thrown.
/// </summary>
protected PhpReference line = new PhpSmartReference();
/// <summary>
/// A column in the source file where the exception has been thrown.
/// </summary>
protected PhpReference column = new PhpSmartReference();
/// <summary>
/// A user stack trace in form of <see cref="PhpArray"/>.
/// </summary>
private PhpReference trace = new PhpSmartReference();
#endregion
#region PHP Methods
/// <summary>
/// Creates an instance of user exception.
/// </summary>
/// <param name="context">Current <see cref="ScriptContext"/>.</param>
/// <param name="message">A message to be associated with the exception.</param>
/// <param name="code">A code to be associated with the exception.</param>
/// <param name="previous">The previous exception used for the exception chaining.</param>
/// <returns>A <b>null</b> reference (void in PHP).</returns>
[ImplementsMethod]
public virtual object __construct(ScriptContext context, [Optional] object message, [Optional] object code, [Optional] object previous)
{
this.message.Value = (message == Arg.Default || message == Type.Missing) ? CoreResources.GetString("default_exception_message") : message;
this.code.Value = (code == Arg.Default || code == Type.Missing) ? 0 : code;
this.previous = (previous == Arg.Default || previous == Type.Missing) ? null : previous;
Debug.Assert(this.previous == null || (this.previous is DObject && ((DObject)this.previous).RealObject is Exception));
// stack is already captured by CLR ctor //
return null;
}
/// <summary>
/// Converts the instance to a string.
/// </summary>
/// <returns>The string containing formatted trace.</returns>
[ImplementsMethod]
public object __toString(ScriptContext context)
{
return BaseToString();
}
/// <summary>
/// Gets a source file where the exception has been thrown.
/// </summary>
/// <returns>The source file.</returns>
[ImplementsMethod]
public object getFile(ScriptContext context)
{
return file.Value;
}
/// <summary>
/// Gets a line in the source file where the exception has been thrown.
/// </summary>
/// <returns>The line.</returns>
[ImplementsMethod]
public object getLine(ScriptContext context)
{
return line.Value;
}
/// <summary>
/// Gets a column in the source file where the exception has been thrown.
/// </summary>
/// <returns>The column.</returns>
[ImplementsMethod]
public object getColumn(ScriptContext context)
{
return column.Value;
}
/// <summary>
/// Gets the code specified in the constructor.
/// </summary>
/// <returns>The code.</returns>
[ImplementsMethod]
public object getCode(ScriptContext context)
{
return code.Value;
}
/// <summary>
/// Gets a message.
/// </summary>
/// <returns>The message set by the constructor.</returns>
[ImplementsMethod]
public object getMessage(ScriptContext context)
{
return message.Value;
}
/// <summary>
/// Returns previous <see cref="Exception"/> (the third parameter of <see cref="__construct"/>).
/// </summary>
/// <returns></returns>
[ImplementsMethod]
public object getPrevious(ScriptContext context)
{
return previous;
}
/// <summary>
/// Returns a trace of the stack in the moment the exception was thrown.
/// </summary>
/// <returns>The trace.</returns>
[ImplementsMethod]
public object getTrace(ScriptContext context)
{
return trace.Value;
}
/// <summary>
/// Returns a trace formatted in a form of a string.
/// </summary>
/// <returns>The formatted trace.</returns>
[ImplementsMethod]
public object getTraceAsString(ScriptContext context)
{
if (stringTraceCache == null)
{
PhpArray array = trace.Value as PhpArray;
stringTraceCache = (array != null) ? PhpStackTrace.FormatUserTrace(array) : String.Empty;
}
return stringTraceCache;
}
#endregion
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{
typeDesc.AddMethod("__construct", PhpMemberAttributes.Public, __construct);
typeDesc.AddMethod("__toString", PhpMemberAttributes.Public, __toString);
typeDesc.AddMethod("getMessage", PhpMemberAttributes.Public, getMessage);
typeDesc.AddMethod("getCode", PhpMemberAttributes.Public, getCode);
typeDesc.AddMethod("getFile", PhpMemberAttributes.Public, getFile);
typeDesc.AddMethod("getTrace", PhpMemberAttributes.Public, getTrace);
typeDesc.AddMethod("getPrevious", PhpMemberAttributes.Public, getPrevious);
typeDesc.AddMethod("getTraceAsString", PhpMemberAttributes.Public, getTraceAsString);
typeDesc.AddMethod("getLine", PhpMemberAttributes.Public, getLine);
typeDesc.AddMethod("getColumn", PhpMemberAttributes.Public, getColumn);
typeDesc.AddProperty("message", PhpMemberAttributes.Protected, __get_message, __set_message);
typeDesc.AddProperty("code", PhpMemberAttributes.Protected, __get_code, __set_code);
typeDesc.AddProperty("file", PhpMemberAttributes.Protected, __get_file, __set_file);
typeDesc.AddProperty("line", PhpMemberAttributes.Protected, __get_line, __set_line);
typeDesc.AddProperty("column", PhpMemberAttributes.Protected, __get_column, __set_column);
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public Exception(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public Exception(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object __construct(object instance, PhpStack stack)
{
object message = stack.PeekValueOptional(1);
object code = stack.PeekValueOptional(2);
object previous = stack.PeekValueOptional(3);
stack.RemoveFrame();
return ((Exception)instance).__construct(stack.Context, message, code, previous);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object __toString(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).__toString(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getMessage(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getMessage(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getPrevious(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getPrevious(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getTrace(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getTrace(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getCode(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getCode(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getFile(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getFile(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getLine(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getLine(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getColumn(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getColumn(stack.Context);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getTraceAsString(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((Exception)instance).getTraceAsString(stack.Context);
}
private static object __get_message(object instance) { return ((Exception)instance).message; }
private static void __set_message(object instance, object value) { ((Exception)instance).message = (PhpReference)value; }
private static object __get_code(object instance) { return ((Exception)instance).code; }
private static void __set_code(object instance, object value) { ((Exception)instance).code = (PhpReference)value; }
private static object __get_file(object instance) { return ((Exception)instance).file; }
private static void __set_file(object instance, object value) { ((Exception)instance).file = (PhpReference)value; }
private static object __get_line(object instance) { return ((Exception)instance).line; }
private static void __set_line(object instance, object value) { ((Exception)instance).line = (PhpReference)value; }
private static object __get_column(object instance) { return ((Exception)instance).column; }
private static void __set_column(object instance, object value) { ((Exception)instance).column = (PhpReference)value; }
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected Exception(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if an error which can only be found on runtime occurs.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class RuntimeException : Exception
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public RuntimeException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public RuntimeException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected RuntimeException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// An Error Exception.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class ErrorException : Exception
{
private int severity;
#region __construct, getSeverity
[ImplementsMethod]
public object __construct(ScriptContext/*!*/context,
[Optional]object message /*""*/, [Optional]object code /*0*/, [Optional]object severity /*1*/,
[Optional]object filename /*__FILE__*/, [Optional]object lineno /*__LINE__*/,
[Optional]object previous /*NULL*/ )
{
base.__construct(context, message, code, previous);
this.severity = (severity == Arg.Default) ? 1 : PHP.Core.Convert.ObjectToInteger(severity);
if (filename != Arg.Default) this.file.Value = PHP.Core.Convert.ObjectToString(filename);
if (lineno != Arg.Default) this.line.Value = PHP.Core.Convert.ObjectToInteger(filename);
return null;
}
/// <summary>
/// Returns the severity of the exception.
/// </summary>
[ImplementsMethod]
public object getSeverity(ScriptContext/*!*/context)
{
return this.severity;
}
#endregion
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{
throw new NotImplementedException();
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public ErrorException (ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public ErrorException (ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static new object __construct(object instance, PhpStack stack)
{
object message = stack.PeekValueOptional(1);
object code = stack.PeekValueOptional(2);
object severity = stack.PeekValueOptional(3);
object filename = stack.PeekValueOptional(4);
object lineno = stack.PeekValueOptional(5);
object previous = stack.PeekValueOptional(6);
stack.RemoveFrame();
return ((ErrorException)instance).__construct(stack.Context, message, code, severity, filename, lineno, previous);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getSeverity(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((ErrorException)instance).getSeverity(stack.Context);
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected ErrorException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception that represents error in the program logic.
/// This kind of exceptions should directly lead to a fix in your code.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class LogicException : Exception
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public LogicException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public LogicException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected LogicException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if an argument does not match with the expected value.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class InvalidArgumentException : LogicException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public InvalidArgumentException (ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public InvalidArgumentException (ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected InvalidArgumentException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown when an illegal index was requested.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class OutOfRangeException : LogicException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OutOfRangeException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OutOfRangeException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
}
/// <summary>
/// Exception thrown if a callback refers to an undefined function or if some arguments are missing.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class BadFunctionCallException : LogicException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public BadFunctionCallException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public BadFunctionCallException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected BadFunctionCallException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if a callback refers to an undefined method or if some arguments are missing.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class BadMethodCallException : BadFunctionCallException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public BadMethodCallException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public BadMethodCallException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected BadMethodCallException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if a length is invalid.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class LengthException : LogicException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public LengthException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public LengthException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected LengthException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown to indicate range errors during program execution.
/// Normally this means there was an arithmetic error other than under/overflow.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class RangeException : RuntimeException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public RangeException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public RangeException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected RangeException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if a value is not a valid key.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class OutOfBoundsException : RuntimeException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OutOfBoundsException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OutOfBoundsException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
}
/// <summary>
/// Exception thrown when adding an element to a full container.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class OverflowException : RuntimeException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OverflowException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public OverflowException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected OverflowException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown when performing an invalid operation on an empty container,
/// such as removing an element.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class UnderflowException : RuntimeException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public UnderflowException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public UnderflowException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected UnderflowException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if a value does not match with a set of values.
/// Typically this happens when a function calls another function and expects the return value
/// to be of a certain type or value not including arithmetic or buffer related errors.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class UnexpectedValueException : RuntimeException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ throw new NotImplementedException(); }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public UnexpectedValueException (ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public UnexpectedValueException (ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected UnexpectedValueException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
/// <summary>
/// Exception thrown if a value does not adhere to a defined valid data domain.
/// </summary>
[ImplementsType]
#if !SILVERLIGHT
[Serializable]
#endif
public class DomainException : LogicException
{
#region Implementation Details
/// <summary>
/// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties.
/// </summary>
/// <param name="typeDesc">The type desc to populate.</param>
internal static new void __PopulateTypeDesc(PhpTypeDesc typeDesc)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public DomainException(ScriptContext context, bool newInstance)
: base(context, newInstance)
{
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public DomainException(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Deserializing constructor.
/// </summary>
protected DomainException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
#endregion
}
}
| |
namespace Ioke.Lang {
using System;
using System.Collections;
using System.Collections.Generic;
using Ioke.Math;
using Ioke.Lang.Util;
public class Number : IokeData {
readonly RatNum value;
readonly bool kind;
public Number(RatNum value) {
this.value = value;
kind = false;
}
private Number() {
this.value = IntNum.make(0);
kind = true;
}
public static IntNum GetFrom(long nativeNumber) {
return IntNum.make(nativeNumber);
}
public static IntNum GetFrom(string textRepresentation) {
if(textRepresentation.StartsWith("0x") || textRepresentation.StartsWith("0X")) {
return IntNum.valueOf(textRepresentation.Substring(2), 16);
} else {
return IntNum.valueOf(textRepresentation);
}
}
public RatNum Value {
get { return value; }
}
public static RatNum GetValue(object number) {
return ((Number)IokeObject.dataOf(number)).value;
}
public static Number Integer(string val) {
return new Number(GetFrom(val));
}
public static Number Integer(long val) {
return new Number(GetFrom(val));
}
public static Number Integer(IntNum val) {
return new Number(val);
}
public static Number Ratio(IntFraction val) {
return new Number(val);
}
public int AsNativeInteger() {
return value.intValue();
}
public string AsNativeString() {
return value.ToString();
}
public long AsNativeLong() {
return value.longValue();
}
public override string ToString() {
return AsNativeString();
}
public override string ToString(IokeObject obj) {
return AsNativeString();
}
public static IntNum IntValue(object number) {
return (IntNum)((Number)IokeObject.dataOf(number)).value;
}
public static int ExtractInt(object number, IokeObject m, IokeObject context) {
if(!(IokeObject.dataOf(number) is Number)) {
number = IokeObject.ConvertToNumber(number, m, context);
}
return IntValue(number).intValue();
}
public override IokeObject ConvertToNumber(IokeObject self, IokeObject m, IokeObject context) {
return self;
}
public override IokeObject ConvertToRational(IokeObject self, IokeObject m, IokeObject context, bool signalCondition) {
return self;
}
public override IokeObject ConvertToDecimal(IokeObject self, IokeObject m, IokeObject context, bool signalCondition) {
return context.runtime.NewDecimal(this);
}
public override void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
IokeObject number = obj;
obj.Kind = "Number";
obj.Mimics(IokeObject.As(runtime.Mixins.GetCell(null, null, "Comparing"), obj), runtime.nul, runtime.nul);
IokeObject real = new IokeObject(runtime, "A real number can be either a rational number or a decimal number", new Number());
real.MimicsWithoutCheck(number);
real.Kind = "Number Real";
number.RegisterCell("Real", real);
IokeObject rational = new IokeObject(runtime, "A rational number is either an integer or a ratio", new Number());
rational.MimicsWithoutCheck(real);
rational.Kind = "Number Rational";
number.RegisterCell("Rational", rational);
IokeObject integer = new IokeObject(runtime, "An integral number", new Number());
integer.MimicsWithoutCheck(rational);
integer.Kind = "Number Integer";
number.RegisterCell("Integer", integer);
runtime.Integer = integer;
IokeObject ratio = new IokeObject(runtime, "A ratio of two integral numbers", new Number());
ratio.MimicsWithoutCheck(rational);
ratio.Kind = "Number Ratio";
number.RegisterCell("Ratio", ratio);
runtime.Ratio = ratio;
IokeObject _decimal = new IokeObject(runtime, "An exact, unlimited representation of a decimal number", new Decimal(BigDecimal.ZERO));
_decimal.MimicsWithoutCheck(real);
_decimal.Init();
number.RegisterCell("Decimal", _decimal);
IokeObject infinity = new IokeObject(runtime, "A value representing infinity", new Number(RatNum.infinity(1)));
infinity.MimicsWithoutCheck(ratio);
infinity.Kind = "Number Infinity";
number.RegisterCell("Infinity", infinity);
runtime.Infinity = infinity;
number.RegisterMethod(runtime.NewNativeMethod("returns a hash for the number",
new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
return context.runtime.NewNumber(Number.GetValue(on).GetHashCode());
})));
number.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side number is equal to the right hand side number.",
new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(runtime.Number)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
Number d = (Number)IokeObject.dataOf(on);
object other = args[0];
return ((other is IokeObject) &&
(IokeObject.dataOf(other) is Number)
&& (((d.kind || ((Number)IokeObject.dataOf(other)).kind) ? on == other :
d.value.Equals(((Number)IokeObject.dataOf(other)).value)))) ? context.runtime.True : context.runtime.False;
})));
rational.RegisterMethod(runtime.NewNativeMethod("compares this number against the argument, returning -1, 0 or 1 based on which one is larger. if the argument is a decimal, the receiver will be converted into a form suitable for comparing against a decimal, and then compared - it's not specified whether this will actually call Decimal#<=> or not. if the argument is neither a Rational nor a Decimal, it tries to call asRational, and if that doesn't work it returns nil.",
new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(rational)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Decimal) {
return context.runtime.NewNumber(new BigDecimal(Number.GetValue(on).longValue()).CompareTo(Decimal.GetValue(arg)));
} else {
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, false);
if(!(IokeObject.dataOf(arg) is Number)) {
// Can't compare, so bail out
return context.runtime.nil;
}
}
if(on == rational || arg == rational || on == integer || arg == integer || on == ratio || arg == ratio) {
if(arg == on) {
return context.runtime.NewNumber(0);
}
return context.runtime.nil;
}
return context.runtime.NewNumber(IntNum.compare(Number.GetValue(on),Number.GetValue(arg)));
}
})));
number.RegisterMethod(runtime.NewNativeMethod("compares this against the argument. should be overridden - in this case only used to check for equivalent number kinds",
new NativeMethod("==", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("other")
.Arguments,
(method, context, message, on, outer) => {
IList args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
object arg = args[0];
if(on == arg) {
return context.runtime.True;
} else {
return context.runtime.False;
}
})));
rational.RegisterMethod(runtime.NewNativeMethod("compares this number against the argument, true if this number is the same, otherwise false",
new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(number)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
if(on == rational || arg == rational || on == integer || arg == integer || on == ratio || arg == ratio || on == infinity || arg == infinity) {
if(arg == on) {
return context.runtime.True;
}
return context.runtime.False;
}
if(IokeObject.dataOf(arg) is Decimal) {
return (new BigDecimal(Number.GetValue(on).longValue()).CompareTo(Decimal.GetValue(arg)) == 0) ? context.runtime.True : context.runtime.False;
} else if(IokeObject.dataOf(arg) is Number) {
return IntNum.compare(Number.GetValue(on),Number.GetValue(arg)) == 0 ? context.runtime.True : context.runtime.False;
} else {
return context.runtime.False;
}
})));
rational.RegisterMethod(runtime.NewNativeMethod("returns the difference between this number and the argument. if the argument is a decimal, the receiver will be converted into a form suitable for subtracting against a decimal, and then subtracted. if the argument is neither a Rational nor a Decimal, it tries to call asRational, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("-", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(number)
.WithRequiredPositional("subtrahend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Decimal) {
return ((Message)IokeObject.dataOf(context.runtime.minusMessage)).SendTo(context.runtime.minusMessage, context, context.runtime.NewDecimal(((Number)IokeObject.dataOf(on))), arg);
} else {
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber((RatNum)Number.GetValue(on).sub(Number.GetValue(arg)));
}
})));
integer.RegisterMethod(runtime.NewNativeMethod("Returns the successor of this number", new TypeCheckingNativeMethod.WithNoArguments("succ", integer,
(method, on, args, keywords, context, message) => {
return runtime.NewNumber(IntNum.add(Number.IntValue(on),IntNum.one()));
})));
integer.RegisterMethod(runtime.NewNativeMethod("Returns the predecessor of this number", new TypeCheckingNativeMethod.WithNoArguments("pred", integer,
(method, on, args, keywords, context, message) => {
return runtime.NewNumber(IntNum.sub(Number.IntValue(on),IntNum.one()));
})));
infinity.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", infinity,
(method, on, args, keywords, context, message) => {
return runtime.NewText("Infinity");
})));
infinity.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", infinity,
(method, on, args, keywords, context, message) => {
return runtime.NewText("Infinity");
})));
rational.RegisterMethod(runtime.NewNativeMethod("returns the addition of this number and the argument. if the argument is a decimal, the receiver will be converted into a form suitable for addition against a decimal, and then added. if the argument is neither a Rational nor a Decimal, it tries to call asRational, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("+", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(number)
.WithRequiredPositional("addend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Decimal) {
return ((Message)IokeObject.dataOf(context.runtime.plusMessage)).SendTo(context.runtime.plusMessage, context, context.runtime.NewDecimal(((Number)IokeObject.dataOf(on))), arg);
} else {
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(RatNum.add(Number.GetValue(on),Number.GetValue(arg),1));
}
})));
rational.RegisterMethod(runtime.NewNativeMethod("returns the product of this number and the argument. if the argument is a decimal, the receiver will be converted into a form suitable for multiplying against a decimal, and then multiplied. if the argument is neither a Rational nor a Decimal, it tries to call asRational, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("*", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(number)
.WithRequiredPositional("multiplier")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Decimal) {
return ((Message)IokeObject.dataOf(context.runtime.multMessage)).SendTo(context.runtime.multMessage, context, context.runtime.NewDecimal(((Number)IokeObject.dataOf(on))), arg);
} else {
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(RatNum.times(Number.GetValue(on),Number.GetValue(arg)));
}
})));
rational.RegisterMethod(runtime.NewNativeMethod("returns the quotient of this number and the argument. if the division is not exact, it will return a Ratio.",
new TypeCheckingNativeMethod("/", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(number)
.WithRequiredPositional("dividend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Decimal) {
return ((Message)IokeObject.dataOf(context.runtime.divMessage)).SendTo(context.runtime.divMessage, context, context.runtime.NewDecimal(((Number)IokeObject.dataOf(on))), arg);
} else {
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
while(Number.GetValue(arg).isZero()) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Arithmetic",
"DivisionByZero"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
object[] newCell = new object[]{arg};
context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);},
context,
new IokeObject.UseValue("dividend", newCell));
arg = newCell[0];
}
return context.runtime.NewNumber(RatNum.divide(Number.GetValue(on),Number.GetValue(arg)));
}
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns the modulo of this number and the argument",
new TypeCheckingNativeMethod("%", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("dividend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(IntNum.modulo(Number.IntValue(on),Number.IntValue(arg)));
})));
rational.RegisterMethod(runtime.NewNativeMethod("returns this number to the power of the argument",
new TypeCheckingNativeMethod("**", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(rational)
.WithRequiredPositional("exponent")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber((RatNum)Number.GetValue(on).power(Number.IntValue(arg)));
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns this number bitwise and the argument",
new TypeCheckingNativeMethod("&", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(BitOps.and(Number.IntValue(on), Number.IntValue(arg)));
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns this number bitwise or the argument",
new TypeCheckingNativeMethod("|", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(BitOps.ior(Number.IntValue(on), Number.IntValue(arg)));
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns this number bitwise xor the argument",
new TypeCheckingNativeMethod("^", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(BitOps.xor(Number.IntValue(on), Number.IntValue(arg)));
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns this number left shifted by the argument",
new TypeCheckingNativeMethod("<<", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(IntNum.shift(Number.IntValue(on), Number.IntValue(arg).intValue()));
})));
integer.RegisterMethod(runtime.NewNativeMethod("returns this number right shifted by the argument",
new TypeCheckingNativeMethod(">>", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(integer)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewNumber(IntNum.shift(Number.IntValue(on), -Number.IntValue(arg).intValue()));
})));
rational.RegisterMethod(runtime.NewNativeMethod("Returns a text representation of the object",
new TypeCheckingNativeMethod.WithNoArguments("asText", number,
(method, on, args, keywords, context, message) => {
return runtime.NewText(on.ToString());
})));
rational.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", number,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(Number.GetInspect(on));
})));
rational.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", number,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(Number.GetInspect(on));
})));
integer.RegisterMethod(runtime.NewNativeMethod("Expects one or two arguments. If one argument is given, executes it as many times as the value of the receiving number. If two arguments are given, the first will be an unevaluated name that will receive the current loop value on each repitition. the iteration length is limited to the positive maximum of a Java int",
new NativeMethod("times", DefaultArgumentsDefinition.builder()
.WithRequiredPositionalUnevaluated("argumentNameOrCode")
.WithOptionalPositionalUnevaluated("code")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
int num = Number.GetValue(context.runtime.Integer.ConvertToThis(on, message, context)).intValue();
if(message.Arguments.Count == 0) {
return runtime.nil;
} else if(message.Arguments.Count == 1) {
object result = runtime.nil;
while(num > 0) {
result = ((Message)IokeObject.dataOf(message)).GetEvaluatedArgument(message, 0, context);
num--;
}
return result;
} else {
int ix = 0;
string name = ((IokeObject)Message.GetArguments(message)[0]).Name;
object result = runtime.nil;
while(ix<num) {
context.SetCell(name, runtime.NewNumber(IntNum.make(ix)));
result = ((Message)IokeObject.dataOf(message)).GetEvaluatedArgument(message, 1, context);
ix++;
}
return result;
}
})));
}
public static string GetInspect(object on) {
return ((Number)(IokeObject.dataOf(on))).Inspect(on);
}
public string Inspect(object obj) {
return AsNativeString();
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using Alachisoft.NCache.Caching.Statistics;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Caching.Util;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.Common.DataStructures;
using System.Collections.Generic;
using Alachisoft.NCache.Persistence;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Events;
using Alachisoft.NCache.Caching.Messaging;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Common.Locking;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Common.Resources;
using Alachisoft.NCache.Runtime.Events;
using EventType = Alachisoft.NCache.Persistence.EventType;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Caching.Pooling;
using Alachisoft.NCache.Common.ErrorHandling;
namespace Alachisoft.NCache.Caching.Topologies.Local
{
internal class LocalCacheImpl : CacheBase, ICacheEventsListener
{
/// <summary> The en-wrapped instance of cache. </summary>
private CacheBase _cache;
public LocalCacheImpl() { }
public LocalCacheImpl(CacheRuntimeContext context)
{
_context = context;
}
/// <summary>
/// Default constructor.
/// </summary>
public LocalCacheImpl(CacheBase cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
_cache = cache;
_context = cache.InternalCache.Context;
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
if (_cache != null)
{
_cache.Dispose();
_cache = null;
}
base.Dispose();
}
#endregion
/// <summary>
/// get/set listener of Cache events. 'null' implies no listener.
/// </summary>
public CacheBase Internal
{
get { return _cache; }
set
{
_cache = value;
_context = value.InternalCache.Context;
}
}
/// <summary>
/// Returns the cache local to the node, i.e., internal cache.
/// </summary>
protected internal override CacheBase InternalCache
{
get { return _cache; }
}
public override TypeInfoMap TypeInfoMap
{
get
{
return _cache.TypeInfoMap;
}
}
/// <summary>
/// get/set the name of the cache.
/// </summary>
public override string Name
{
get { return Internal.Name; }
set { Internal.Name = value; }
}
/// <summary>
/// get/set listener of Cache events. 'null' implies no listener.
/// </summary>
public override ICacheEventsListener Listener
{
get { return Internal.Listener; }
set { Internal.Listener = value; }
}
/// <summary>
/// Notifications are enabled.
/// </summary>
public override Notifications Notifiers
{
get { return Internal.Notifiers; }
set { Internal.Notifiers = value; }
}
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public override long Count
{
get
{
return Internal.Count;
}
}
/// <summary>
/// returns the statistics of the Clustered Cache.
/// </summary>
public override CacheStatistics Statistics
{
get
{
return Internal.Statistics;
}
}
/// <summary>
/// returns the statistics of the Clustered Cache.
/// </summary>
internal override CacheStatistics ActualStats
{
get
{
return Internal.ActualStats;
}
}
#region / --- ICache --- /
/// Removes all entries from the store.
/// </summary>
public override void Clear(Caching.Notifications notification, DataSourceUpdateOptions updateOptions, OperationContext operationContext)
{
Internal.Clear(notification, updateOptions, operationContext);
}
/// <summary>
/// Determines whether the cache contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the cache.</param>
/// <returns>true if the cache contains an element
/// with the specified key; otherwise, false.</returns>
public override bool Contains(object key, OperationContext operationContext)
{
return Internal.Contains(key, operationContext);
}
/// <summary>
/// Determines whether the cache contains the specified keys.
/// </summary>
/// <param name="keys">The keys to locate in the cache.</param>
/// <returns>list of existing keys.</returns>
public override Hashtable Contains(IList keys, OperationContext operationContext)
{
return Internal.Contains(keys, operationContext);
}
/// <summary>
/// Retrieve the object from the cache. A string key is passed as parameter.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <returns>cache entry.</returns>
public override CacheEntry Get(object key, ref ulong version, ref object lockId, ref DateTime lockDate, LockExpiration lockExpiration, LockAccessType accessType, OperationContext operationContext)
{
CacheEntry entry = Internal.Get(key, ref version, ref lockId, ref lockDate, lockExpiration, accessType, operationContext);
if (entry != null && KeepDeflattedValues)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
return entry;
}
public override HashVector GetTagData(string[] tags, TagComparisonType comparisonType, OperationContext operationContext)
{
return Internal.GetTagData(tags, comparisonType, operationContext);
}
public override Hashtable Remove(string[] tags, TagComparisonType tagComparisonType, bool notify, OperationContext operationContext)
{
return Internal.Remove(tags, tagComparisonType, notify, operationContext);
}
internal override ICollection GetTagKeys(string[] tags, TagComparisonType comparisonType, OperationContext operationContext)
{
return Internal.GetTagKeys(tags, comparisonType, operationContext);
}
public override IDictionary GetEntryAttributeValues(object key, IList<string> columns, OperationContext operationContext)
{
return Internal.GetEntryAttributeValues(key, columns, operationContext);
}
/// <summary>
/// Retrieve the objects from the cache. An array of keys is passed as parameter.
/// </summary>
/// <param name="key">keys of the entries.</param>
/// <returns>cache entries.</returns>
public override IDictionary Get(object[] keys, OperationContext operationContext)
{
HashVector data = (HashVector)Internal.Get(keys, operationContext);
if (data != null && KeepDeflattedValues)
{
IDictionaryEnumerator ide = data.GetEnumerator();
CacheEntry entry;
while (ide.MoveNext())
{
if (operationContext.CancellationToken != null && operationContext.CancellationToken.IsCancellationRequested)
throw new OperationCanceledException(ExceptionsResource.OperationFailed);
entry = ide.Value as CacheEntry;
if (entry != null)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
}
}
return data;
}
public override PollingResult Poll(OperationContext operationContext)
{
return Internal.Poll(operationContext);
}
/// <summary>
/// Retrieve the keys from the cache.
/// </summary>
/// <param name="keys">keys of the entries.</param>
/// <returns>list of keys.</returns>
public override ArrayList GetGroupKeys(string group, string subGroup, OperationContext operationContext)
{
return Internal.GetGroupKeys(group, subGroup, operationContext);
}
/// <summary>
/// Retrieve the keys from the cache.
/// </summary>
/// <param name="keys">keys of the entries.</param>
/// <returns>list of keys.</returns>
public override CacheEntry GetGroup(object key, string group, string subGroup, ref ulong version, ref object lockId, ref DateTime lockDate, LockExpiration lockExpiration, LockAccessType accessType, OperationContext operationContext)
{
if (!IsCacheOperationAllowed(operationContext))
return null;
CacheEntry entry = Internal.GetGroup(key, group, subGroup, ref version, ref lockId, ref lockDate, lockExpiration, accessType, operationContext);
if (entry != null && KeepDeflattedValues)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
return entry;
}
/// <summary>
/// Gets the data group information of the item.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public override Alachisoft.NCache.Caching.DataGrouping.GroupInfo GetGroupInfo(object key, OperationContext operationContext)
{
return Internal.GetGroupInfo(key, operationContext);
}
/// <summary>
/// Gets the data groups of the items.
/// </summary>
/// <param name="keys">Keys of the items</param>
/// <returns>Hashtable containing key of the item as 'key' and GroupInfo as 'value'</returns>
public override Hashtable GetGroupInfoBulk(object[] keys, OperationContext operationContext)
{
return Internal.GetGroupInfoBulk(keys, operationContext);
}
/// <summary>
/// Retrieve the keys from the cache.
/// </summary>
/// <param name="keys">keys of the entries.</param>
/// <returns>key and value pairs.</returns>
public override HashVector GetGroupData(string group, string subGroup, OperationContext operationContext)
{
HashVector data = Internal.GetGroupData(group, subGroup, operationContext);
if (data != null && KeepDeflattedValues)
{
IDictionaryEnumerator ide = data.GetEnumerator();
CacheEntry entry;
while (ide.MoveNext())
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
}
}
return data;
}
/// <summary>
/// Gets/sets the list of data groups contained in the cache.
/// </summary>
public override ArrayList DataGroupList
{
get
{
return Internal.DataGroupList;
}
}
/// <summary>
/// Adds a pair of key and value to the cache. Throws an exception or reports error
/// if the specified key already exists in the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
public override CacheAddResult Add(object key, CacheEntry cacheEntry, bool notify, OperationContext operationContext)
{
try
{
if (cacheEntry != null)
cacheEntry.MarkInUse(NCModulesConstants.CacheImpl);
operationContext?.MarkInUse(NCModulesConstants.CacheImpl);
CacheAddResult result = CacheAddResult.Failure;
if (Internal != null)
{
#region -- PART I -- Cascading Dependency Operation
object[] keys = cacheEntry.KeysIAmDependingOn;
if (keys != null)
{
Hashtable goodKeysTable = Contains(keys, operationContext);
if (!goodKeysTable.ContainsKey("items-found"))
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (goodKeysTable["items-found"] == null)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (goodKeysTable["items-found"] == null || (((ArrayList)goodKeysTable["items-found"]).Count != keys.Length))
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
}
#endregion
result = Internal.Add(key, cacheEntry, notify, operationContext);
#region -- PART II -- Cascading Dependency Operation
KeyDependencyInfo[] keyDepInfos = cacheEntry.KeysIAmDependingOnWithDependencyInfo;
if (result == CacheAddResult.Success && keyDepInfos != null)
{
Hashtable keyDepInfoTable = new Hashtable();
foreach (KeyDependencyInfo keyDepInfo in keyDepInfos)
{
if (keyDepInfoTable[keyDepInfo.Key] == null)
{
keyDepInfoTable.Add(keyDepInfo.Key, new ArrayList());
}
((ArrayList)keyDepInfoTable[keyDepInfo.Key]).Add(new KeyDependencyInfo(key.ToString()));
}
object generateQueryInfo = operationContext.GetValueByField(OperationContextFieldName.GenerateQueryInfo);
if (generateQueryInfo == null)
{
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
}
#region OLD KEY DEPENDENCY CODE
// Internal.AddDepKeyList(table, operationContext);
#endregion
Internal.AddDepKeyList(keyDepInfoTable, operationContext);
if (generateQueryInfo == null)
{
operationContext.RemoveValueByField(OperationContextFieldName.GenerateQueryInfo);
}
}
#endregion
}
return result;
}
finally
{
if (cacheEntry != null)
cacheEntry.MarkFree(NCModulesConstants.CacheImpl);
operationContext?.MarkFree(NCModulesConstants.CacheImpl);
}
}
/// <summary>
/// Add ExpirationHint against the given key
/// Key must already exists in the cache
/// </summary>
/// <param name="key"></param>
/// <param name="eh"></param>
/// <returns></returns>
public override bool Add(object key, ExpirationHint eh, OperationContext operationContext)
{
CacheEntry cacheEntry = null;
try
{
bool result = false;
if (Internal != null)
{
#region -- PART I -- Cascading Dependency Operation
cacheEntry = CacheEntry.CreateCacheEntry(Context.TransactionalPoolManager);
cacheEntry.ExpirationHint = eh;
cacheEntry.MarkInUse(NCModulesConstants.CacheImpl);
object[] keys = cacheEntry.KeysIAmDependingOn;
if (keys != null)
{
Hashtable goodKeysTable = Contains(keys, operationContext);
if (!goodKeysTable.ContainsKey("items-found"))
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (goodKeysTable["items-found"] == null)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (((ArrayList)goodKeysTable["items-found"]).Count != keys.Length)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
}
#endregion
result = Internal.Add(key, eh, operationContext);
#region -- PART II -- Cascading Dependency Operation
KeyDependencyInfo[] keyDepInfos = cacheEntry.KeysIAmDependingOnWithDependencyInfo;
if (result && keyDepInfos != null)
{
Hashtable keyDepInfoTable = new Hashtable();
foreach (KeyDependencyInfo keyDepInfo in keyDepInfos)
{
if (keyDepInfoTable[keyDepInfo.Key] == null)
{
keyDepInfoTable.Add(keyDepInfo.Key, new ArrayList());
}
((ArrayList)keyDepInfoTable[keyDepInfo.Key]).Add(new KeyDependencyInfo(key.ToString()));
}
try
{
#region OLD KEY DEPENDENCY CODE
#endregion
keyDepInfoTable = Internal.AddDepKeyList(keyDepInfoTable, operationContext);
}
catch (Exception e)
{
throw e;
}
#region OLD KEY DEPENDENCY CODE
// if (table != null)
#endregion
if (keyDepInfoTable != null)
{
#region OLD KEY DEPENDENCY CODE
#endregion
IDictionaryEnumerator en = keyDepInfoTable.GetEnumerator();
while (en.MoveNext())
{
if (en.Value is bool && !((bool)en.Value))
{
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
}
}
}
}
#endregion
}
return result;
}
finally
{
if (cacheEntry != null)
{
MiscUtil.ReturnEntryToPool(cacheEntry, Context.TransactionalPoolManager);
cacheEntry.MarkFree(NCModulesConstants.CacheImpl);
}
}
}
public override bool Add(object key, OperationContext operationContext)
{
return Internal.Add(key, operationContext);
}
/// <summary>
/// Adds key and value pairs to the cache. Throws an exception or returns the
/// list of keys that already exists in the cache.
/// </summary>
/// <param name="keys">key of the entry.</param>
/// <param name="cacheEntries">the cache entry.</param>
/// <returns>List of keys that are added or that alredy exists in the cache and their status</returns>
public override Hashtable Add(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
{
Hashtable table = new Hashtable();
ArrayList goodKeysList = new ArrayList();
ArrayList badKeysList = new ArrayList();
ArrayList goodEntriesList = new ArrayList();
CacheEntry[] goodEntries = null;
try
{
if (cacheEntries != null)
cacheEntries.MarkInUse(NCModulesConstants.CacheImpl);
if (Internal != null)
{
#region -- PART I -- Cascading Dependency Operation
for (int i = 0; i < cacheEntries.Length; i++)
{
object[] tempKeys = cacheEntries[i].KeysIAmDependingOn;
if (tempKeys != null)
{
Hashtable goodKeysTable = Contains(tempKeys, operationContext);
if (goodKeysTable.ContainsKey("items-found") && goodKeysTable["items-found"] != null && tempKeys.Length == ((ArrayList)goodKeysTable["items-found"]).Count)
{
goodKeysList.Add(keys[i]);
goodEntriesList.Add(cacheEntries[i]);
}
else
{
badKeysList.Add(keys[i]);
}
}
else
{
goodKeysList.Add(keys[i]);
goodEntriesList.Add(cacheEntries[i]);
}
}
#endregion
goodEntries = new CacheEntry[goodEntriesList.Count];
goodEntriesList.CopyTo(goodEntries);
table = Internal.Add(goodKeysList.ToArray(), goodEntries, notify, operationContext);
#region --Part II-- Cascading Dependency Operations
object generateQueryInfo = operationContext.GetValueByField(OperationContextFieldName.GenerateQueryInfo);
if (generateQueryInfo == null)
{
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
}
for (int i = 0; i < goodKeysList.Count; i++)
{
if (operationContext.CancellationToken != null && operationContext.CancellationToken.IsCancellationRequested)
throw new OperationCanceledException(ExceptionsResource.OperationFailed);
if (table[goodKeysList[i]] is Exception)
continue;
CacheAddResult retVal = (CacheAddResult)table[goodKeysList[i]];
KeyDependencyInfo[] keyDepInfos = goodEntries[i].KeysIAmDependingOnWithDependencyInfo;
if (retVal == CacheAddResult.Success && keyDepInfos != null)
{
Hashtable keyDepInfoTable = new Hashtable();
foreach (KeyDependencyInfo keyDepInfo in keyDepInfos)
{
if (keyDepInfoTable[keyDepInfo.Key] == null)
{
keyDepInfoTable.Add(keyDepInfo.Key, new ArrayList());
}
((ArrayList)keyDepInfoTable[keyDepInfo.Key]).Add(new KeyDependencyInfo(goodKeysList[i].ToString()));
}
Internal.AddDepKeyList(keyDepInfoTable, operationContext);
}
}
if (generateQueryInfo == null)
{
operationContext.RemoveValueByField(OperationContextFieldName.GenerateQueryInfo);
}
for (int i = 0; i < badKeysList.Count; i++)
{
table.Add(badKeysList[i], new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND)));
}
#endregion
}
return table;
}
finally
{
if (cacheEntries != null)
cacheEntries.MarkFree(NCModulesConstants.CacheImpl);
if (goodEntries != null)
goodEntries.MarkFree(NCModulesConstants.CacheImpl);
}
}
/// <summary>
/// Adds a pair of key and value to the cache. If the specified key already exists
/// in the cache; it is updated, otherwise a new item is added to the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
public override CacheInsResultWithEntry Insert(object key, CacheEntry cacheEntry, bool notify, object lockId, ulong version, LockAccessType accessType, OperationContext operationContext)
{
try
{
if (cacheEntry != null)
cacheEntry.MarkInUse(NCModulesConstants.CacheImpl);
operationContext?.MarkInUse(NCModulesConstants.LocalCache);
CacheInsResultWithEntry retVal = null;
if (Internal != null)
{
#region -- PART I -- Cascading Dependency Operation
object[] dependingKeys = cacheEntry.KeysIAmDependingOn;
if (dependingKeys != null)
{
Hashtable goodKeysTable = Contains(dependingKeys, operationContext);
if (!goodKeysTable.ContainsKey("items-found"))
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (goodKeysTable["items-found"] == null)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (dependingKeys.Length != ((ArrayList)goodKeysTable["items-found"]).Count)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
}
#endregion
retVal = Internal.Insert(key, cacheEntry, notify, lockId, version, accessType, operationContext);
if (retVal == null) retVal = retVal = CacheInsResultWithEntry.CreateCacheInsResultWithEntry(_context.TransactionalPoolManager);
#region -- PART II -- Cascading Dependency Operation
if (retVal.Result == CacheInsResult.Success || retVal.Result == CacheInsResult.SuccessOverwrite)
{
#region OLD KEY DEPENDENCY CODE
// Hashtable table = null;
#endregion
Hashtable keyDepInfosTable = null;
object generateQueryInfo = operationContext.GetValueByField(OperationContextFieldName.GenerateQueryInfo);
if (generateQueryInfo == null)
{
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
}
if (generateQueryInfo == null)
{
operationContext.RemoveValueByField(OperationContextFieldName.GenerateQueryInfo);
}
}
#endregion
}
return retVal;
}
finally
{
if (cacheEntry != null)
cacheEntry.MarkFree(NCModulesConstants.CacheImpl);
}
}
/// <summary>
/// Adds key and value pairs to the cache. If any of the specified key already exists
/// in the cache; it is updated, otherwise a new item is added to the cache.
/// </summary>
/// <param name="keys">keys of the entries.</param>
/// <param name="cacheEntries">the cache entries.</param>
/// <returns>returns the results for inserted keys</returns>
public override Hashtable Insert(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
{
Hashtable retVal = null;
ArrayList goodKeysList = new ArrayList();
ArrayList goodEntriesList = new ArrayList();
ArrayList badKeysList = new ArrayList();
CacheEntry[] goodEntries = null;
try
{
if (cacheEntries != null)
cacheEntries.MarkInUse(NCModulesConstants.CacheImpl);
if (Internal != null)
{
#region -- PART I -- Cascading Dependency Operation
for (int i = 0; i < cacheEntries.Length; i++)
{
object[] tempKeys = cacheEntries[i].KeysIAmDependingOn;
if (tempKeys != null)
{
Hashtable goodKeysTable = Contains(tempKeys, operationContext);
if (goodKeysTable.ContainsKey("items-found") && goodKeysTable["items-found"] != null && tempKeys.Length == ((ArrayList)goodKeysTable["items-found"]).Count)
{
goodKeysList.Add(keys[i]);
goodEntriesList.Add(cacheEntries[i]);
}
else
{
badKeysList.Add(keys[i]);
}
}
else
{
goodKeysList.Add(keys[i]);
goodEntriesList.Add(cacheEntries[i]);
}
}
#endregion
goodEntries = new CacheEntry[goodEntriesList.Count];
goodEntriesList.CopyTo(goodEntries);
retVal = Internal.Insert(goodKeysList.ToArray(), goodEntries, notify, operationContext);
#region -- PART II -- Cascading Dependency Operation
object generateQueryInfo = operationContext.GetValueByField(OperationContextFieldName.GenerateQueryInfo);
if (generateQueryInfo == null)
{
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
}
for (int i = 0; i < goodKeysList.Count; i++)
{
if (operationContext.CancellationToken != null && operationContext.CancellationToken.IsCancellationRequested)
throw new OperationCanceledException(ExceptionsResource.OperationFailed);
CacheInsResultWithEntry result = retVal[goodKeysList[i]] as CacheInsResultWithEntry;
if (result != null && (result.Result == CacheInsResult.Success || result.Result == CacheInsResult.SuccessOverwrite))
{
Hashtable keyDepInfosTable = null;
if (result.Entry != null && result.Entry.KeysIAmDependingOnWithDependencyInfo != null)
{
keyDepInfosTable = GetFinalKeysListWithDependencyInfo(result.Entry, goodEntries[i]);
Hashtable oldKeysTable = GetKeysTable(goodKeysList[i], (KeyDependencyInfo[])keyDepInfosTable["oldKeys"]);
Internal.RemoveDepKeyList(oldKeysTable, operationContext);
oldKeysTable = GetKeyDependencyInfoTable(goodKeysList[i], (KeyDependencyInfo[])keyDepInfosTable["newKeys"]);
Internal.AddDepKeyList(oldKeysTable, operationContext);
}
else if (goodEntries[i].KeysIAmDependingOn != null)
{
Hashtable newKeysTable = GetKeyDependencyInfoTable(goodKeysList[i], goodEntries[i].KeysIAmDependingOnWithDependencyInfo);
Internal.AddDepKeyList(newKeysTable, operationContext);
}
}
}
//Now Remove GeneratedQueryInfo If added at this step
if (generateQueryInfo == null)
{
operationContext.RemoveValueByField(OperationContextFieldName.GenerateQueryInfo);
}
for (int i = 0; i < badKeysList.Count; i++)
{
retVal.Add(badKeysList[i], new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND)));
}
#endregion
}
return retVal;
}
finally
{
if (goodEntries != null)
goodEntries.MarkFree(NCModulesConstants.CacheImpl);
if (cacheEntries != null)
cacheEntries.MarkFree(NCModulesConstants.CacheImpl);
}
}
public override object RemoveSync(object[] keys, ItemRemoveReason reason, bool notify, OperationContext operationContext)
{
ArrayList depenedentItemList = new ArrayList();
try
{
Hashtable totalRemovedItems = new Hashtable();
CacheEntry entry = null;
IDictionaryEnumerator ide = null;
Hashtable result = Internal.Remove(keys, reason, false, operationContext);
ide = result.GetEnumerator();
while (ide.MoveNext())
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
totalRemovedItems.Add(ide.Key, entry);
if (entry.KeysDependingOnMe != null && entry.KeysDependingOnMe.Count > 0)
{
depenedentItemList.AddRange(entry.KeysDependingOnMe.Keys);
}
}
}
ide = totalRemovedItems.GetEnumerator();
while (ide.MoveNext())
{
try
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
if (IsItemRemoveNotifier)
{
EventId eventId = null;
OperationID opId = operationContext.OperatoinID;
EventContext eventContext = null;
//generate event id
if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations
{
eventId = EventId.CreateEventId(opId);
}
else //for bulk
{
eventId = ((EventContext)operationContext.GetValueByField(OperationContextFieldName.EventContext)).EventID;
}
}
if (entry.Notifications != null)
{
EventId eventId = null;
OperationID opId = operationContext.OperatoinID;
Caching.Notifications cbEtnry = entry.Notifications;// e.DeflattedValue(_context.SerializationContext);
EventContext eventContext = null;
if (cbEtnry != null && cbEtnry.ItemRemoveCallbackListener != null && cbEtnry.ItemRemoveCallbackListener.Count > 0)
{
//generate event id
if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations
{
eventId = EventId.CreateEventId(opId);
}
else //for bulk
{
eventId = ((EventContext)operationContext.GetValueByField(OperationContextFieldName.EventContext)).EventID;
}
eventId.EventType = EventType.ITEM_REMOVED_CALLBACK;
eventContext = new EventContext();
eventContext.Add(EventContextFieldName.EventID, eventId);
EventCacheEntry eventCacheEntry = CacheHelper.CreateCacheEventEntry(cbEtnry.ItemRemoveCallbackListener, entry, Context);
eventContext.Item = eventCacheEntry;
eventContext.Add(EventContextFieldName.ItemRemoveCallbackList, cbEtnry.ItemRemoveCallbackListener.Clone());
eventContext.UniqueId = GenerateEventType(EventType.ITEM_REMOVED_CALLBACK)+entry.Version.ToString();
//Will always reaise the whole entry for old clients
NotifyCustomRemoveCallback(ide.Key, entry, reason, true, operationContext, eventContext);
}
}
}
}
catch (Exception ex)
{
}
}
}
catch (Exception)
{
throw;
}
return depenedentItemList;
}
public string GenerateEventType(EventType eventType)
{
switch (eventType)
{
case EventType.ITEM_REMOVED_CALLBACK:
return "Removed_cb";
break;
case EventType.ITEM_UPDATED_CALLBACK:
return "Updated_cb";
break;
case EventType.ITEM_ADDED_EVENT:
return "Added_event";
break;
case EventType.ITEM_REMOVED_EVENT:
return "Removed_event";
break;
case EventType.ITEM_UPDATED_EVENT:
return "Updated_event";
break;
case EventType.ITEM_ADDED_CALLBACK:
return "Added_cb";
break;
default:
return "";
}
return "";
}
/// <summary>
/// Removes the object and key pair from the cache. The key is specified as parameter.
/// Moreover it take a removal reason and a boolean specifying if a notification should
/// be raised.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="removalReason">reason for the removal.</param>
/// <param name="notify">boolean specifying to raise the event.</param>
/// <returns>item value</returns>
public override CacheEntry Remove(object key, ItemRemoveReason ir, bool notify, object lockId, ulong version, LockAccessType accessType, OperationContext operationContext)
{
CacheEntry retVal = Internal.Remove(key, ir, notify, lockId, version, accessType, operationContext);
if (retVal != null && retVal.KeysIAmDependingOn != null)
{
Internal.RemoveDepKeyList(GetKeysTable(key, retVal.KeysIAmDependingOn), operationContext);
}
return retVal;
}
/// <summary>
/// Removes the key and pairs from the cache. The keys are specified as parameter.
/// Moreover it take a removal reason and a boolean specifying if a notification should
/// be raised.
/// </summary>
/// <param name="keys">key of the entries.</param>
/// <param name="removalReason">reason for the removal.</param>
/// <param name="notify">boolean specifying to raise the event.</param>
/// <returns>removed keys list</returns>
public override Hashtable Remove(IList keys, ItemRemoveReason ir, bool notify, OperationContext operationContext)
{
Hashtable retVal = Internal.Remove(keys, ir, notify, operationContext);
foreach (object key in keys)
{
if (operationContext.CancellationToken != null && operationContext.CancellationToken.IsCancellationRequested)
throw new OperationCanceledException(ExceptionsResource.OperationFailed);
CacheEntry entry = (CacheEntry)retVal[key];
if (entry != null && entry.KeysIAmDependingOn != null)
{
Internal.RemoveDepKeyList(GetKeysTable(key, entry.KeysIAmDependingOn), operationContext);
}
}
return retVal;
}
/// <summary>
/// Remove the group from cache.
/// </summary>
/// <param name="group">group to be removed.</param>
/// <param name="subGroup">subGroup to be removed.</param>
/// <param name="notify">boolean specifying to raise the event.</param>
public override Hashtable Remove(string group, string subGroup, bool notify, OperationContext operationContext)
{
ArrayList list = GetGroupKeys(group, subGroup, operationContext);
if (list != null && list.Count > 0)
{
object[] grpKeys = MiscUtil.GetArrayFromCollection(list);
return Remove(grpKeys, ItemRemoveReason.Removed, notify, operationContext);
}
return null;
}
/// <summary>
/// Broadcasts a user-defined event across the cluster.
/// </summary>
/// <param name="notifId"></param>
/// <param name="data"></param>
/// <param name="async"></param>
public override void SendNotification(object notifId, object data, OperationContext operationContext)
{
Internal.SendNotification(notifId, data, operationContext);
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
/// <returns>IDictionaryEnumerator enumerator.</returns>
public override IDictionaryEnumerator GetEnumerator()
{
return Internal.GetEnumerator();
}
public override EnumerationDataChunk GetNextChunk(EnumerationPointer pointer, OperationContext operationContext)
{
return Internal.GetNextChunk(pointer, operationContext);
}
#endregion
#region/ --- Key based notification registration --- /
public override void RegisterKeyNotification(string key, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.RegisterKeyNotification(key, updateCallback, removeCallback, operationContext);
}
public override void RegisterKeyNotification(string[] keys, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.RegisterKeyNotification(keys, updateCallback, removeCallback, operationContext);
}
public override void UnregisterKeyNotification(string key, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.UnregisterKeyNotification(key, updateCallback, removeCallback, operationContext);
}
public override void UnregisterKeyNotification(string[] keys, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.UnregisterKeyNotification(keys, updateCallback, removeCallback, operationContext);
}
#endregion
public override void UnLock(object key, object lockId, bool isPreemptive, OperationContext operationContext)
{
Internal.UnLock(key, lockId, isPreemptive, operationContext);
}
public override LockOptions Lock(object key, LockExpiration lockExpiration, ref object lockId, ref DateTime lockDate, OperationContext operationContext)
{
return Internal.Lock(key, lockExpiration, ref lockId, ref lockDate, operationContext);
}
public override LockOptions IsLocked(object key, ref object lockId, ref DateTime lockDate, OperationContext operationContext)
{
return Internal.IsLocked(key, ref lockId, ref lockDate, operationContext);
}
#region / --- Stream Operations--- /
public override bool OpenStream(string key, string lockHandle, Alachisoft.NCache.Common.Enum.StreamModes mode, string group, string subGroup, ExpirationHint hint, Alachisoft.NCache.Caching.EvictionPolicies.EvictionHint evictinHint, OperationContext operationContext)
{
#region -- PART I -- Cascading Dependency Operation
object[] keys = CacheHelper.GetKeyDependencyTable(hint);
if (keys != null && mode == Alachisoft.NCache.Common.Enum.StreamModes.Write)
{
Hashtable goodKeysTable = Contains(keys, operationContext);
if (!goodKeysTable.ContainsKey("items-found"))
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (goodKeysTable["items-found"] == null)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
if (((ArrayList)goodKeysTable["items-found"]).Count != keys.Length)
throw new OperationFailedException(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.Common.DEPENDENCY_KEY_NOT_FOUND));
}
#endregion
bool streamopened = Internal.OpenStream(key, lockHandle, mode, group, subGroup, hint, evictinHint, operationContext);
#region -- PART II -- Cascading Dependency Operation
if (streamopened && mode == Alachisoft.NCache.Common.Enum.StreamModes.Write && keys != null)
{
Hashtable keyDepInfoTable = new Hashtable();
keyDepInfoTable = GetKeyDependencyInfoTable(key, (KeyDependencyInfo[])CacheHelper.GetKeyDependencyInfoTable(hint));
Internal.AddDepKeyList(keyDepInfoTable, operationContext);
}
#endregion
return streamopened;
}
public override void CloseStream(string key, string lockHandle, OperationContext operationContext)
{
Internal.CloseStream(key, lockHandle, operationContext);
}
public override int ReadFromStream(ref Alachisoft.NCache.Common.DataStructures.VirtualArray vBuffer, string key, string lockHandle, int offset, int length, OperationContext operationContext)
{
return Internal.ReadFromStream(ref vBuffer, key, lockHandle, offset, length, operationContext);
}
public override void WriteToStream(string key, string lockHandle, Alachisoft.NCache.Common.DataStructures.VirtualArray vBuffer, int srcOffset, int dstOffset, int length, OperationContext operationContext)
{
Internal.WriteToStream(key, lockHandle, vBuffer, srcOffset, dstOffset, length, operationContext);
}
public override long GetStreamLength(string key, string lockHandle, OperationContext operationContext)
{
return Internal.GetStreamLength(key, lockHandle, operationContext);
}
#endregion
#region ICacheEventsListener Members
void ICacheEventsListener.OnItemAdded(object key, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnItemUpdated(object key, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnItemRemoved(object key, object val, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnItemsRemoved(object[] keys, object[] vals, ItemRemoveReason reason, OperationContext operationContext, EventContext[] eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnCacheCleared(OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnCustomEvent(object notifId, object data, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnCustomUpdateCallback(object key, object value, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnPollNotify(string clientId, short callbackId, NCache.Caching.Events.EventTypeInternal eventType)
{
base.NotifyPollRequestCallback(clientId, callbackId, true, eventType);
}
void ICacheEventsListener.OnCustomRemoveCallback(object key, object value, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
#if !CLIENT && !DEVELOPMENT
void ICacheEventsListener.OnHashmapChanged(Alachisoft.NCache.Common.DataStructures.NewHashmap newHashmap, bool updateClientMap)
{
throw new Exception("The method or operation is not implemented.");
}
#endif
void ICacheEventsListener.OnWriteBehindOperationCompletedCallback(OpCode operationCode, object result, Caching.Notifications notification)
{
throw new Exception("The method or operation is not implemented.");
}
internal override void Touch(List<string> keys, OperationContext operationContext)
{
Internal.Touch(keys, operationContext);
}
#endregion
#region ------------------------------- Messaging ------------------------------
#region ---------------------- IMessageStore Implementation --------------------
public override bool AssignmentOperation(MessageInfo messageInfo, SubscriptionInfo subscriptionInfo, TopicOperationType type, OperationContext context)
{
if (Internal == null)
throw new InvalidOperationException();
return Internal.AssignmentOperation(messageInfo, subscriptionInfo, type, context);
}
public override void RemoveMessages(IList<MessageInfo> messagesTobeRemoved, MessageRemovedReason reason, OperationContext context)
{
if (Internal == null)
throw new InvalidOperationException();
Internal.RemoveMessages(messagesTobeRemoved, reason, context);
}
public override bool StoreMessage(string topic, Message message, OperationContext context)
{
if (Internal == null)
throw new InvalidOperationException();
return Internal.StoreMessage(topic, message, context);
}
public override void AcknowledgeMessageReceipt(string clientId, IDictionary<string, IList<string>> topicWiseMessageIds, OperationContext operationContext)
{
if (Internal == null)
throw new InvalidOperationException();
Internal.AcknowledgeMessageReceipt(clientId, topicWiseMessageIds, operationContext);
}
public override bool TopicOperation(TopicOperation channelOperation, OperationContext operationContext)
{
if (Internal == null)
throw new InvalidOperationException();
return Internal.TopicOperation(channelOperation, operationContext);
}
#endregion
public override long GetMessageCount(string topicName, OperationContext operationContext)
{
if (Internal == null)
{
throw new InvalidOperationException();
}
return Internal.GetMessageCount(topicName, operationContext);
}
public override void ClientConnected(string client, bool isInproc, Runtime.Caching.ClientInfo clientInfo)
{
if (Internal != null)
{
Internal.ClientConnected(client, isInproc, clientInfo);
}
}
public override void ClientDisconnected(string client, bool isInproc, Runtime.Caching.ClientInfo clientInfo)
{
CacheStatistics stats = InternalCache.Statistics;
if (stats != null && stats.ConnectedClients != null)
{
lock (stats.ConnectedClients.SyncRoot)
{
if (stats.ConnectedClients.Contains(client))
{
stats.ConnectedClients.Remove(client);
}
}
}
if (Internal != null)
{
Internal.ClientDisconnected(client, isInproc, clientInfo);
}
}
public void OnOperationModeChanged(OperationMode mode)
{
}
#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.Collections.Generic;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Security.Principal;
using System.DirectoryServices;
using System.Collections.Specialized;
namespace System.DirectoryServices.AccountManagement
{
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal partial class ADStoreCtx : StoreCtx
{
//
// Query operations
//
// Returns true if this store has native support for search (and thus a wormhole).
// Returns true for everything but SAM (both reg-SAM and MSAM).
internal override bool SupportsSearchNatively { get { return true; } }
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// PrincipalSearcher.
internal override Type SearcherNativeType() { return typeof(DirectorySearcher); }
private void BuildExtensionPropertyList(Hashtable propertyList, Type p)
{
System.Reflection.PropertyInfo[] propertyInfoList = p.GetProperties();
foreach (System.Reflection.PropertyInfo pInfo in propertyInfoList)
{
DirectoryPropertyAttribute[] pAttributeList = (DirectoryPropertyAttribute[])(pInfo.GetCustomAttributes(typeof(DirectoryPropertyAttribute), true));
foreach (DirectoryPropertyAttribute pAttribute in pAttributeList)
{
if (!propertyList.Contains(pAttribute.SchemaAttributeName))
propertyList.Add(pAttribute.SchemaAttributeName, pAttribute.SchemaAttributeName);
}
}
}
protected void BuildPropertySet(Type p, StringCollection propertySet)
{
if (TypeToLdapPropListMap[this.MappingTableIndex].ContainsKey(p))
{
Debug.Assert(TypeToLdapPropListMap[this.MappingTableIndex].ContainsKey(p));
string[] props = new string[TypeToLdapPropListMap[this.MappingTableIndex][p].Count];
TypeToLdapPropListMap[this.MappingTableIndex][p].CopyTo(props, 0);
propertySet.AddRange(props);
}
else
{
Type baseType;
if (p.IsSubclassOf(typeof(UserPrincipal)))
{
baseType = typeof(UserPrincipal);
}
else if (p.IsSubclassOf(typeof(GroupPrincipal)))
{
baseType = typeof(GroupPrincipal);
}
else if (p.IsSubclassOf(typeof(ComputerPrincipal)))
{
baseType = typeof(ComputerPrincipal);
}
else if (p.IsSubclassOf(typeof(AuthenticablePrincipal)))
{
baseType = typeof(AuthenticablePrincipal);
}
else
{
baseType = typeof(Principal);
}
Hashtable propertyList = new Hashtable();
// Load the properties for the base types...
foreach (string s in TypeToLdapPropListMap[this.MappingTableIndex][baseType])
{
if (!propertyList.Contains(s))
{
propertyList.Add(s, s);
}
}
// Reflect the properties off the extension class and add them to the list.
BuildExtensionPropertyList(propertyList, p);
foreach (string property in propertyList.Values)
{
propertySet.Add(property);
}
// Cache the list for this property type so we don't need to reflect again in the future.
this.AddPropertySetToTypePropListMap(p, propertySet);
}
}
// Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
// searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
// doesn't already exist) and returns the native searcher.
// If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
// produces a query that will match all principals in the store.
//
// For stores which don't have a native searcher (SAM), the StoreCtx
// is free to create any type of object it chooses to use as its internal representation of the query.
//
// Also adds in any clauses to the searcher to ensure that only principals, not mere
// contacts, are retrieved from the store.
internal override object PushFilterToNativeSearcher(PrincipalSearcher ps)
{
// This is the first time we're being called on this principal. Create a fresh searcher.
if (ps.UnderlyingSearcher == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: creating fresh DirectorySearcher");
ps.UnderlyingSearcher = new DirectorySearcher(this.ctxBase);
((DirectorySearcher)ps.UnderlyingSearcher).PageSize = ps.PageSize;
((DirectorySearcher)ps.UnderlyingSearcher).ServerTimeLimit = new TimeSpan(0, 0, 30); // 30 seconds
}
DirectorySearcher ds = (DirectorySearcher)ps.UnderlyingSearcher;
Principal qbeFilter = ps.QueryFilter;
StringBuilder ldapFilter = new StringBuilder();
if (qbeFilter == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: no qbeFilter specified");
// No filter specified. Search for all principals (all users, computers, groups).
ldapFilter.Append("(|(objectClass=user)(objectClass=computer)(objectClass=group))");
}
else
{
//
// Start by appending the appropriate objectClass given the Principal type
//
ldapFilter.Append(GetObjectClassPortion(qbeFilter.GetType()));
//
// Next, fill in the properties (if any)
//
QbeFilterDescription filters = BuildQbeFilterDescription(qbeFilter);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: using {0} filters", filters.FiltersToApply.Count);
Hashtable filterTable = (Hashtable)s_filterPropertiesTable[this.MappingTableIndex];
foreach (FilterBase filter in filters.FiltersToApply)
{
FilterPropertyTableEntry entry = (FilterPropertyTableEntry)filterTable[filter.GetType()];
if (entry == null)
{
// Must be a property we don't support
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
SR.StoreCtxUnsupportedPropertyForQuery,
PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
}
ldapFilter.Append(entry.converter(filter, entry.suggestedADPropertyName));
}
//
// Wrap off the filter
//
ldapFilter.Append(")");
}
// We don't need any attributes returned, since we're just going to get a DirectoryEntry
// for the result. Per RFC 2251, OID 1.1 == no attributes.
//ds.PropertiesToLoad.Add("1.1");
BuildPropertySet(qbeFilter.GetType(), ds.PropertiesToLoad);
ds.Filter = ldapFilter.ToString();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: using LDAP filter {0}", ds.Filter);
return ds;
}
virtual protected string GetObjectClassPortion(Type principalType)
{
string ldapFilter;
if (principalType == typeof(UserPrincipal))
ldapFilter = "(&(objectCategory=user)(objectClass=user)"; // objCat because we don't want to match on computer accounts
else if (principalType == typeof(GroupPrincipal))
ldapFilter = "(&(objectClass=group)";
else if (principalType == typeof(ComputerPrincipal))
ldapFilter = "(&(objectClass=computer)";
else if (principalType == typeof(Principal))
ldapFilter = "(&(|(objectClass=user)(objectClass=group))";
else if (principalType == typeof(AuthenticablePrincipal))
ldapFilter = "(&(objectClass=user)";
else
{
string objClass = ExtensionHelper.ReadStructuralObjectClass(principalType);
if (null == objClass)
{
Debug.Fail("ADStoreCtx.GetObjectClassPortion: fell off end looking for " + principalType.ToString());
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType.ToString()));
}
StringBuilder SB = new StringBuilder();
SB.Append("(&(objectClass=");
SB.Append(objClass);
SB.Append(")");
ldapFilter = SB.ToString();
}
return ldapFilter;
}
// The core query operation.
// Given a PrincipalSearcher containg a query filter, transforms it into the store schema
// and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit,
// or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1).
// If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null),
// matches all principals in the store.
//
// The collection may not be complete, i.e., paging - the returned ResultSet will automatically
// page in additional results as needed.
internal override ResultSet Query(PrincipalSearcher ps, int sizeLimit)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Query");
try
{
// Set up the DirectorySearcher
DirectorySearcher ds = (DirectorySearcher)PushFilterToNativeSearcher(ps);
int oldSizeLimit = ds.SizeLimit;
Debug.Assert(sizeLimit >= -1);
if (sizeLimit != -1)
ds.SizeLimit = sizeLimit;
// Perform the actual search
SearchResultCollection src = ds.FindAll();
Debug.Assert(src != null);
// Create a ResultSet for the search results
ADEntriesSet resultSet = new ADEntriesSet(src, this, ps.QueryFilter.GetType());
ds.SizeLimit = oldSizeLimit;
return resultSet;
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
//
// Query tables
//
// We only list properties we support filtering on in this table. At run-time, if we detect they set a
// property that's not listed here, we throw an exception.
private static object[,] s_filterPropertiesTableRaw =
{
// QbeType AD property Converter
{typeof(DescriptionFilter), "description", new FilterConverterDelegate(StringConverter)},
{typeof(DisplayNameFilter), "displayName", new FilterConverterDelegate(StringConverter)},
{typeof(IdentityClaimFilter), "", new FilterConverterDelegate(IdentityClaimConverter)},
{typeof(SamAccountNameFilter), "sAMAccountName", new FilterConverterDelegate(StringConverter)},
{typeof(DistinguishedNameFilter), "distinguishedName", new FilterConverterDelegate(StringConverter)},
{typeof(GuidFilter), "objectGuid", new FilterConverterDelegate(GuidConverter)},
{typeof(UserPrincipalNameFilter), "userPrincipalName", new FilterConverterDelegate(StringConverter)},
{typeof(StructuralObjectClassFilter), "objectClass", new FilterConverterDelegate(StringConverter)},
{typeof(NameFilter), "name", new FilterConverterDelegate(StringConverter)},
{typeof(CertificateFilter), "", new FilterConverterDelegate(CertificateConverter)},
{typeof(AuthPrincEnabledFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(PermittedWorkstationFilter), "userWorkstations", new FilterConverterDelegate(CommaStringConverter)},
{typeof(PermittedLogonTimesFilter), "logonHours", new FilterConverterDelegate(BinaryConverter)},
{typeof(ExpirationDateFilter), "accountExpires", new FilterConverterDelegate(ExpirationDateConverter)},
{typeof(SmartcardLogonRequiredFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(DelegationPermittedFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(HomeDirectoryFilter), "homeDirectory", new FilterConverterDelegate(StringConverter)},
{typeof(HomeDriveFilter), "homeDrive", new FilterConverterDelegate(StringConverter)},
{typeof(ScriptPathFilter), "scriptPath", new FilterConverterDelegate(StringConverter)},
{typeof(PasswordNotRequiredFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(PasswordNeverExpiresFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(CannotChangePasswordFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(AllowReversiblePasswordEncryptionFilter), "userAccountControl", new FilterConverterDelegate(UserAccountControlConverter)},
{typeof(GivenNameFilter), "givenName", new FilterConverterDelegate(StringConverter)},
{typeof(MiddleNameFilter), "middleName", new FilterConverterDelegate(StringConverter)},
{typeof(SurnameFilter), "sn", new FilterConverterDelegate(StringConverter)},
{typeof(EmailAddressFilter), "mail", new FilterConverterDelegate(StringConverter)},
{typeof(VoiceTelephoneNumberFilter), "telephoneNumber", new FilterConverterDelegate(StringConverter)},
{typeof(EmployeeIDFilter), "employeeID", new FilterConverterDelegate(StringConverter)},
{typeof(GroupIsSecurityGroupFilter), "groupType", new FilterConverterDelegate(GroupTypeConverter)},
{typeof(GroupScopeFilter), "groupType", new FilterConverterDelegate(GroupTypeConverter)},
{typeof(ServicePrincipalNameFilter), "servicePrincipalName",new FilterConverterDelegate(StringConverter)},
{typeof(ExtensionCacheFilter), null ,new FilterConverterDelegate(ExtensionCacheConverter)},
{typeof(BadPasswordAttemptFilter), "badPasswordTime",new FilterConverterDelegate(DefaultValutMatchingDateTimeConverter)},
{typeof(ExpiredAccountFilter), "accountExpires",new FilterConverterDelegate(MatchingDateTimeConverter)},
{typeof(LastLogonTimeFilter), "lastLogon",new FilterConverterDelegate(LastLogonConverter)},
{typeof(LockoutTimeFilter), "lockoutTime",new FilterConverterDelegate(MatchingDateTimeConverter)},
{typeof(PasswordSetTimeFilter), "pwdLastSet",new FilterConverterDelegate(DefaultValutMatchingDateTimeConverter)},
{typeof(BadLogonCountFilter), "badPwdCount",new FilterConverterDelegate(MatchingIntConverter)}
};
private static Hashtable s_filterPropertiesTable = null;
private class FilterPropertyTableEntry
{
internal string suggestedADPropertyName;
internal FilterConverterDelegate converter;
}
//
// Conversion routines
//
// returns LDAP filter clause, e.g., "(description=foo*")
protected delegate string FilterConverterDelegate(FilterBase filter, string suggestedAdProperty);
protected static string StringConverter(FilterBase filter, string suggestedAdProperty)
{
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append(ADUtils.PAPIQueryToLdapQueryString((string)filter.Value));
sb.Append(")");
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
return sb.ToString();
}
protected static string AcctDisabledConverter(FilterBase filter, string suggestedAdProperty)
{
// Principal property is AccountEnabled where TRUE = enabled FALSE = disabled. In ADAM
// this is stored as accountDisabled where TRUE = disabled and FALSE = enabled so here we need to revese the value.
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append(!(bool)filter.Value ? "TRUE" : "FALSE");
sb.Append(")");
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
return sb.ToString();
}
// Use this function when searching for an attribute where the absence of the attribute = a default setting.
// i.e. ms-DS-UserPasswordNotRequired in ADAM where non existence equals false.
protected static string DefaultValueBoolConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(NonPresentAttrDefaultStateMapping != null);
Debug.Assert(NonPresentAttrDefaultStateMapping.ContainsKey(suggestedAdProperty));
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
bool defaultState = NonPresentAttrDefaultStateMapping[suggestedAdProperty];
if (defaultState == (bool)filter.Value)
{
sb.Append("(|(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*)(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append((bool)filter.Value ? "TRUE" : "FALSE");
sb.Append(")))");
}
else
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append((bool)filter.Value ? "TRUE" : "FALSE");
sb.Append(")");
}
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
return sb.ToString();
}
/*** If standard bool conversion is needed uncomment this function
protected static string BoolConverter(FilterBase filter, string suggestedAdProperty)
{
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append( (bool)filter.Value ? "TRUE" : "FALSE" );
sb.Append(")");
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
return sb.ToString();
}
*****/
protected static string CommaStringConverter(FilterBase filter, string suggestedAdProperty)
{
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=*");
sb.Append(ADUtils.PAPIQueryToLdapQueryString((string)filter.Value));
sb.Append("*");
sb.Append(")");
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
return sb.ToString();
}
protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref String filter, bool throwOnFail)
{
if (identity == null)
identity = "";
StringBuilder sb = new StringBuilder();
switch (identityFormat)
{
case UrnScheme.GuidScheme:
// Transform from hex string ("1AFF") to LDAP hex string ("\1A\FF")
// The string passed is the string format of a GUID. We neeed to convert it into the ldap hex string
// to build a query
Guid g;
try
{
g = new Guid(identity);
}
catch (FormatException e)
{
if (throwOnFail)
// For now throw an exception to let the caller know the type was invalid.
throw new ArgumentException(e.Message, e);
else
return false;
}
Byte[] gByte = g.ToByteArray();
StringBuilder stringguid = new StringBuilder();
foreach (byte b in gByte)
{
stringguid.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
string ldapHexGuid = ADUtils.HexStringToLdapHexString(stringguid.ToString());
if (ldapHexGuid == null)
{
if (throwOnFail)
throw new ArgumentException(SR.StoreCtxGuidIdentityClaimBadFormat);
else
return false;
}
sb.Append("(objectGuid=");
sb.Append(ldapHexGuid);
sb.Append(")");
break;
case UrnScheme.DistinguishedNameScheme:
sb.Append("(distinguishedName=");
sb.Append(ADUtils.EscapeRFC2254SpecialChars(identity));
sb.Append(")");
break;
case UrnScheme.SidScheme:
if (false == SecurityIdentityClaimConverterHelper(identity, false, sb, throwOnFail))
{
return false;
}
break;
case UrnScheme.SamAccountScheme:
int index = identity.IndexOf('\\');
if (index == identity.Length - 1)
if (throwOnFail)
throw new ArgumentException(SR.StoreCtxNT4IdentityClaimWrongForm);
else
return false;
string samAccountName = (index != -1) ? identity.Substring(index + 1) : // +1 to skip the '/'
identity;
sb.Append("(samAccountName=");
sb.Append(ADUtils.EscapeRFC2254SpecialChars(samAccountName));
sb.Append(")");
break;
case UrnScheme.NameScheme:
sb.Append("(name=");
sb.Append(ADUtils.EscapeRFC2254SpecialChars(identity));
sb.Append(")");
break;
case UrnScheme.UpnScheme:
sb.Append("(userPrincipalName=");
sb.Append(ADUtils.EscapeRFC2254SpecialChars(identity));
sb.Append(")");
break;
default:
if (throwOnFail)
throw new ArgumentException(SR.StoreCtxUnsupportedIdentityClaimForQuery);
else
return false;
}
filter = sb.ToString();
return true;
}
protected static string IdentityClaimConverter(FilterBase filter, string suggestedAdProperty)
{
IdentityClaim ic = (IdentityClaim)filter.Value;
if (ic.UrnScheme == null)
throw new ArgumentException(SR.StoreCtxIdentityClaimMustHaveScheme);
string urnValue = ic.UrnValue;
if (urnValue == null)
urnValue = "";
string filterString = null;
IdentityClaimToFilter(urnValue, ic.UrnScheme, ref filterString, true);
return filterString;
}
// If useSidHistory == false, build a filter for objectSid.
// If useSidHistory == true, build a filter for objectSid and sidHistory.
protected static bool SecurityIdentityClaimConverterHelper(string urnValue, bool useSidHistory, StringBuilder filter, bool throwOnFail)
{
// String is in SDDL format. Translate it to ldap hex format
IntPtr pBytePtr = IntPtr.Zero;
byte[] sidB = null;
try
{
if (UnsafeNativeMethods.ConvertStringSidToSid(urnValue, ref pBytePtr))
{
// Now we convert the native SID to a byte[] SID
sidB = Utils.ConvertNativeSidToByteArray(pBytePtr);
if (null == sidB)
{
if (throwOnFail)
throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat);
else
return false;
}
}
else
{
if (throwOnFail)
throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat);
else
return false;
}
}
finally
{
if (IntPtr.Zero != pBytePtr)
UnsafeNativeMethods.LocalFree(pBytePtr);
}
StringBuilder stringizedBinarySid = new StringBuilder();
foreach (byte b in sidB)
{
stringizedBinarySid.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
string ldapHexSid = ADUtils.HexStringToLdapHexString(stringizedBinarySid.ToString());
if (ldapHexSid == null)
return false;
if (useSidHistory)
{
filter.Append("(|(objectSid=");
filter.Append(ldapHexSid);
filter.Append(")(sidHistory=");
filter.Append(ldapHexSid);
filter.Append("))");
}
else
{
filter.Append("(objectSid=");
filter.Append(ldapHexSid);
filter.Append(")");
}
return true;
}
protected static string CertificateConverter(FilterBase filter, string suggestedAdProperty)
{
System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
(System.Security.Cryptography.X509Certificates.X509Certificate2)filter.Value;
byte[] rawCertificate = certificate.RawData;
StringBuilder sb = new StringBuilder();
sb.Append("(userCertificate=");
sb.Append(ADUtils.EscapeBinaryValue(rawCertificate));
sb.Append(")");
return sb.ToString();
}
protected static string UserAccountControlConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(String.Compare(suggestedAdProperty, "userAccountControl", StringComparison.OrdinalIgnoreCase) == 0);
StringBuilder sb = new StringBuilder();
// bitwise-AND
bool value = (bool)filter.Value;
switch (filter.PropertyName)
{
case AuthPrincEnabledFilter.PropertyNameStatic:
// UF_ACCOUNTDISABLE
// Note that the logic is inverted on this one. We expose "Enabled",
// but AD stores it as "Disabled".
if (value)
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=2))");
else
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=2)");
break;
case SmartcardLogonRequiredFilter.PropertyNameStatic:
// UF_SMARTCARD_REQUIRED
if (value)
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=262144)");
else
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=262144))");
break;
case DelegationPermittedFilter.PropertyNameStatic:
// UF_NOT_DELEGATED
// Note that the logic is inverted on this one. That's because we expose
// "delegation allowed", but AD represents it as the inverse, "delegation NOT allowed"
if (value)
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=1048576))");
else
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=1048576)");
break;
case PasswordNotRequiredFilter.PropertyNameStatic:
// UF_PASSWD_NOTREQD
if (value)
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=32)");
else
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=32))");
break;
case PasswordNeverExpiresFilter.PropertyNameStatic:
// UF_DONT_EXPIRE_PASSWD
if (value)
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=65536)");
else
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=65536))");
break;
case CannotChangePasswordFilter.PropertyNameStatic:
// UF_PASSWD_CANT_CHANGE
// This bit doesn't work correctly in AD (AD models the "user can't change password"
// setting as special ACEs in the ntSecurityDescriptor).
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
SR.StoreCtxUnsupportedPropertyForQuery,
PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
case AllowReversiblePasswordEncryptionFilter.PropertyNameStatic:
// UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
if (value)
sb.Append("(userAccountControl:1.2.840.113556.1.4.803:=128)");
else
sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=128))");
break;
default:
Debug.Fail("ADStoreCtx.UserAccountControlConverter: fell off end looking for " + filter.PropertyName);
break;
}
return sb.ToString();
}
protected static string BinaryConverter(FilterBase filter, string suggestedAdProperty)
{
StringBuilder sb = new StringBuilder();
if (filter.Value != null)
{
sb.Append("(");
sb.Append(suggestedAdProperty);
sb.Append("=");
sb.Append(ADUtils.EscapeBinaryValue((byte[])filter.Value));
}
else
{
sb.Append("(!(");
sb.Append(suggestedAdProperty);
sb.Append("=*))");
}
sb.Append(")");
return sb.ToString();
}
protected static string ExpirationDateConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(String.Compare(suggestedAdProperty, "accountExpires", StringComparison.OrdinalIgnoreCase) == 0);
Debug.Assert(filter is ExpirationDateFilter);
Nullable<DateTime> date = (Nullable<DateTime>)filter.Value;
StringBuilder sb = new StringBuilder();
if (!date.HasValue)
{
// Spoke with ColinBr. Both values are used to represent "no expiration date set".
sb.Append("(|(accountExpires=9223372036854775807)(accountExpires=0))");
}
else
{
sb.Append("(accountExpires=");
sb.Append(ADUtils.DateTimeToADString(date.Value));
sb.Append(")");
}
return sb.ToString();
}
protected static string GuidConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(String.Compare(suggestedAdProperty, "objectGuid", StringComparison.OrdinalIgnoreCase) == 0);
Debug.Assert(filter is GuidFilter);
Nullable<Guid> guid = (Nullable<Guid>)filter.Value;
StringBuilder sb = new StringBuilder();
if (guid == null)
{
// Spoke with ColinBr. Both values are used to represent "no expiration date set".
// sb.Append("(|(accountExpires=9223372036854775807)(accountExpires=0))");
}
else
{
sb.Append("(objectGuid=");
// Transform from hex string ("1AFF") to LDAP hex string ("\1A\FF")
string ldapHexGuid = ADUtils.HexStringToLdapHexString(guid.ToString());
if (ldapHexGuid == null)
throw new InvalidOperationException(SR.StoreCtxGuidIdentityClaimBadFormat);
sb.Append(ldapHexGuid);
sb.Append(")");
}
return sb.ToString();
}
protected static string MatchingIntConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(filter.Value is QbeMatchType);
QbeMatchType qmt = (QbeMatchType)filter.Value;
return (ExtensionTypeConverter(suggestedAdProperty, qmt.Value.GetType(), qmt.Value, qmt.Match));
}
protected static string DefaultValutMatchingDateTimeConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(filter.Value is QbeMatchType);
QbeMatchType qmt = (QbeMatchType)filter.Value;
Debug.Assert(qmt.Value is DateTime);
return (DateTimeFilterBuilder(suggestedAdProperty, (DateTime)qmt.Value, LdapConstants.defaultUtcTime, false, qmt.Match));
}
protected static string MatchingDateTimeConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(filter.Value is QbeMatchType);
QbeMatchType qmt = (QbeMatchType)filter.Value;
Debug.Assert(qmt.Value is DateTime);
return (ExtensionTypeConverter(suggestedAdProperty, qmt.Value.GetType(), qmt.Value, qmt.Match));
}
protected static string LastLogonConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(filter.Value is QbeMatchType);
QbeMatchType qmt = (QbeMatchType)filter.Value;
Debug.Assert(qmt.Value is DateTime);
Debug.Assert((suggestedAdProperty == "lastLogon") || (suggestedAdProperty == "lastLogonTimestamp"));
StringBuilder sb = new StringBuilder();
sb.Append("(|");
sb.Append(DateTimeFilterBuilder("lastLogon", (DateTime)qmt.Value, LdapConstants.defaultUtcTime, false, qmt.Match));
sb.Append(DateTimeFilterBuilder("lastLogonTimestamp", (DateTime)qmt.Value, LdapConstants.defaultUtcTime, true, qmt.Match));
sb.Append(")");
return (sb.ToString());
}
protected static string GroupTypeConverter(FilterBase filter, string suggestedAdProperty)
{
Debug.Assert(String.Compare(suggestedAdProperty, "groupType", StringComparison.OrdinalIgnoreCase) == 0);
Debug.Assert(filter is GroupIsSecurityGroupFilter || filter is GroupScopeFilter);
// 1.2.840.113556.1.4.803 is like a bit-wise AND operator
switch (filter.PropertyName)
{
case GroupIsSecurityGroupFilter.PropertyNameStatic:
bool value = (bool)filter.Value;
// GROUP_TYPE_SECURITY_ENABLED
// If group is enabled, it IS security-enabled
if (value)
return "(groupType:1.2.840.113556.1.4.803:=2147483648)";
else
return "(!(groupType:1.2.840.113556.1.4.803:=2147483648))";
case GroupScopeFilter.PropertyNameStatic:
GroupScope value2 = (GroupScope)filter.Value;
switch (value2)
{
case GroupScope.Local:
// GROUP_TYPE_RESOURCE_GROUP, a.k.a. ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP
return "(groupType:1.2.840.113556.1.4.803:=4)";
case GroupScope.Global:
// GROUP_TYPE_ACCOUNT_GROUP, a.k.a. ADS_GROUP_TYPE_GLOBAL_GROUP
return "(groupType:1.2.840.113556.1.4.803:=2)";
default:
// GROUP_TYPE_UNIVERSAL_GROUP, a.k.a. ADS_GROUP_TYPE_UNIVERSAL_GROUP
Debug.Assert(value2 == GroupScope.Universal);
return "(groupType:1.2.840.113556.1.4.803:=8)";
}
default:
Debug.Fail("ADStoreCtx.GroupTypeConverter: fell off end looking for " + filter.PropertyName);
return "";
}
}
public static string DateTimeFilterBuilder(string attributeName, DateTime searchValue, DateTime defaultValue, bool requirePresence, MatchType mt)
{
string ldapSearchValue = null;
string ldapDefaultValue = null;
bool defaultNeeded = false;
ldapSearchValue = ADUtils.DateTimeToADString(searchValue);
if (defaultValue != null)
{
ldapDefaultValue = ADUtils.DateTimeToADString(defaultValue);
}
StringBuilder ldapFilter = new StringBuilder("(");
if (defaultValue != null && (mt != MatchType.Equals && mt != MatchType.NotEquals))
{
defaultNeeded = true;
}
if (defaultNeeded || (mt == MatchType.NotEquals && requirePresence))
{
ldapFilter.Append("&(");
}
switch (mt)
{
case MatchType.Equals:
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapSearchValue);
break;
case MatchType.NotEquals:
ldapFilter.Append("!(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapSearchValue);
ldapFilter.Append(")");
break;
case MatchType.GreaterThanOrEquals:
ldapFilter.Append(attributeName);
ldapFilter.Append(">=");
ldapFilter.Append(ldapSearchValue);
break;
case MatchType.LessThanOrEquals:
ldapFilter.Append(attributeName);
ldapFilter.Append("<=");
ldapFilter.Append(ldapSearchValue);
break;
case MatchType.GreaterThan:
ldapFilter.Append("&");
// Greater-than-or-equals (or less-than-or-equals))
ldapFilter.Append("(");
ldapFilter.Append(attributeName);
ldapFilter.Append(mt == MatchType.GreaterThan ? ">=" : "<=");
ldapFilter.Append(ldapSearchValue);
ldapFilter.Append(")");
// And not-equal
ldapFilter.Append("(!(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapSearchValue);
ldapFilter.Append("))");
// And exists (need to include because of tristate LDAP logic)
ldapFilter.Append("(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=*)");
break;
case MatchType.LessThan:
goto case MatchType.GreaterThan;
}
ldapFilter.Append(")");
bool closeFilter = false;
if (defaultNeeded)
{
ldapFilter.Append("(!");
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapDefaultValue);
ldapFilter.Append(")");
closeFilter = true;
}
if (mt == MatchType.NotEquals && requirePresence)
{
ldapFilter.Append("(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=*)");
closeFilter = true;
}
if (closeFilter)
ldapFilter.Append(")");
return (ldapFilter.ToString());
}
public static string ExtensionTypeConverter(string attributeName, Type type, Object value, MatchType mt)
{
StringBuilder ldapFilter = new StringBuilder("(");
string ldapValue;
if (typeof(Boolean) == type)
{
ldapValue = ((bool)value ? "TRUE" : "FALSE");
}
else if (type is ICollection)
{
StringBuilder collectionFilter = new StringBuilder();
ICollection collection = (ICollection)value;
foreach (object o in collection)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionTypeConverter collection filter type " + o.GetType().ToString());
collectionFilter.Append(ExtensionTypeConverter(attributeName, o.GetType(), o, mt));
}
return collectionFilter.ToString();
}
else if (typeof(DateTime) == type)
{
ldapValue = ADUtils.DateTimeToADString((DateTime)value);
}
else
{
ldapValue = ADUtils.PAPIQueryToLdapQueryString(value.ToString());
}
switch (mt)
{
case MatchType.Equals:
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapValue);
break;
case MatchType.NotEquals:
ldapFilter.Append("!(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapValue);
ldapFilter.Append(")");
break;
case MatchType.GreaterThanOrEquals:
ldapFilter.Append(attributeName);
ldapFilter.Append(">=");
ldapFilter.Append(ldapValue);
break;
case MatchType.LessThanOrEquals:
ldapFilter.Append(attributeName);
ldapFilter.Append("<=");
ldapFilter.Append(ldapValue);
break;
case MatchType.GreaterThan:
ldapFilter.Append("&");
// Greater-than-or-equals (or less-than-or-equals))
ldapFilter.Append("(");
ldapFilter.Append(attributeName);
ldapFilter.Append(mt == MatchType.GreaterThan ? ">=" : "<=");
ldapFilter.Append(ldapValue);
ldapFilter.Append(")");
// And not-equal
ldapFilter.Append("(!(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=");
ldapFilter.Append(ldapValue);
ldapFilter.Append("))");
// And exists (need to include because of tristate LDAP logic)
ldapFilter.Append("(");
ldapFilter.Append(attributeName);
ldapFilter.Append("=*)");
break;
case MatchType.LessThan:
goto case MatchType.GreaterThan;
}
ldapFilter.Append(")");
return ldapFilter.ToString();
}
protected static string ExtensionCacheConverter(FilterBase filter, string suggestedAdProperty)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter ");
StringBuilder query = new StringBuilder();
if (filter.Value != null)
{
ExtensionCache ec = (ExtensionCache)filter.Value;
foreach (KeyValuePair<string, ExtensionCacheValue> kvp in ec.properties)
{
Type type = kvp.Value.Type == null ? kvp.Value.Value.GetType() : kvp.Value.Type;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter filter type " + type.ToString());
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter match type " + kvp.Value.MatchType.ToString());
if (kvp.Value.Value is ICollection)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter encountered collection.");
ICollection collection = (ICollection)kvp.Value.Value;
foreach (object o in collection)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter collection filter type " + o.GetType().ToString());
query.Append(ExtensionTypeConverter(kvp.Key, o.GetType(), o, kvp.Value.MatchType));
}
}
else
{
query.Append(ExtensionTypeConverter(kvp.Key, type, kvp.Value.Value, kvp.Value.MatchType));
}
}
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter complete built filter " + query.ToString());
return query.ToString();
}
///
/// <summary>
/// Adds the specified Property set to the TypeToPropListMap data structure.
/// </summary>
///
private void AddPropertySetToTypePropListMap(Type principalType, StringCollection propertySet)
{
lock (TypeToLdapPropListMap)
{
if (!TypeToLdapPropListMap[this.MappingTableIndex].ContainsKey(principalType))
{
TypeToLdapPropListMap[this.MappingTableIndex].Add(principalType, propertySet);
}
}
}
}
}
//#endif // PAPI_AD
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using System.Diagnostics;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// Page for scenario 1 of our sample.
/// </summary>
public sealed partial class Scenario1
{
private MainPage rootPage = null;
private bool isInitialized = false;
/// <summary>
/// Indicates whether this scenario page is still active. Changes value during navigation
/// to or away from the page.
/// </summary>
private bool isThisPageActive = false;
// same type as returned from Windows.Storage.Pickers.FileOpenPicker.PickMultipleFilesAsync()
private IReadOnlyList<StorageFile> playlist = null;
/// <summary>
/// index to current media item in playlist
/// </summary>
private int currentItemIndex = 0;
/// <summary>
/// Indicates whetehr to stat the playlist again upon reaching the end.
/// </summary>
private bool repeatPlaylist = false;
private SystemMediaTransportControls systemMediaControls = null;
private DispatcherTimer smtcPositionUpdateTimer = null;
private bool pausedDueToMute = false;
public Scenario1()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
rootPage = MainPage.Current;
isThisPageActive = true;
// retrieve the SystemMediaTransportControls object, register for its events, and configure it
// to a disabled state consistent with how this scenario starts off (ie. no media loaded)
SetupSystemMediaTransportControls();
if (!isInitialized)
{
isInitialized = true;
MyMediaElement.CurrentStateChanged += MyMediaElement_CurrentStateChanged;
MyMediaElement.MediaOpened += MyMediaElement_MediaOpened;
MyMediaElement.MediaEnded += MyMediaElement_MediaEnded;
MyMediaElement.MediaFailed += MyMediaElement_MediaFailed;
smtcPositionUpdateTimer = new DispatcherTimer();
smtcPositionUpdateTimer.Interval = TimeSpan.FromSeconds(5);
smtcPositionUpdateTimer.Tick += positionUpdate_TimerTick;
}
}
private void positionUpdate_TimerTick(object sender, object e)
{
UpdateSmtcPosition();
}
/// <summary>
/// Invoked when we are about to leave this page.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
isThisPageActive = false;
rootPage = null;
// Because the system media transport control object is associated with the current app view
// (ie. window), all scenario pages in this sample will be using the same instance. Therefore
// we need to remove the event handlers specific to this scenario page before
// user navigates away to another scenario in the sample.
systemMediaControls.ButtonPressed -= systemMediaControls_ButtonPressed;
systemMediaControls.PlaybackRateChangeRequested -= systemMediaControls_PlaybackRateChangeRequested;
systemMediaControls.PlaybackPositionChangeRequested -= systemMediaControls_PlaybackPositionChangeRequested;
systemMediaControls.AutoRepeatModeChangeRequested -= systemMediaControls_AutoRepeatModeChangeRequested;
// Perform other cleanup for this scenario page.
MyMediaElement.Source = null;
playlist = null;
currentItemIndex = 0;
}
/// <summary>
/// Invoked from this scenario page's OnNavigatedTo event handler. Retrieve and initialize the
/// SystemMediaTransportControls object.
/// </summary>
private void SetupSystemMediaTransportControls()
{
// Retrieve the SystemMediaTransportControls object associated with the current app view
// (ie. window). There is exactly one instance of the object per view, instantiated by
// the system the first time GetForCurrentView() is called for the view. All subsequent
// calls to GetForCurrentView() from the same view (eg. from different scenario pages in
// this sample) will return the same instance of the object.
systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
// This scenario will always start off with no media loaded, so we will start off disabling the
// system media transport controls. Doing so will hide the system UI for media transport controls
// from being displayed, and will prevent the app from receiving any events such as ButtonPressed
// from it, regardless of the current state of event registrations and button enable/disable states.
// This makes IsEnabled a handy way to turn system media transport controls off and back on, as you
// may want to do when the user navigates to and away from certain parts of your app.
systemMediaControls.IsEnabled = false;
// To receive notifications for the user pressing media keys (eg. "Stop") on the keyboard, or
// clicking/tapping on the equivalent software buttons in the system media transport controls UI,
// all of the following needs to be true:
// 1. Register for ButtonPressed event on the SystemMediaTransportControls object.
// 2. IsEnabled property must be true to enable SystemMediaTransportControls itself.
// [Note: IsEnabled is initialized to true when the system instantiates the
// SystemMediaTransportControls object for the current app view.]
// 3. For each button you want notifications from, set the corresponding property to true to
// enable the button. For example, set IsPlayEnabled to true to enable the "Play" button
// and media key.
// [Note: the individual button-enabled properties are initialized to false when the
// system instantiates the SystemMediaTransportControls object for the current app view.]
//
// Here we'll perform 1, and 3 for the buttons that will always be enabled for this scenario (Play,
// Pause, Stop). For 2, we purposely set IsEnabled to false to be consistent with the scenario's
// initial state of no media loaded. Later in the code where we handle the loading of media
// selected by the user, we will enable SystemMediaTransportControls.
systemMediaControls.ButtonPressed += systemMediaControls_ButtonPressed;
// Add event handlers to support requests from the system to change our playback state.
systemMediaControls.PlaybackRateChangeRequested += systemMediaControls_PlaybackRateChangeRequested;
systemMediaControls.PlaybackPositionChangeRequested += systemMediaControls_PlaybackPositionChangeRequested;
systemMediaControls.AutoRepeatModeChangeRequested += systemMediaControls_AutoRepeatModeChangeRequested;
// Subscribe to property changed events to get SoundLevel changes.
systemMediaControls.PropertyChanged += systemMediaControls_PropertyChanged;
// Note: one of the prerequisites for an app to be allowed to play audio while in background,
// is to enable handling Play and Pause ButtonPressed events from SystemMediaTransportControls.
systemMediaControls.IsPlayEnabled = true;
systemMediaControls.IsPauseEnabled = true;
systemMediaControls.IsStopEnabled = true;
systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
}
private async void systemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (args.Property == SystemMediaTransportControlsProperty.SoundLevel)
{
// Check for the new Sound level
switch (systemMediaControls.SoundLevel)
{
case SoundLevel.Full:
if (pausedDueToMute)
{
// If we previously paused due to being muted, resume.
MyMediaElement.Play();
}
break;
case SoundLevel.Low:
// We're being ducked, take no action.
break;
case SoundLevel.Muted:
if (MyMediaElement != null && MyMediaElement.CurrentState == MediaElementState.Playing)
{
// We've been muted by the system, pause to save our playback position.
MyMediaElement.Pause();
pausedDueToMute = true;
}
break;
}
}
});
}
private async void systemMediaControls_AutoRepeatModeChangeRequested(SystemMediaTransportControls sender, AutoRepeatModeChangeRequestedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Media Element only supports repeating a track, if we want to repeat a list we need to handle it ourselves
switch (args.RequestedAutoRepeatMode)
{
case MediaPlaybackAutoRepeatMode.None:
MyMediaElement.IsLooping = false;
repeatPlaylist = false;
break;
case MediaPlaybackAutoRepeatMode.List:
MyMediaElement.IsLooping = false;
repeatPlaylist = true;
break;
case MediaPlaybackAutoRepeatMode.Track:
MyMediaElement.IsLooping = true;
repeatPlaylist = false;
break;
}
// Report back our new state as whatever was requested, seeing as we always honor it.
systemMediaControls.AutoRepeatMode = args.RequestedAutoRepeatMode;
rootPage.NotifyUser("Auto repeat mode change requested", NotifyType.StatusMessage);
});
}
/// <summary>
/// Used to update all position/duration related information to the SystemMediaTransport controls.
/// Can be used when some state changes (new track, position changed) or periodically (every 5 seconds or so)
/// to keep the system in sync with this apps playback state.
/// </summary>
private void UpdateSmtcPosition()
{
var timelineProperties = new SystemMediaTransportControlsTimelineProperties();
// This is a simple scenario that supports seeking, therefore start time and min seek are both 0 and
// end time and max seek are both the duration. This allows the system to suggest seeking anywhere in the track.
// Position is obviously the current media elements position.
// Note: More complex scenarios may alter more of these values, such as only allowing seeking in a section of the content,
// by setting min and max seek differently to start and end. For other scenarios such as live playback, end time may be
// updated frequently too.
timelineProperties.StartTime = TimeSpan.FromSeconds(0);
timelineProperties.MinSeekTime = TimeSpan.FromSeconds(0);
timelineProperties.Position = MyMediaElement.Position;
timelineProperties.MaxSeekTime = MyMediaElement.NaturalDuration.TimeSpan;
timelineProperties.EndTime = MyMediaElement.NaturalDuration.TimeSpan;
systemMediaControls.UpdateTimelineProperties(timelineProperties);
}
/// <summary>
/// Handles a request from the System Media Transport Controls to change our current playback position.
/// </summary>
private async void systemMediaControls_PlaybackPositionChangeRequested(SystemMediaTransportControls sender, PlaybackPositionChangeRequestedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// First we validate that the requested position falls within the range of the current piece of content we are playing,
// this should usually be the case but the content may have changed whilst the request was coming in.
if (args.RequestedPlaybackPosition.Duration() <= MyMediaElement.NaturalDuration.TimeSpan.Duration() &&
args.RequestedPlaybackPosition.Duration().TotalSeconds >= 0)
{
// Next we verify that our media element is in a state that we think is valid to change the position
if (MyMediaElement.CurrentState == MediaElementState.Paused || MyMediaElement.CurrentState == MediaElementState.Playing)
{
// Finally if the above conditions are met we update the position and report the new position back to SMTC.
MyMediaElement.Position = args.RequestedPlaybackPosition.Duration();
UpdateSmtcPosition();
}
}
rootPage.NotifyUser("Playback position change requested", NotifyType.StatusMessage);
});
}
/// <summary>
/// Handles a request from the System Media Transport Controls tro change our current playback rate
/// </summary>
private async void systemMediaControls_PlaybackRateChangeRequested(SystemMediaTransportControls sender, PlaybackRateChangeRequestedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Check to make sure the requested value is in a range we deem appropriate, if so set it on the MediaElement.
// We then need to turn around and update SMTC so that the system knows the new value.
if (args.RequestedPlaybackRate >= 0 && args.RequestedPlaybackRate <= 2)
{
MyMediaElement.PlaybackRate = args.RequestedPlaybackRate;
systemMediaControls.PlaybackRate = MyMediaElement.PlaybackRate;
}
rootPage.NotifyUser("Playback rate change requested", NotifyType.StatusMessage);
});
}
// For supported audio and video formats for Windows Store apps, see:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh986969.aspx
private static string[] supportedAudioFormats = new string[]
{
".3g2", ".3gp2", ".3gp", ".3gpp", ".m4a", ".mp4", ".asf", ".wma", ".aac", ".adt", ".adts", ".mp3", ".wav", ".ac3", ".ec3",
};
private static string[] supportedVideoFormats = new string[]
{
".3g2", ".3gp2", ".3gp", ".3gpp", ".m4v", ".mp4v", ".mp4", ".mov", ".m2ts", ".asf", ".wmv", ".avi",
};
/// <summary>
/// Invoked when user invokes the "Select Files" XAML button in the app.
/// Launches the Windows File Picker to let user select a list of audio or video files
// to play in the app.
/// </summary>
private async void SelectFilesButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.List;
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.CommitButtonText = "Play";
foreach (string fileExtension in supportedAudioFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
foreach (string fileExtension in supportedVideoFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
IReadOnlyList<StorageFile> selectedFiles = await filePicker.PickMultipleFilesAsync();
if (selectedFiles.Count > 0)
{
rootPage.NotifyUser(String.Format("{0} file(s) selected", selectedFiles.Count), NotifyType.StatusMessage);
playlist = selectedFiles;
// Now that we have a playlist ready, allow the user to control media playback via system media
// transport controls. We enable it now even if one or more files may turn out unable to load
// into the MediaElement control, to allow the user to invoke Next/Previous to go to another
// item in the playlist to try playing.
systemMediaControls.IsEnabled = true;
// For the design of this sample scenario, we will always automatically start playback after
// the user has selected new files to play. Set AutoPlay to true so the XAML MediaElement
// control will automatically start playing after we do a SetSource() on it in SetNewMediaItem().
MyMediaElement.AutoPlay = true;
await SetNewMediaItem(0); // Start with first file in the list of picked files.
}
else
{
// user canceled the file picker
rootPage.NotifyUser("no files selected", NotifyType.StatusMessage);
}
}
private void MyMediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
if (isThisPageActive)
{
if (MyMediaElement.IsAudioOnly)
{
// Ensure the XAML MediaElement control has enough height and some reasonable width
// to display the build-in transport controls for audio-only playback.
MyMediaElement.MinWidth = 456;
MyMediaElement.MinHeight = 120;
MyMediaElement.MaxHeight = 120;
// Force the MediaElement out of fullscreen mode in case the user was using that
// for a video playback but we are now loading audio-only content. The build-in
// transport controls for audio-only playback do not have the button to
// enter/exit fullscreen mode.
MyMediaElement.IsFullWindow = false;
}
else
{
// For video playback, let XAML resize MediaElement control based on the dimensions
// of the video, but also have XAML scale it down as necessary (preserving aspect ratio)
// to a reasonable maximum height like 300.
MyMediaElement.MinWidth = 0;
MyMediaElement.MinHeight = 0;
MyMediaElement.MaxHeight = 300;
}
}
}
private async void MyMediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
if (isThisPageActive)
{
if (currentItemIndex < playlist.Count - 1)
{
// Current media must've been playing if we received an event about it ending.
// The design of this sample scenario is to automatically start playing the next
// item in the playlist. So we'll set the AutoPlay property to true, then in
// SetNewMediaItem() when we eventually call SetSource() on the XAML MediaElement
// control, it will automatically playing the new media item.
MyMediaElement.AutoPlay = true;
await SetNewMediaItem(currentItemIndex + 1);
}
else
{
// End of playlist reached.
if (repeatPlaylist)
{
// Playlist repeat was selected so start again.
MyMediaElement.AutoPlay = true;
await SetNewMediaItem(0);
rootPage.NotifyUser("end of playlist, starting playback again at beginning of playlist", NotifyType.StatusMessage);
}
else
{
// Repeat wasn't selected so just stop playback.
MyMediaElement.AutoPlay = false;
MyMediaElement.Stop();
rootPage.NotifyUser("end of playlist, stopping playback", NotifyType.StatusMessage);
}
}
}
}
private void MyMediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
if (isThisPageActive)
{
string errorMessage = String.Format(@"Cannot play {0} [""{1}""]." +
"\nPress Next or Previous to continue, or select new files to play.",
playlist[currentItemIndex].Name,
e.ErrorMessage.Trim());
rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage);
}
}
/// <summary>
/// Updates the SystemMediaTransportControls' PlaybackStatus property based on the CurrentState property of the
/// MediaElement control.
/// </summary>
/// <remarks>Invoked mainly from the MediaElement control's CurrentStateChanged event handler.</remarks>
private void SyncPlaybackStatusToMediaElementState()
{
// Updating PlaybackStatus with accurate information is important; for example, it determines whether the system media
// transport controls UI will show a play vs pause software button, and whether hitting the play/pause toggle key on
// the keyboard will translate to a Play vs a Pause ButtonPressed event.
//
// Even if your app uses its own custom transport controls in place of the built-in ones from XAML, it is still a good
// idea to update PlaybackStatus in response to the MediaElement's CurrentStateChanged event. Windows supports scenarios
// such as streaming media from a MediaElement to a networked device (eg. TV) selected by the user from Devices charm
// (ie. "Play To"), in which case the user may pause and resume media streaming using a TV remote or similar means.
// The CurrentStateChanged event may be the only way to get notified of playback status changes in those cases.
switch (MyMediaElement.CurrentState)
{
case MediaElementState.Closed:
systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
case MediaElementState.Opening:
// This state is when new media is being loaded to the XAML MediaElement control [ie.
// SetSource()]. For this sample the design is to maintain the previous playing/pause
// state before the new media is being loaded. So we'll leave the PlaybackStatus alone
// during loading. This keeps the system UI from flickering between displaying a "Play"
// vs "Pause" software button during the transition to a new media item.
break;
case MediaElementState.Buffering:
// No updates in MediaPlaybackStatus necessary--buffering is just
// a transitional state where the system is still working to get
// media to start or to continue playing.
break;
case MediaElementState.Paused:
systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Playing:
systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Stopped:
systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
}
// If we started playing start our timer else make sure it's stopped.
// On state changed always send an update to keep the system in sync.
if(MyMediaElement.CurrentState == MediaElementState.Playing)
{
smtcPositionUpdateTimer.Start();
}
else
{
smtcPositionUpdateTimer.Stop();
}
UpdateSmtcPosition();
}
private void MyMediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (!isThisPageActive)
{
return;
}
// For the design of this sample, the general idea is that if user is playing
// media when Next/Previous is invoked, we will automatically start playing
// the new item once it has loaded. Whereas if the user has paused or stopped
// media playback when Next/Previous is invoked, we won't automatically start
// playing the new item. In other words, we maintain the user's intent to
// play or not play across changing the media. This is most easily handled
// using the AutoPlay property of the XAML MediaElement control.
if (MyMediaElement.CurrentState == MediaElementState.Playing)
{
MyMediaElement.AutoPlay = true;
}
else if (MyMediaElement.CurrentState == MediaElementState.Stopped ||
MyMediaElement.CurrentState == MediaElementState.Paused)
{
MyMediaElement.AutoPlay = false;
}
// Update the playback status tracked by SystemMediaTransportControls. See comments
// in SyncPlaybackStatusToMediaElementState()'s body for why this is important.
SyncPlaybackStatusToMediaElementState();
}
private async void systemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
// The system media transport control's ButtonPressed event may not fire on the app's UI thread. XAML controls
// (including the MediaElement control in our page as well as the scenario page itself) typically can only be
// safely accessed and manipulated on the UI thread, so here for simplicity, we dispatch our entire event handling
// code to execute on the UI thread, as our code here primarily deals with updating the UI and the MediaElement.
//
// Depending on how exactly you are handling the different button presses (which for your app may include buttons
// not used in this sample scenario), you may instead choose to only dispatch certain parts of your app's
// event handling code (such as those that interact with XAML) to run on UI thread.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
// Because the handling code is dispatched asynchronously, it is possible the user may have
// navigated away from this scenario page to another scenario page by the time we are executing here.
// Check to ensure the page is still active before proceeding.
if (isThisPageActive)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
rootPage.NotifyUser("Play pressed", NotifyType.StatusMessage);
MyMediaElement.Play();
break;
case SystemMediaTransportControlsButton.Pause:
rootPage.NotifyUser("Pause pressed", NotifyType.StatusMessage);
MyMediaElement.Pause();
break;
case SystemMediaTransportControlsButton.Stop:
rootPage.NotifyUser("Stop pressed", NotifyType.StatusMessage);
MyMediaElement.Stop();
break;
case SystemMediaTransportControlsButton.Next:
rootPage.NotifyUser("Next pressed", NotifyType.StatusMessage);
// range-checking will be performed in SetNewMediaItem()
await SetNewMediaItem(currentItemIndex + 1);
break;
case SystemMediaTransportControlsButton.Previous:
rootPage.NotifyUser("Previous pressed", NotifyType.StatusMessage);
// range-checking will be performed in SetNewMediaItem()
await SetNewMediaItem(currentItemIndex - 1);
break;
// Insert additional case statements for other buttons you want to handle in your app.
// Remember that you also need to first enable those buttons via the corresponding
// Is****Enabled property on the SystemMediaTransportControls object.
}
}
});
}
/// <summary>
/// Returns an appropriate MediaPlaybackType value based on the given StorageFile's ContentType (MIME type).
/// </summary>
/// <returns>
/// One of the three valid MediaPlaybackType enum values, or MediaPlaybackType.Unknown if the ContentType
/// is not a media type (audio, video, image) or cannot be determined.
// </returns>
/// <remarks>
/// For use with SystemMediaTransportControlsDisplayUpdater.CopyFromFileAsync() in UpdateSystemMediaControlsDisplayAsync().
/// </remarks>
private MediaPlaybackType GetMediaTypeFromFileContentType(StorageFile file)
{
// Determine the appropriate MediaPlaybackType of the media file based on its ContentType (ie. MIME type).
// The MediaPlaybackType determines the information shown in the system UI for the system media transport
// controls. For example, the CopyFromFileAsync() API method will look for different metadata properties
// from the file to be extracted for eventual display in the system UI, depending on the MediaPlaybackType
// passed to the method.
// NOTE: MediaPlaybackType.Unknown is *not* a valid value to use in SystemMediaTransportControls APIs.
// This method will return MediaPlaybackType.Unknown to indicate no valid MediaPlaybackType exists/can be
// determined for the given StorageFile.
MediaPlaybackType mediaPlaybackType = MediaPlaybackType.Unknown;
string fileMimeType = file.ContentType.ToLowerInvariant();
if (fileMimeType.StartsWith("audio/"))
{
mediaPlaybackType = MediaPlaybackType.Music;
}
else if (fileMimeType.StartsWith("video/"))
{
mediaPlaybackType = MediaPlaybackType.Video;
}
else if (fileMimeType.StartsWith("image/"))
{
mediaPlaybackType = MediaPlaybackType.Image;
}
return mediaPlaybackType;
}
/// <summary>
/// Updates the system UI for media transport controls to display media metadata from the given StorageFile.
/// </summary>
/// <param name="mediaFile">
/// The media file being loaded. This method will try to extract media metadata from the file for use in
/// the system UI for media transport controls.
/// </param>
private async Task UpdateSystemMediaControlsDisplayAsync(StorageFile mediaFile)
{
MediaPlaybackType mediaType = GetMediaTypeFromFileContentType(mediaFile);
bool copyFromFileAsyncSuccessful = false;
if (MediaPlaybackType.Unknown != mediaType)
{
// Use the SystemMediaTransportControlsDisplayUpdater's CopyFromFileAsync() API method to try extracting
// from the StorageFile the relevant media metadata information (eg. track title, artist and album art
// for MediaPlaybackType.Music), copying them into properties of DisplayUpdater and related classes.
//
// In place of using CopyFromFileAsync() [or, you can't use that method because your app's media playback
// scenario doesn't involve StorageFiles], you can also use other properties in DisplayUpdater and
// related classes to explicitly set the MediaPlaybackType and media metadata properties to values of
// your choosing.
//
// Usage notes:
// - the first argument cannot be MediaPlaybackType.Unknown
// - API method may throw an Exception on certain file errors from the passed in StorageFile, such as
// file-not-found error (eg. file was deleted after user had picked it from file picker earlier).
try
{
copyFromFileAsyncSuccessful = await systemMediaControls.DisplayUpdater.CopyFromFileAsync(mediaType, mediaFile);
}
catch (Exception)
{
// For this sample, we will handle this case same as CopyFromFileAsync returning false,
// though we could provide our own metadata here.
}
}
else
{
// If we are here, it means we are unable to determine a MediaPlaybackType based on the StorageFile's
// ContentType (MIME type). CopyFromFileAsync() requires a valid MediaPlaybackType (ie. cannot be
// MediaPlaybackType.Unknown) for the first argument. One way to handle this is to just pick a valid
// MediaPlaybackType value to call CopyFromFileAsync() with, based on what your app does (eg. Music
// if your app is a music player). The MediaPlaybackType directs the API to look for particular sets
// of media metadata information from the StorageFile, and extraction is best-effort so in worst case
// simply no metadata information are extracted.
//
// For this sample, we will handle this case the same way as CopyFromFileAsync() returning false
}
if (!isThisPageActive)
{
// User may have navigated away from this scenario page to another scenario page
// before the async operation completed.
return;
}
if (!copyFromFileAsyncSuccessful)
{
// For this sample, if CopyFromFileAsync() didn't work for us for whatever reasons, we will just
// clear DisplayUpdater of all previously set metadata, if any. This makes sure we don't end up
// displaying in the system UI for media transport controls any stale metadata from the media item
// we were previously playing.
systemMediaControls.DisplayUpdater.ClearAll();
}
// Finally update the system UI display for media transport controls with the new values currently
// set in the DisplayUpdater, be it via CopyFrmoFileAsync(), ClearAll(), etc.
systemMediaControls.DisplayUpdater.Update();
}
/// <summary>
/// Performs all necessary actions (including SystemMediaTransportControls related) of loading a new media item
/// in the app for playback.
/// </summary>
/// <param name="newItemIndex">index in playlist of new item to load for playback, can be out of range.</param>
/// <remarks>
/// If the newItemIndex argument is out of range, it will be adjusted accordingly to stay in range.
/// </remarks>
private async Task SetNewMediaItem(int newItemIndex)
{
// enable Next button unless we're on last item of the playlist
if (newItemIndex >= playlist.Count - 1)
{
systemMediaControls.IsNextEnabled = false;
newItemIndex = playlist.Count - 1;
}
else
{
systemMediaControls.IsNextEnabled = true;
}
// enable Previous button unless we're on first item of the playlist
if (newItemIndex <= 0)
{
systemMediaControls.IsPreviousEnabled = false;
newItemIndex = 0;
}
else
{
systemMediaControls.IsPreviousEnabled = true;
}
// note that the Play, Pause and Stop buttons were already enabled via SetupSystemMediaTransportControls()
// invoked during this scenario page's OnNavigateToHandler()
currentItemIndex = newItemIndex;
StorageFile mediaFile = playlist[newItemIndex];
IRandomAccessStream stream = null;
try
{
stream = await mediaFile.OpenAsync(FileAccessMode.Read);
}
catch (Exception e)
{
// User may have navigated away from this scenario page to another scenario page
// before the async operation completed.
if (isThisPageActive)
{
// If the file can't be opened, for this sample we will behave similar to the case of
// setting a corrupted/invalid media file stream on the MediaElement (which triggers a
// MediaFailed event). We abort any ongoing playback by nulling the MediaElement's
// source. The user must press Next or Previous to move to a different media item,
// or use the file picker to load a new set of files to play.
MyMediaElement.Source = null;
string errorMessage = String.Format(@"Cannot open {0} [""{1}""]." +
"\nPress Next or Previous to continue, or select new files to play.",
mediaFile.Name,
e.Message.Trim());
rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage);
}
}
// User may have navigated away from this scenario page to another scenario page
// before the async operation completed. Check to make sure page is still active.
if (!isThisPageActive)
{
return;
}
if (stream != null)
{
// We're about to change the MediaElement's source media, so put ourselves into a
// "changing media" state. We stay in that state until the new media is playing,
// loaded (if user has currently paused or stopped playback), or failed to load.
// At those points we will call OnChangingMediaEnded().
MyMediaElement.SetSource(stream, mediaFile.ContentType);
}
try
{
// Updates the system UI for media transport controls to display metadata information
// reflecting the file we are playing (eg. track title, album art/video thumbnail, etc.)
// We call this even if the mediaFile can't be opened; in that case the method can still
// update the system UI to remove any metadata information previously displayed.
await UpdateSystemMediaControlsDisplayAsync(mediaFile);
}
catch (Exception e)
{
// Check isThisPageActive as user may have navigated away from this scenario page to
// another scenario page before the async operations completed.
if (isThisPageActive)
{
rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Threading.Tasks;
using System.Transactions;
using Bmz.Framework.Dependency;
using Bmz.Framework.Domain.Uow;
using Bmz.Framework.EntityFramework.Utils;
using Bmz.Framework.MultiTenancy;
using Bmz.Framework.Reflection;
using Castle.Core.Internal;
using EntityFramework.DynamicFilters;
namespace Bmz.Framework.EntityFramework.Uow
{
/// <summary>
/// Implements Unit of work for Entity Framework.
/// </summary>
public class EfUnitOfWork : UnitOfWorkBase, ITransientDependency
{
protected IDictionary<string, DbContext> ActiveDbContexts { get; private set; }
protected IIocResolver IocResolver { get; private set; }
protected TransactionScope CurrentTransaction;
private readonly IDbContextResolver _dbContextResolver;
/// <summary>
/// Creates a new <see cref="EfUnitOfWork"/>.
/// </summary>
public EfUnitOfWork(
IIocResolver iocResolver,
IConnectionStringResolver connectionStringResolver,
IDbContextResolver dbContextResolver,
IUnitOfWorkDefaultOptions defaultOptions)
: base(connectionStringResolver, defaultOptions)
{
IocResolver = iocResolver;
_dbContextResolver = dbContextResolver;
ActiveDbContexts = new Dictionary<string, DbContext>();
}
protected override void BeginUow()
{
if (Options.IsTransactional == true)
{
var transactionOptions = new TransactionOptions
{
IsolationLevel = Options.IsolationLevel.GetValueOrDefault(IsolationLevel.ReadUncommitted),
};
if (Options.Timeout.HasValue)
{
transactionOptions.Timeout = Options.Timeout.Value;
}
CurrentTransaction = new TransactionScope(
Options.Scope.GetValueOrDefault(TransactionScopeOption.Required),
transactionOptions,
Options.AsyncFlowOption.GetValueOrDefault(TransactionScopeAsyncFlowOption.Enabled)
);
}
}
public override void SaveChanges()
{
ActiveDbContexts.Values.ForEach(SaveChangesInDbContext);
}
public override async Task SaveChangesAsync()
{
foreach (var dbContext in ActiveDbContexts.Values)
{
await SaveChangesInDbContextAsync(dbContext);
}
}
protected override void CompleteUow()
{
SaveChanges();
if (CurrentTransaction != null)
{
CurrentTransaction.Complete();
}
DisposeUow();
}
protected override async Task CompleteUowAsync()
{
await SaveChangesAsync();
if (CurrentTransaction != null)
{
CurrentTransaction.Complete();
}
DisposeUow();
}
protected override void ApplyDisableFilter(string filterName)
{
foreach (var activeDbContext in ActiveDbContexts.Values)
{
activeDbContext.DisableFilter(filterName);
}
}
protected override void ApplyEnableFilter(string filterName)
{
foreach (var activeDbContext in ActiveDbContexts.Values)
{
activeDbContext.EnableFilter(filterName);
}
}
protected override void ApplyFilterParameterValue(string filterName, string parameterName, object value)
{
foreach (var activeDbContext in ActiveDbContexts.Values)
{
if (TypeHelper.IsFunc<object>(value))
{
activeDbContext.SetFilterScopedParameterValue(filterName, parameterName, (Func<object>)value);
}
else
{
activeDbContext.SetFilterScopedParameterValue(filterName, parameterName, value);
}
}
}
public virtual TDbContext GetOrCreateDbContext<TDbContext>(MultiTenancySides? multiTenancySide = null)
where TDbContext : DbContext
{
var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);
connectionStringResolveArgs["DbContextType"] = typeof(TDbContext);
var connectionString = ResolveConnectionString(connectionStringResolveArgs);
var dbContextKey = typeof(TDbContext).FullName + "#" + connectionString;
DbContext dbContext;
if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
{
dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString);
((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
{
ObjectContext_ObjectMaterialized(dbContext, args);
};
foreach (var filter in Filters)
{
if (filter.IsEnabled)
{
dbContext.EnableFilter(filter.FilterName);
}
else
{
dbContext.DisableFilter(filter.FilterName);
}
foreach (var filterParameter in filter.FilterParameters)
{
if (TypeHelper.IsFunc<object>(filterParameter.Value))
{
dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, (Func<object>)filterParameter.Value);
}
else
{
dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, filterParameter.Value);
}
}
}
ActiveDbContexts[dbContextKey] = dbContext;
}
return (TDbContext)dbContext;
}
protected override void DisposeUow()
{
ActiveDbContexts.Values.ForEach(Release);
ActiveDbContexts.Clear();
if (CurrentTransaction != null)
{
CurrentTransaction.Dispose();
CurrentTransaction = null;
}
}
protected virtual void SaveChangesInDbContext(DbContext dbContext)
{
dbContext.SaveChanges();
}
protected virtual async Task SaveChangesInDbContextAsync(DbContext dbContext)
{
await dbContext.SaveChangesAsync();
}
protected virtual void Release(DbContext dbContext)
{
dbContext.Dispose();
IocResolver.Release(dbContext);
}
private static void ObjectContext_ObjectMaterialized(DbContext dbContext, ObjectMaterializedEventArgs e)
{
var entityType = ObjectContext.GetObjectType(e.Entity.GetType());
var previousState = dbContext.Entry(e.Entity).State;
DateTimePropertyInfoHelper.NormalizeDatePropertyKinds(e.Entity, entityType);
dbContext.Entry(e.Entity).State = previousState;
}
}
}
| |
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Pkix
{
/// <summary>
/// A trust anchor or most-trusted Certification Authority (CA).
///
/// This class represents a "most-trusted CA", which is used as a trust anchor
/// for validating X.509 certification paths. A most-trusted CA includes the
/// public key of the CA, the CA's name, and any constraints upon the set of
/// paths which may be validated using this key. These parameters can be
/// specified in the form of a trusted X509Certificate or as individual
/// parameters.
/// </summary>
public class TrustAnchor
{
private readonly AsymmetricKeyParameter pubKey;
private readonly string caName;
private readonly X509Name caPrincipal;
private readonly X509Certificate trustedCert;
private byte[] ncBytes;
private NameConstraints nc;
/// <summary>
/// Creates an instance of TrustAnchor with the specified X509Certificate and
/// optional name constraints, which are intended to be used as additional
/// constraints when validating an X.509 certification path.
/// The name constraints are specified as a byte array. This byte array
/// should contain the DER encoded form of the name constraints, as they
/// would appear in the NameConstraints structure defined in RFC 2459 and
/// X.509. The ASN.1 definition of this structure appears below.
///
/// <pre>
/// NameConstraints ::= SEQUENCE {
/// permittedSubtrees [0] GeneralSubtrees OPTIONAL,
/// excludedSubtrees [1] GeneralSubtrees OPTIONAL }
///
/// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
///
/// GeneralSubtree ::= SEQUENCE {
/// base GeneralName,
/// minimum [0] BaseDistance DEFAULT 0,
/// maximum [1] BaseDistance OPTIONAL }
///
/// BaseDistance ::= INTEGER (0..MAX)
///
/// GeneralName ::= CHOICE {
/// otherName [0] OtherName,
/// rfc822Name [1] IA5String,
/// dNSName [2] IA5String,
/// x400Address [3] ORAddress,
/// directoryName [4] Name,
/// ediPartyName [5] EDIPartyName,
/// uniformResourceIdentifier [6] IA5String,
/// iPAddress [7] OCTET STRING,
/// registeredID [8] OBJECT IDENTIFIER}
/// </pre>
///
/// Note that the name constraints byte array supplied is cloned to protect
/// against subsequent modifications.
/// </summary>
/// <param name="trustedCert">a trusted X509Certificate</param>
/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
/// NameConstraints extension to be used for checking name
/// constraints. Only the value of the extension is included, not
/// the OID or criticality flag. Specify null to omit the
/// parameter.</param>
/// <exception cref="ArgumentNullException">if the specified X509Certificate is null</exception>
public TrustAnchor(
X509Certificate trustedCert,
byte[] nameConstraints)
{
if (trustedCert == null)
throw new ArgumentNullException("trustedCert");
this.trustedCert = trustedCert;
this.pubKey = null;
this.caName = null;
this.caPrincipal = null;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Creates an instance of <c>TrustAnchor</c> where the
/// most-trusted CA is specified as an X500Principal and public key.
/// </summary>
/// <remarks>
/// <p>
/// Name constraints are an optional parameter, and are intended to be used
/// as additional constraints when validating an X.509 certification path.
/// </p><p>
/// The name constraints are specified as a byte array. This byte array
/// contains the DER encoded form of the name constraints, as they
/// would appear in the NameConstraints structure defined in RFC 2459
/// and X.509. The ASN.1 notation for this structure is supplied in the
/// documentation for the other constructors.
/// </p><p>
/// Note that the name constraints byte array supplied here is cloned to
/// protect against subsequent modifications.
/// </p>
/// </remarks>
/// <param name="caPrincipal">the name of the most-trusted CA as X509Name</param>
/// <param name="pubKey">the public key of the most-trusted CA</param>
/// <param name="nameConstraints">
/// a byte array containing the ASN.1 DER encoding of a NameConstraints extension to
/// be used for checking name constraints. Only the value of the extension is included,
/// not the OID or criticality flag. Specify <c>null</c> to omit the parameter.
/// </param>
/// <exception cref="ArgumentNullException">
/// if <c>caPrincipal</c> or <c>pubKey</c> is null
/// </exception>
public TrustAnchor(
X509Name caPrincipal,
AsymmetricKeyParameter pubKey,
byte[] nameConstraints)
{
if (caPrincipal == null)
throw new ArgumentNullException("caPrincipal");
if (pubKey == null)
throw new ArgumentNullException("pubKey");
this.trustedCert = null;
this.caPrincipal = caPrincipal;
this.caName = caPrincipal.ToString();
this.pubKey = pubKey;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Creates an instance of <code>TrustAnchor</code> where the most-trusted
/// CA is specified as a distinguished name and public key. Name constraints
/// are an optional parameter, and are intended to be used as additional
/// constraints when validating an X.509 certification path.
/// <br/>
/// The name constraints are specified as a byte array. This byte array
/// contains the DER encoded form of the name constraints, as they would
/// appear in the NameConstraints structure defined in RFC 2459 and X.509.
/// </summary>
/// <param name="caName">the X.500 distinguished name of the most-trusted CA in RFC
/// 2253 string format</param>
/// <param name="pubKey">the public key of the most-trusted CA</param>
/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
/// NameConstraints extension to be used for checking name
/// constraints. Only the value of the extension is included, not
/// the OID or criticality flag. Specify null to omit the
/// parameter.</param>
/// throws NullPointerException, IllegalArgumentException
public TrustAnchor(
string caName,
AsymmetricKeyParameter pubKey,
byte[] nameConstraints)
{
if (caName == null)
throw new ArgumentNullException("caName");
if (pubKey == null)
throw new ArgumentNullException("pubKey");
if (caName.Length == 0)
throw new ArgumentException("caName can not be an empty string");
this.caPrincipal = new X509Name(caName);
this.pubKey = pubKey;
this.caName = caName;
this.trustedCert = null;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Returns the most-trusted CA certificate.
/// </summary>
public X509Certificate TrustedCert
{
get { return this.trustedCert; }
}
/// <summary>
/// Returns the name of the most-trusted CA as an X509Name.
/// </summary>
public X509Name CA
{
get { return this.caPrincipal; }
}
/// <summary>
/// Returns the name of the most-trusted CA in RFC 2253 string format.
/// </summary>
public string CAName
{
get { return this.caName; }
}
/// <summary>
/// Returns the public key of the most-trusted CA.
/// </summary>
public AsymmetricKeyParameter CAPublicKey
{
get { return this.pubKey; }
}
/// <summary>
/// Decode the name constraints and clone them if not null.
/// </summary>
private void setNameConstraints(
byte[] bytes)
{
if (bytes == null)
{
ncBytes = null;
nc = null;
}
else
{
ncBytes = (byte[]) bytes.Clone();
// validate DER encoding
//nc = new NameConstraintsExtension(Boolean.FALSE, bytes);
nc = NameConstraints.GetInstance(Asn1Object.FromByteArray(bytes));
}
}
public byte[] GetNameConstraints
{
get { return Arrays.Clone(ncBytes); }
}
/// <summary>
/// Returns a formatted string describing the <code>TrustAnchor</code>.
/// </summary>
/// <returns>a formatted string describing the <code>TrustAnchor</code></returns>
public override string ToString()
{
// TODO Some of the sub-objects might not implement ToString() properly
string nl = Platform.NewLine;
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.Append(nl);
if (this.pubKey != null)
{
sb.Append(" Trusted CA Public Key: ").Append(this.pubKey).Append(nl);
sb.Append(" Trusted CA Issuer Name: ").Append(this.caName).Append(nl);
}
else
{
sb.Append(" Trusted CA cert: ").Append(this.TrustedCert).Append(nl);
}
if (nc != null)
{
sb.Append(" Name Constraints: ").Append(nc).Append(nl);
}
return sb.ToString();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexFileNameFilter = Lucene.Net.Index.IndexFileNameFilter;
namespace Lucene.Net.Store
{
/// <summary>A Directory is a flat list of files. Files may be written once, when they
/// are created. Once a file is created it may only be opened for read, or
/// deleted. Random access is permitted both when reading and writing.
///
/// <p/> Java's i/o APIs not used directly, but rather all i/o is
/// through this API. This permits things such as: <list>
/// <item> implementation of RAM-based indices;</item>
/// <item> implementation indices stored in a database, via JDBC;</item>
/// <item> implementation of an index as a single file;</item>
/// </list>
///
/// Directory locking is implemented by an instance of <see cref="LockFactory" />
///, and can be changed for each Directory
/// instance using <see cref="SetLockFactory" />.
///
/// </summary>
[Serializable]
public abstract class Directory : System.IDisposable
{
protected internal volatile bool isOpen = true;
/// <summary>Holds the LockFactory instance (implements locking for
/// this Directory instance).
/// </summary>
[NonSerialized]
protected internal LockFactory interalLockFactory;
/// <summary>Returns an array of strings, one for each file in the directory.</summary>
/// <exception cref="System.IO.IOException"></exception>
public abstract System.String[] ListAll();
/// <summary>Returns true iff a file with the given name exists. </summary>
public abstract bool FileExists(System.String name);
/// <summary>Returns the time the named file was last modified. </summary>
public abstract long FileModified(System.String name);
/// <summary>Set the modified time of an existing file to now. </summary>
public abstract void TouchFile(System.String name);
/// <summary>Removes an existing file in the directory. </summary>
public abstract void DeleteFile(System.String name);
/// <summary>Returns the length of a file in the directory. </summary>
public abstract long FileLength(System.String name);
/// <summary>Creates a new, empty file in the directory with the given name.
/// Returns a stream writing this file.
/// </summary>
public abstract IndexOutput CreateOutput(System.String name);
/// <summary>Ensure that any writes to this file are moved to
/// stable storage. Lucene uses this to properly commit
/// changes to the index, to prevent a machine/OS crash
/// from corrupting the index.
/// </summary>
public virtual void Sync(System.String name)
{
}
/// <summary>Returns a stream reading an existing file. </summary>
public abstract IndexInput OpenInput(System.String name);
/// <summary>Returns a stream reading an existing file, with the
/// specified read buffer size. The particular Directory
/// implementation may ignore the buffer size. Currently
/// the only Directory implementations that respect this
/// parameter are <see cref="FSDirectory" /> and <see cref="Lucene.Net.Index.CompoundFileReader" />
///.
/// </summary>
public virtual IndexInput OpenInput(System.String name, int bufferSize)
{
return OpenInput(name);
}
/// <summary>Construct a <see cref="Lock" />.</summary>
/// <param name="name">the name of the lock file
/// </param>
public virtual Lock MakeLock(System.String name)
{
return interalLockFactory.MakeLock(name);
}
/// <summary> Attempt to clear (forcefully unlock and remove) the
/// specified lock. Only call this at a time when you are
/// certain this lock is no longer in use.
/// </summary>
/// <param name="name">name of the lock to be cleared.
/// </param>
public virtual void ClearLock(System.String name)
{
if (interalLockFactory != null)
{
interalLockFactory.ClearLock(name);
}
}
[Obsolete("Use Dispose() instead")]
public void Close()
{
Dispose();
}
/// <summary>Closes the store. </summary>
public void Dispose()
{
Dispose(true);
}
protected abstract void Dispose(bool disposing);
/// <summary> Set the LockFactory that this Directory instance should
/// use for its locking implementation. Each * instance of
/// LockFactory should only be used for one directory (ie,
/// do not share a single instance across multiple
/// Directories).
///
/// </summary>
/// <param name="lockFactory">instance of <see cref="LockFactory" />.
/// </param>
public virtual void SetLockFactory(LockFactory lockFactory)
{
System.Diagnostics.Debug.Assert(lockFactory != null);
this.interalLockFactory = lockFactory;
lockFactory.LockPrefix = this.GetLockId();
}
/// <summary> Get the LockFactory that this Directory instance is
/// using for its locking implementation. Note that this
/// may be null for Directory implementations that provide
/// their own locking implementation.
/// </summary>
public virtual LockFactory LockFactory
{
get { return this.interalLockFactory; }
}
/// <summary> Return a string identifier that uniquely differentiates
/// this Directory instance from other Directory instances.
/// This ID should be the same if two Directory instances
/// (even in different JVMs and/or on different machines)
/// are considered "the same index". This is how locking
/// "scopes" to the right index.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual string GetLockId()
{
return ToString();
}
public override string ToString()
{
return base.ToString() + " lockFactory=" + LockFactory;
}
/// <summary> Copy contents of a directory src to a directory dest.
/// If a file in src already exists in dest then the
/// one in dest will be blindly overwritten.
///
/// <p/><b>NOTE:</b> the source directory cannot change
/// while this method is running. Otherwise the results
/// are undefined and you could easily hit a
/// FileNotFoundException.
///
/// <p/><b>NOTE:</b> this method only copies files that look
/// like index files (ie, have extensions matching the
/// known extensions of index files).
///
/// </summary>
/// <param name="src">source directory
/// </param>
/// <param name="dest">destination directory
/// </param>
/// <param name="closeDirSrc">if <c>true</c>, call <see cref="Close()" /> method on source directory
/// </param>
/// <throws> IOException </throws>
public static void Copy(Directory src, Directory dest, bool closeDirSrc)
{
System.String[] files = src.ListAll();
IndexFileNameFilter filter = IndexFileNameFilter.Filter;
byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE];
for (int i = 0; i < files.Length; i++)
{
if (!filter.Accept(null, files[i]))
continue;
IndexOutput os = null;
IndexInput is_Renamed = null;
try
{
// create file in dest directory
os = dest.CreateOutput(files[i]);
// read current file
is_Renamed = src.OpenInput(files[i]);
// and copy to dest directory
long len = is_Renamed.Length();
long readCount = 0;
while (readCount < len)
{
int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len?(int) (len - readCount):BufferedIndexOutput.BUFFER_SIZE;
is_Renamed.ReadBytes(buf, 0, toRead);
os.WriteBytes(buf, toRead);
readCount += toRead;
}
}
finally
{
// graceful cleanup
try
{
if (os != null)
os.Close();
}
finally
{
if (is_Renamed != null)
is_Renamed.Close();
}
}
}
if (closeDirSrc)
src.Close();
}
/// <throws> AlreadyClosedException if this Directory is closed </throws>
public /*protected internal*/ void EnsureOpen()
{
if (!isOpen)
throw new AlreadyClosedException("this Directory is closed");
}
public bool isOpen_ForNUnit
{
get { return isOpen; }
}
}
}
| |
// 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.Buffers.Text;
namespace System.Text.Encodings.Web.Utf8
{
public class UrlEncoder
{
static readonly bool[] IsAllowed = new bool[0x7F + 1];
internal static bool TryEncode(ReadOnlySpan<byte> input, Span<byte> output, out int written)
{
written = 0;
for (int inputIndex = 0; inputIndex < input.Length; inputIndex++)
{
var next = input[inputIndex];
if(next > 0x7F)
{
throw new NotImplementedException();
}
if(written >= output.Length)
{
written = 0;
return false;
}
if (IsAllowed[next])
{
output[written++] = input[inputIndex];
}
else
{
output[written++] = (byte)'%';
if(!Utf8Formatter.TryFormat(next, output.Slice(written), out int formatted, 'X'))
{
written = 0;
return false;
}
written += formatted;
}
}
return true;
}
/// <summary>
/// Unescape a URL path
/// </summary>
/// <param name="source">The byte span represents a UTF8 encoding url path.</param>
/// <param name="destination">The byte span where unescaped url path is copied to.</param>
/// <returns>The length of the byte sequence of the unescaped url path.</returns>
internal static int Decode(ReadOnlySpan<byte> source, Span<byte> destination)
{
if (destination.Length < source.Length)
{
throw new ArgumentException(
"Lenghth of the destination byte span is less then the source.",
nameof(destination));
}
// This requires the destination span to be larger or equal to source span
source.CopyTo(destination);
return DecodeInPlace(destination);
}
/// <summary>
/// Unescape a URL path in place.
/// </summary>
/// <param name="buffer">The byte span represents a UTF8 encoding url path.</param>
/// <returns>The number of the bytes representing the result.</returns>
/// <remarks>
/// The unescape is done in place, which means after decoding the result is the subset of
/// the input span.
/// </remarks>
internal static int DecodeInPlace(Span<byte> buffer)
{
// the slot to read the input
var sourceIndex = 0;
// the slot to write the unescaped byte
var destinationIndex = 0;
while (true)
{
if (sourceIndex == buffer.Length)
{
break;
}
if (buffer[sourceIndex] == '%')
{
var decodeIndex = sourceIndex;
// If decoding process succeeds, the writer iterator will be moved
// to the next write-ready location. On the other hand if the scanned
// percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// these bytes should be copied to output as is.
// The decodeReader iterator is always moved to the first byte not yet
// be scanned after the process. A failed decoding means the chars
// between the reader and decodeReader can be copied to output untouched.
if (!DecodeCore(ref decodeIndex, ref destinationIndex, buffer))
{
Copy(sourceIndex, decodeIndex, ref destinationIndex, buffer);
}
sourceIndex = decodeIndex;
}
else
{
buffer[destinationIndex++] = buffer[sourceIndex++];
}
}
return destinationIndex;
}
/// <summary>
/// Unescape the percent-encodings
/// </summary>
/// <param name="sourceIndex">The iterator point to the first % char</param>
/// <param name="destinationIndex">The place to write to</param>
/// <param name="end">The end of the buffer</param>
/// <param name="buffer">The byte array</param>
private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Span<byte> buffer)
{
// preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// bytes from this till the last scanned one will be copied to the memory pointed by writer.
var byte1 = UnescapePercentEncoding(ref sourceIndex, buffer);
if (byte1 == -1)
{
return false;
}
if (byte1 == 0)
{
throw new InvalidOperationException("The path contains null characters.");
}
if (byte1 <= 0x7F)
{
// first byte < U+007f, it is a single byte ASCII
buffer[destinationIndex++] = (byte)byte1;
return true;
}
int byte2 = 0, byte3 = 0, byte4 = 0;
// anticipate more bytes
var currentDecodeBits = 0;
var byteCount = 1;
var expectValueMin = 0;
if ((byte1 & 0xE0) == 0xC0)
{
// 110x xxxx, expect one more byte
currentDecodeBits = byte1 & 0x1F;
byteCount = 2;
expectValueMin = 0x80;
}
else if ((byte1 & 0xF0) == 0xE0)
{
// 1110 xxxx, expect two more bytes
currentDecodeBits = byte1 & 0x0F;
byteCount = 3;
expectValueMin = 0x800;
}
else if ((byte1 & 0xF8) == 0xF0)
{
// 1111 0xxx, expect three more bytes
currentDecodeBits = byte1 & 0x07;
byteCount = 4;
expectValueMin = 0x10000;
}
else
{
// invalid first byte
return false;
}
var remainingBytes = byteCount - 1;
while (remainingBytes > 0)
{
// read following three chars
if (sourceIndex == buffer.Length)
{
return false;
}
var nextSourceIndex = sourceIndex;
var nextByte = UnescapePercentEncoding(ref nextSourceIndex, buffer);
if (nextByte == -1)
{
return false;
}
if ((nextByte & 0xC0) != 0x80)
{
// the follow up byte is not in form of 10xx xxxx
return false;
}
currentDecodeBits = (currentDecodeBits << 6) | (nextByte & 0x3F);
remainingBytes--;
if (remainingBytes == 1 && currentDecodeBits >= 0x360 && currentDecodeBits <= 0x37F)
{
// this is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that
// are not allowed in UTF-8;
return false;
}
if (remainingBytes == 2 && currentDecodeBits >= 0x110)
{
// this is going to be out of the upper Unicode bound 0x10FFFF.
return false;
}
sourceIndex = nextSourceIndex;
if (byteCount - remainingBytes == 2)
{
byte2 = nextByte;
}
else if (byteCount - remainingBytes == 3)
{
byte3 = nextByte;
}
else if (byteCount - remainingBytes == 4)
{
byte4 = nextByte;
}
}
if (currentDecodeBits < expectValueMin)
{
// overlong encoding (e.g. using 2 bytes to encode something that only needed 1).
return false;
}
// all bytes are verified, write to the output
// TODO: measure later to determine if the performance of following logic can be improved
// the idea is to combine the bytes into short/int and write to span directly to avoid
// range check cost
if (byteCount > 0)
{
buffer[destinationIndex++] = (byte)byte1;
}
if (byteCount > 1)
{
buffer[destinationIndex++] = (byte)byte2;
}
if (byteCount > 2)
{
buffer[destinationIndex++] = (byte)byte3;
}
if (byteCount > 3)
{
buffer[destinationIndex++] = (byte)byte4;
}
return true;
}
private static void Copy(int begin, int end, ref int writer, Span<byte> buffer)
{
while (begin != end)
{
buffer[writer++] = buffer[begin++];
}
}
/// <summary>
/// Read the percent-encoding and try unescape it.
///
/// The operation first peek at the character the <paramref name="scan"/>
/// iterator points at. If it is % the <paramref name="scan"/> is then
/// moved on to scan the following to characters. If the two following
/// characters are hexadecimal literals they will be unescaped and the
/// value will be returned.
///
/// If the first character is not % the <paramref name="scan"/> iterator
/// will be removed beyond the location of % and -1 will be returned.
///
/// If the following two characters can't be successfully unescaped the
/// <paramref name="scan"/> iterator will be move behind the % and -1
/// will be returned.
/// </summary>
/// <param name="scan">The value to read</param>
/// <param name="buffer">The byte array</param>
/// <returns>The unescaped byte if success. Otherwise return -1.</returns>
private static int UnescapePercentEncoding(ref int scan, Span<byte> buffer)
{
if (buffer[scan++] != '%')
{
return -1;
}
buffer = buffer.Slice(scan);
if (buffer.Length < 2)
{
return -1;
}
if (!Utf8Parser.TryParse(buffer.Slice(0, 2), out byte value, out var bytesConsumed, 'X'))
{
return -1;
}
if (bytesConsumed != 2)
{
return -1;
}
// skip %2F - '/'
if (value == 0x2F)
{
return -1;
}
scan += 2;
return value;
}
static UrlEncoder()
{
// Unreserved
IsAllowed['A'] = true;
IsAllowed['B'] = true;
IsAllowed['C'] = true;
IsAllowed['D'] = true;
IsAllowed['E'] = true;
IsAllowed['F'] = true;
IsAllowed['G'] = true;
IsAllowed['H'] = true;
IsAllowed['I'] = true;
IsAllowed['J'] = true;
IsAllowed['K'] = true;
IsAllowed['L'] = true;
IsAllowed['M'] = true;
IsAllowed['N'] = true;
IsAllowed['O'] = true;
IsAllowed['P'] = true;
IsAllowed['Q'] = true;
IsAllowed['R'] = true;
IsAllowed['S'] = true;
IsAllowed['T'] = true;
IsAllowed['U'] = true;
IsAllowed['V'] = true;
IsAllowed['W'] = true;
IsAllowed['X'] = true;
IsAllowed['Y'] = true;
IsAllowed['Z'] = true;
IsAllowed['a'] = true;
IsAllowed['b'] = true;
IsAllowed['c'] = true;
IsAllowed['d'] = true;
IsAllowed['e'] = true;
IsAllowed['f'] = true;
IsAllowed['g'] = true;
IsAllowed['h'] = true;
IsAllowed['i'] = true;
IsAllowed['j'] = true;
IsAllowed['k'] = true;
IsAllowed['l'] = true;
IsAllowed['m'] = true;
IsAllowed['n'] = true;
IsAllowed['o'] = true;
IsAllowed['p'] = true;
IsAllowed['q'] = true;
IsAllowed['r'] = true;
IsAllowed['s'] = true;
IsAllowed['t'] = true;
IsAllowed['u'] = true;
IsAllowed['v'] = true;
IsAllowed['w'] = true;
IsAllowed['x'] = true;
IsAllowed['y'] = true;
IsAllowed['z'] = true;
IsAllowed['0'] = true;
IsAllowed['1'] = true;
IsAllowed['2'] = true;
IsAllowed['3'] = true;
IsAllowed['4'] = true;
IsAllowed['5'] = true;
IsAllowed['6'] = true;
IsAllowed['7'] = true;
IsAllowed['8'] = true;
IsAllowed['9'] = true;
IsAllowed['-'] = true;
IsAllowed['_'] = true;
IsAllowed['.'] = true;
IsAllowed['~'] = true;
}
public static Utf8UriEncoder Utf8 { get; } = new Utf8UriEncoder();
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework.Api
{
/// <summary>
/// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite
/// containing test fixtures present in the assembly.
/// </summary>
public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder
{
static Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder));
#region Instance Fields
/// <summary>
/// The default suite builder used by the test assembly builder.
/// </summary>
ISuiteBuilder _defaultSuiteBuilder;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class.
/// </summary>
public DefaultTestAssemblyBuilder()
{
_defaultSuiteBuilder = new DefaultSuiteBuilder();
}
#endregion
#region Build Methods
/// <summary>
/// Build a suite of tests from a provided assembly
/// </summary>
/// <param name="assembly">The assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(Assembly assembly, IDictionary<string, object> options)
{
#if PORTABLE || NETSTANDARD1_6
log.Debug("Loading {0}", assembly.FullName);
#else
log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName);
#endif
#if PORTABLE
string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).FullName;
#else
string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly);
#endif
return Build(assembly, assemblyPath, options);
}
/// <summary>
/// Build a suite of tests given the filename of an assembly
/// </summary>
/// <param name="assemblyName">The filename of the assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(string assemblyName, IDictionary<string, object> options)
{
#if PORTABLE || NETSTANDARD1_6
log.Debug("Loading {0}", assemblyName);
#else
log.Debug("Loading {0} in AppDomain {1}", assemblyName, AppDomain.CurrentDomain.FriendlyName);
#endif
TestSuite testAssembly = null;
try
{
var assembly = AssemblyHelper.Load(assemblyName);
testAssembly = Build(assembly, assemblyName, options);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyName);
testAssembly.MakeInvalid(ExceptionHelper.BuildFriendlyMessage(ex));
}
return testAssembly;
}
private TestSuite Build(Assembly assembly, string assemblyPath, IDictionary<string, object> options)
{
TestSuite testAssembly = null;
try
{
if (options.ContainsKey(FrameworkPackageSettings.DefaultTestNamePattern))
TestNameGenerator.DefaultTestNamePattern = options[FrameworkPackageSettings.DefaultTestNamePattern] as string;
if (options.ContainsKey(FrameworkPackageSettings.WorkDirectory))
TestContext.DefaultWorkDirectory = options[FrameworkPackageSettings.WorkDirectory] as string;
else
TestContext.DefaultWorkDirectory =
#if PORTABLE
@"\My Documents";
#else
Directory.GetCurrentDirectory();
#endif
if (options.ContainsKey(FrameworkPackageSettings.TestParametersDictionary))
{
var testParametersDictionary = options[FrameworkPackageSettings.TestParametersDictionary] as IDictionary<string, string>;
if (testParametersDictionary != null)
{
foreach (var parameter in testParametersDictionary)
TestContext.Parameters.Add(parameter.Key, parameter.Value);
}
}
else
{
// This cannot be changed without breaking backwards compatibility with old runners.
// Deserializes the way old runners understand.
if (options.ContainsKey(FrameworkPackageSettings.TestParameters))
{
string parameters = options[FrameworkPackageSettings.TestParameters] as string;
if (!string.IsNullOrEmpty(parameters))
foreach (string param in parameters.Split(new[] { ';' }))
{
int eq = param.IndexOf("=");
if (eq > 0 && eq < param.Length - 1)
{
var name = param.Substring(0, eq);
var val = param.Substring(eq + 1);
TestContext.Parameters.Add(name, val);
}
}
}
}
IList fixtureNames = null;
if (options.ContainsKey(FrameworkPackageSettings.LOAD))
fixtureNames = options[FrameworkPackageSettings.LOAD] as IList;
var fixtures = GetFixtures(assembly, fixtureNames);
testAssembly = BuildTestAssembly(assembly, assemblyPath, fixtures);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyPath);
testAssembly.MakeInvalid(ExceptionHelper.BuildFriendlyMessage(ex));
}
return testAssembly;
}
#endregion
#region Helper Methods
private IList<Test> GetFixtures(Assembly assembly, IList names)
{
var fixtures = new List<Test>();
log.Debug("Examining assembly for test fixtures");
var testTypes = GetCandidateFixtureTypes(assembly, names);
log.Debug("Found {0} classes to examine", testTypes.Count);
#if LOAD_TIMING
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
#endif
int testcases = 0;
foreach (Type testType in testTypes)
{
var typeInfo = new TypeWrapper(testType);
try
{
if (_defaultSuiteBuilder.CanBuildFrom(typeInfo))
{
Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo);
fixtures.Add(fixture);
testcases += fixture.TestCaseCount;
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
#if LOAD_TIMING
log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed);
#else
log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases);
#endif
return fixtures;
}
private IList<Type> GetCandidateFixtureTypes(Assembly assembly, IList names)
{
var types = assembly.GetTypes();
if (names == null || names.Count == 0)
return types;
var result = new List<Type>();
foreach (string name in names)
{
Type fixtureType = assembly.GetType(name);
if (fixtureType != null)
result.Add(fixtureType);
else
{
string prefix = name + ".";
foreach (Type type in types)
if (type.FullName.StartsWith(prefix))
result.Add(type);
}
}
return result;
}
#if !PORTABLE
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
#endif
private TestSuite BuildTestAssembly(Assembly assembly, string assemblyName, IList<Test> fixtures)
{
TestSuite testAssembly = new TestAssembly(assembly, assemblyName);
if (fixtures.Count == 0)
{
testAssembly.MakeInvalid("Has no TestFixtures");
}
else
{
NamespaceTreeBuilder treeBuilder =
new NamespaceTreeBuilder(testAssembly);
treeBuilder.Add(fixtures);
testAssembly = treeBuilder.RootSuite;
}
testAssembly.ApplyAttributesToTest(assembly);
#if !PORTABLE && !NETSTANDARD1_6
testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id);
testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName);
#endif
// TODO: Make this an option? Add Option to sort assemblies as well?
testAssembly.Sort();
return testAssembly;
}
#endregion
}
}
| |
// 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.ComponentModel;
using System.Runtime.InteropServices;
namespace Carbon.Service
{
// ReSharper disable InconsistentNaming
public sealed class ServiceInfo
{
public ServiceInfo(string name) : this(name, null)
{
}
public ServiceInfo(string name, string computerName)
{
var databaseHandle = OpenSCManager(computerName, null, SC_MANAGER_CONNECT);
if (databaseHandle == IntPtr.Zero)
{
throw new Win32Exception();
}
var serviceHandle = OpenService(databaseHandle, name, SERVICE_QUERY_CONFIG);
if (serviceHandle == IntPtr.Zero)
{
throw new Win32Exception();
}
Name = name;
SetServiceInfo(serviceHandle);
SetDelayedAutoStart(serviceHandle);
SetDescription(serviceHandle);
SetFailureActions(serviceHandle);
CloseServiceHandle(databaseHandle);
CloseServiceHandle(serviceHandle);
}
private void SetServiceInfo(IntPtr serviceHandle)
{
UInt32 dwBytesNeeded;
// Allocate memory for struct.
var ptr = Marshal.AllocHGlobal(4096);
QueryServiceConfig(serviceHandle, ptr, 4096, out dwBytesNeeded);
var config = new QUERY_SERVICE_CONFIG();
// Copy
Marshal.PtrToStructure(ptr, config);
// Free memory for struct.
Marshal.FreeHGlobal(ptr);
UserName = config.lpServiceStartName.Trim('"');
Path = config.lpBinaryPathName;
ErrorControl = (ErrorControl) config.dwErrorControl;
LoadOrderGroup = config.lpLoadOrderGroup;
TagID = config.dwTagID;
StartType = (StartType) config.dwStartType;
}
public bool DelayedAutoStart { get; private set; }
public string Description { get; private set; }
public string FailureProgram { get; private set; }
public ErrorControl ErrorControl { get; private set; }
public FailureAction FirstFailure { get; private set; }
public string LoadOrderGroup { get; private set; }
public string Name { get; private set; }
public string Path { get; private set; }
public uint ResetPeriod { get; private set; }
public uint ResetPeriodDays
{
get
{
if (ResetPeriod == 0)
{
return 0;
}
return ResetPeriod/24/60/60;
}
}
public uint RestartDelay { get; private set; }
public uint RestartDelayMinutes
{
get { return ConvertToMinutes(RestartDelay); }
}
public uint RebootDelay { get; private set; }
public uint RebootDelayMinutes
{
get { return ConvertToMinutes(RebootDelay); }
}
public uint RunCommandDelay { get; private set; }
public uint RunCommandDelayMinutes
{
get { return ConvertToMinutes(RunCommandDelay); }
}
public FailureAction SecondFailure { get; private set; }
public StartType StartType { get; private set; }
public uint TagID { get; private set; }
public FailureAction ThirdFailure { get; private set; }
public string UserName { get; private set; }
private uint ConvertToMinutes(uint restartDelay)
{
if (restartDelay == 0)
return 0;
return restartDelay / 1000 / 60;
}
private void SetDelayedAutoStart(IntPtr serviceHandle)
{
UInt32 dwBytesNeeded;
// Determine the buffer size needed
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_DELAYED_AUTO_START, IntPtr.Zero, 0, out dwBytesNeeded);
var ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_DELAYED_AUTO_START, ptr, dwBytesNeeded, out dwBytesNeeded);
var delayedAutoStartStruct = new SERVICE_DELAYED_AUTO_START_INFO();
Marshal.PtrToStructure(ptr, delayedAutoStartStruct);
Marshal.FreeHGlobal(ptr);
DelayedAutoStart = delayedAutoStartStruct.fDelayedAutostart;
}
private void SetDescription(IntPtr serviceHandle)
{
UInt32 dwBytesNeeded;
// Determine the buffer size needed
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_DESCRIPTION, IntPtr.Zero, 0, out dwBytesNeeded);
var ptr = Marshal.AllocHGlobal((int) dwBytesNeeded);
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_DESCRIPTION, ptr, dwBytesNeeded, out dwBytesNeeded);
var descriptionStruct = new SERVICE_DESCRIPTION();
Marshal.PtrToStructure(ptr, descriptionStruct);
Marshal.FreeHGlobal(ptr);
Description = descriptionStruct.lpDescription;
}
private void SetFailureActions(IntPtr serviceHandle)
{
UInt32 dwBytesNeeded;
// Determine the buffer size needed
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, IntPtr.Zero, 0, out dwBytesNeeded);
var ptr = Marshal.AllocHGlobal((int) dwBytesNeeded);
QueryServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, ptr, dwBytesNeeded, out dwBytesNeeded);
var failureActions = new SERVICE_FAILURE_ACTIONS();
Marshal.PtrToStructure(ptr, failureActions);
// Report it.
ResetPeriod = (UInt32) failureActions.dwResetPeriod;
FailureProgram = failureActions.lpCommand;
var offset = 0;
for (var i = 0; i < failureActions.cActions; i++)
{
var type = (FailureAction)Marshal.ReadInt32(failureActions.lpsaActions, offset);
offset += sizeof(Int32);
var delay = (UInt32)Marshal.ReadInt32(failureActions.lpsaActions, offset);
offset += sizeof(Int32);
if (i == 0)
{
FirstFailure = type;
}
else if(i == 1)
{
SecondFailure = type;
}
else if (i == 2)
{
ThirdFailure = type;
}
switch (type)
{
case( FailureAction.RunCommand ):
RunCommandDelay = delay;
break;
case( FailureAction.Reboot):
RebootDelay = delay;
break;
case( FailureAction.Restart):
RestartDelay = delay;
break;
}
}
Marshal.FreeHGlobal(ptr);
}
#region P/Invoke declarations
#pragma warning disable 649
#pragma warning disable 169
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class SERVICE_DELAYED_AUTO_START_INFO
{
public bool fDelayedAutostart;
}
[StructLayout(LayoutKind.Sequential)]
private class SERVICE_DESCRIPTION
{
[MarshalAs(UnmanagedType.LPWStr)] public String lpDescription;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private class SERVICE_FAILURE_ACTIONS
{
public int dwResetPeriod;
[MarshalAs(UnmanagedType.LPWStr)] public string lpRebootMsg;
[MarshalAs(UnmanagedType.LPWStr)] public string lpCommand;
public int cActions;
public IntPtr lpsaActions;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr OpenSCManager(String lpMachineName, String lpDatabaseName, UInt32 dwDesiredAccess);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseServiceHandle(IntPtr hSCObject);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr OpenService(IntPtr hSCManager, String lpServiceName, UInt32 dwDesiredAccess);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "QueryServiceConfig2W")]
private static extern Boolean QueryServiceConfig2(IntPtr hService, UInt32 dwInfoLevel, IntPtr buffer, UInt32 cbBufSize,
out UInt32 pcbBytesNeeded);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern Boolean QueryServiceConfig(IntPtr hService, IntPtr intPtrQueryConfig, UInt32 cbBufSize, out UInt32 pcbBytesNeeded);
private const Int32 SC_MANAGER_CONNECT = 0x00000001;
private const Int32 SERVICE_QUERY_CONFIG = 0x00000001;
private const UInt32 SERVICE_CONFIG_DESCRIPTION = 0x01;
private const UInt32 SERVICE_CONFIG_FAILURE_ACTIONS = 0x02;
private const UInt32 SERVICE_CONFIG_DELAYED_AUTO_START = 0x3;
[StructLayout(LayoutKind.Sequential)]
private class QUERY_SERVICE_CONFIG
{
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwServiceType;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwStartType;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwErrorControl;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpBinaryPathName;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpLoadOrderGroup;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTagID;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpDependencies;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpServiceStartName;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpDisplayName;
};
#pragma warning restore 169
#pragma warning restore 649
#endregion // P/Invoke declarations
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using BenchmarkDotNet.Extensions;
namespace BenchmarkDotNet.Environments
{
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class OsBrandStringHelper
{
// See https://en.wikipedia.org/wiki/Ver_(command)
// See https://docs.microsoft.com/en-us/windows/release-health/release-information
// See https://docs.microsoft.com/en-us/windows/release-health/windows11-release-information
private static readonly Dictionary<string, string> WindowsBrandVersions = new Dictionary<string, string>
{
{ "1.04", "1.0" },
{ "2.11", "2.0" },
{ "3", "3.0" },
{ "3.10.528", "NT 3.1" },
{ "3.11", "for Workgroups 3.11" },
{ "3.50.807", "NT 3.5" },
{ "3.51.1057", "NT 3.51" },
{ "4.00.950", "95" },
{ "4.00.1111", "95 OSR2" },
{ "4.03.1212-1214", "95 OSR2.1" },
{ "4.03.1214", "95 OSR2.5" },
{ "4.00.1381", "NT 4.0" },
{ "4.10.1998", "98" },
{ "4.10.2222", "98 SE" },
{ "4.90.2380.2", "ME Beta" },
{ "4.90.2419", "ME Beta 2" },
{ "4.90.3000", "ME" },
{ "5.00.1515", "NT 5.0 Beta" },
{ "5.00.2031", "2000 Beta 3" },
{ "5.00.2128", "2000 RC2" },
{ "5.00.2183", "2000 RC3" },
{ "5.00.2195", "2000" },
{ "5.0.2195", "2000 Professional" },
{ "5.1.2505", "XP RC1" },
{ "5.1.2600", "XP" },
{ "5.1.2600.1105-1106", "XP SP1" },
{ "5.1.2600.2180", "XP SP2" },
{ "5.2.3541", ".NET Server interim" },
{ "5.2.3590", ".NET Server Beta 3" },
{ "5.2.3660", ".NET Server RC1" },
{ "5.2.3718", ".NET Server 2003 RC2" },
{ "5.2.3763", "Server 2003 Beta" },
{ "5.2.3790", "XP Professional x64 Edition" },
{ "5.2.3790.1180", "Server 2003 SP1" },
{ "5.2.3790.1218", "Server 2003" },
{ "6.0.5048", "Longhorn" },
{ "6.0.5112", "Vista Beta 1" },
{ "6.0.5219", "Vista CTP" },
{ "6.0.5259", "Vista TAP Preview" },
{ "6.0.5270", "Vista CTP December" },
{ "6.0.5308", "Vista CTP February" },
{ "6.0.5342", "Vista CTP Refresh" },
{ "6.0.5365", "Vista April EWD" },
{ "6.0.5381", "Vista Beta 2 Preview" },
{ "6.0.5384", "Vista Beta 2" },
{ "6.0.5456", "Vista Pre-RC1 Build 5456" },
{ "6.0.5472", "Vista Pre-RC1 Build 5472" },
{ "6.0.5536", "Vista Pre-RC1 Build 5536" },
{ "6.0.5600.16384", "Vista RC1" },
{ "6.0.5700", "Vista Pre-RC2" },
{ "6.0.5728", "Vista Pre-RC2 Build 5728" },
{ "6.0.5744.16384", "Vista RC2" },
{ "6.0.5808", "Vista Pre-RTM Build 5808" },
{ "6.0.5824", "Vista Pre-RTM Build 5824" },
{ "6.0.5840", "Vista Pre-RTM Build 5840" },
{ "6.0.6000", "Vista" },
{ "6.0.6000.16386", "Vista RTM" },
{ "6.0.6001", "Vista SP1" },
{ "6.0.6002", "Vista SP2" },
{ "6.1.7600", "7" },
{ "6.1.7600.16385", "7" },
{ "6.1.7601", "7 SP1" },
{ "6.1.8400", "Home Server 2011" },
{ "6.2.8102", "8 Developer Preview" },
{ "6.2.9200", "8" },
{ "6.2.9200.16384", "8 RTM" },
{ "6.2.10211", "Phone 8" },
{ "6.3.9600", "8.1" },
{ "6.4.9841", "10 Technical Preview 1" },
{ "6.4.9860", "10 Technical Preview 2" },
{ "6.4.9879", "10 Technical Preview 3" },
{ "10.0.9926", "10 Technical Preview 4" },
{ "10.0.10041", "10 Technical Preview 5" },
{ "10.0.10049", "10 Technical Preview 6" },
{ "10.0.10240", "10 Threshold 1 [1507, RTM]" },
{ "10.0.10586", "10 Threshold 2 [1511, November Update]" },
{ "10.0.14393", "10 Redstone 1 [1607, Anniversary Update]" },
{ "10.0.15063", "10 Redstone 2 [1703, Creators Update]" },
{ "10.0.16299", "10 Redstone 3 [1709, Fall Creators Update]" },
{ "10.0.17134", "10 Redstone 4 [1803, April 2018 Update]" },
{ "10.0.17763", "10 Redstone 5 [1809, October 2018 Update]" },
{ "10.0.18362", "10 19H1 [1903, May 2019 Update]" },
{ "10.0.18363", "10 19H2 [1909, November 2019 Update]" },
{ "10.0.19041", "10 20H1 [2004, May 2020 Update]" },
{ "10.0.19042", "10 20H2 [20H2, October 2020 Update]" },
{ "10.0.19043", "10 21H1 [21H1, May 2021 Update]" },
{ "10.0.19044", "10 21H2 [21H2, November 2021 Update]" },
{ "10.0.22000", "11 21H2 [21H2]" },
};
private class Windows1XVersion
{
[CanBeNull] private string CodeVersion { get; }
[CanBeNull] private string CodeName { get; }
[CanBeNull] private string MarketingName { get; }
private int BuildNumber { get; }
[NotNull] private string MarketingNumber => BuildNumber >= 22000 ? "11" : "10";
[CanBeNull] private string ShortifiedCodeName => CodeName?.Replace(" ", "");
[CanBeNull] private string ShortifiedMarketingName => MarketingName?.Replace(" ", "");
private Windows1XVersion([CanBeNull] string codeVersion, [CanBeNull] string codeName, [CanBeNull] string marketingName, int buildNumber)
{
CodeVersion = codeVersion;
CodeName = codeName;
MarketingName = marketingName;
BuildNumber = buildNumber;
}
private string ToFullVersion([CanBeNull] int? ubr = null)
=> ubr == null ? $"10.0.{BuildNumber}" : $"10.0.{BuildNumber}.{ubr}";
private static string Collapse(params string[] values) => string.Join("/", values.Where(v => !string.IsNullOrEmpty(v)));
// The line with OsBrandString is one of the longest lines in the summary.
// When people past in on GitHub, it can be a reason of an ugly horizontal scrollbar.
// To avoid this, we are trying to minimize this line and use the minimum possible number of characters.
public string ToPrettifiedString([CanBeNull] int? ubr)
=> CodeVersion == ShortifiedCodeName
? $"{MarketingNumber} ({Collapse(ToFullVersion(ubr), CodeVersion, ShortifiedMarketingName)})"
: $"{MarketingNumber} ({Collapse(ToFullVersion(ubr), CodeVersion, ShortifiedMarketingName, ShortifiedCodeName)})";
// See https://en.wikipedia.org/wiki/Windows_10_version_history
// See https://en.wikipedia.org/wiki/Windows_11_version_history
private static readonly List<Windows1XVersion> WellKnownVersions = new ()
{
// Windows 10
new Windows1XVersion("1507", "Threshold 1", "RTM", 10240),
new Windows1XVersion("1511", "Threshold 2", "November Update", 10586),
new Windows1XVersion("1607", "Redstone 1", "Anniversary Update", 14393),
new Windows1XVersion("1703", "Redstone 2", "Creators Update", 15063),
new Windows1XVersion("1709", "Redstone 3", "Fall Creators Update", 16299),
new Windows1XVersion("1803", "Redstone 4", "April 2018 Update", 17134),
new Windows1XVersion("1809", "Redstone 5", "October 2018 Update", 17763),
new Windows1XVersion("1903", "19H1", "May 2019 Update", 18362),
new Windows1XVersion("1909", "19H2", "November 2019 Update", 18363),
new Windows1XVersion("2004", "20H1", "May 2020 Update", 19041),
new Windows1XVersion("20H2", "20H2", "October 2020 Update", 19042),
new Windows1XVersion("21H1", "21H1", "May 2021 Update", 19043),
new Windows1XVersion("21H2", "21H2", "November 2021 Update", 19044),
new Windows1XVersion("21H2", "21H2", "November 2021 Update", 19044),
// Windows 11
new Windows1XVersion("21H2", "21H2", null, 22000),
};
[CanBeNull]
public static Windows1XVersion Resolve([NotNull] string osVersionString)
{
var windows1XVersion = WellKnownVersions.FirstOrDefault(v => osVersionString == $"10.0.{v.BuildNumber}");
if (windows1XVersion != null)
return windows1XVersion;
if (Version.TryParse(osVersionString, out var osVersion))
{
if (osVersion.Major == 10 && osVersion.Minor == 0)
return new Windows1XVersion(null, null, null, osVersion.Build);
}
return null;
}
}
/// <summary>
/// Transform an operation system name and version to a nice form for summary.
/// </summary>
/// <param name="osName">Original operation system name</param>
/// <param name="osVersion">Original operation system version</param>
/// <param name="windowsUbr">UBR (Update Build Revision), the revision number of Windows version (if available)</param>
/// <returns>Prettified operation system title</returns>
[NotNull]
public static string Prettify([NotNull] string osName, [NotNull] string osVersion, [CanBeNull] int? windowsUbr = null)
{
if (osName == "Windows")
return PrettifyWindows(osVersion, windowsUbr);
return $"{osName} {osVersion}";
}
[NotNull]
private static string PrettifyWindows([NotNull] string osVersion, [CanBeNull] int? windowsUbr)
{
var windows1XVersion = Windows1XVersion.Resolve(osVersion);
if (windows1XVersion != null)
return "Windows " + windows1XVersion.ToPrettifiedString(windowsUbr);
string brandVersion = WindowsBrandVersions.GetValueOrDefault(osVersion);
string completeOsVersion = windowsUbr != null && osVersion.Count(c => c == '.') == 2
? osVersion + "." + windowsUbr
: osVersion;
string fullVersion = brandVersion == null ? osVersion : brandVersion + " (" + completeOsVersion + ")";
return "Windows " + fullVersion;
}
private class MacOSXVersion
{
private int DarwinVersion { get; }
[NotNull]private string CodeName { get; }
private MacOSXVersion(int darwinVersion, [NotNull] string codeName)
{
DarwinVersion = darwinVersion;
CodeName = codeName;
}
private static readonly List<MacOSXVersion> WellKnownVersions = new List<MacOSXVersion>
{
new MacOSXVersion(6, "Jaguar"),
new MacOSXVersion(7, "Panther"),
new MacOSXVersion(8, "Tiger"),
new MacOSXVersion(9, "Leopard"),
new MacOSXVersion(10, "Snow Leopard"),
new MacOSXVersion(11, "Lion"),
new MacOSXVersion(12, "Mountain Lion"),
new MacOSXVersion(13, "Mavericks"),
new MacOSXVersion(14, "Yosemite"),
new MacOSXVersion(15, "El Capitan"),
new MacOSXVersion(16, "Sierra"),
new MacOSXVersion(17, "High Sierra"),
new MacOSXVersion(18, "Mojave"),
new MacOSXVersion(19, "Catalina"),
new MacOSXVersion(20, "Big Sur"),
new MacOSXVersion(21, "Monterey")
};
[CanBeNull]
public static string ResolveCodeName([NotNull] string kernelVersion)
{
if (string.IsNullOrWhiteSpace(kernelVersion))
return null;
kernelVersion = kernelVersion.ToLowerInvariant().Trim();
if (kernelVersion.StartsWith("darwin"))
kernelVersion = kernelVersion.Substring(6).Trim();
var numbers = kernelVersion.Split('.');
if (numbers.Length == 0)
return null;
string majorVersionStr = numbers[0];
if (int.TryParse(majorVersionStr, out int majorVersion))
return WellKnownVersions.FirstOrDefault(v => v.DarwinVersion == majorVersion)?.CodeName;
return null;
}
}
[NotNull]
public static string PrettifyMacOSX([NotNull] string systemVersion, [NotNull] string kernelVersion)
{
string codeName = MacOSXVersion.ResolveCodeName(kernelVersion);
if (codeName != null)
{
int firstDigitIndex = systemVersion.IndexOfAny("0123456789".ToCharArray());
if (firstDigitIndex == -1)
return $"{systemVersion} {codeName} [{kernelVersion}]";
string systemVersionTitle = systemVersion.Substring(0, firstDigitIndex).Trim();
string systemVersionNumbers = systemVersion.Substring(firstDigitIndex).Trim();
return $"{systemVersionTitle} {codeName} {systemVersionNumbers} [{kernelVersion}]";
}
return $"{systemVersion} [{kernelVersion}]";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Marten.NodaTime.Testing.TestData;
using Marten.Testing.Events.Projections;
using Marten.Testing.Harness;
using NodaTime;
using Shouldly;
using Weasel.Postgresql;
using Xunit;
namespace Marten.NodaTime.Testing.Acceptance
{
[Collection("noda_time_integration")]
public class noda_time_acceptance: OneOffConfigurationsContext
{
public void noda_time_default_setup()
{
#region sample_noda_time_default_setup
var store = DocumentStore.For(_ =>
{
_.Connection(ConnectionSource.ConnectionString);
// sets up NodaTime handling
_.UseNodaTime();
});
#endregion sample_noda_time_default_setup
}
public void noda_time_setup_without_json_net_serializer_configuration()
{
#region sample_noda_time_setup_without_json_net_serializer_configuration
var store = DocumentStore.For(_ =>
{
_.Connection(ConnectionSource.ConnectionString);
_.Serializer<CustomJsonSerializer>();
// sets up NodaTime handling
_.UseNodaTime(shouldConfigureJsonNetSerializer: false);
});
#endregion sample_noda_time_setup_without_json_net_serializer_configuration
}
[Fact]
public void can_insert_document()
{
StoreOptions(_ => _.UseNodaTime());
var testDoc = TargetWithDates.Generate();
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var docFromDb = query.Query<TargetWithDates>().FirstOrDefault(d => d.Id == testDoc.Id);
docFromDb.ShouldNotBeNull();
docFromDb.Equals(testDoc).ShouldBeTrue();
}
}
//[Fact]
public void can_query_document_with_noda_time_types()
{
StoreOptions(_ =>
{
_.UseNodaTime();
_.DatabaseSchemaName = "NodaTime";
});
var dateTime = DateTime.UtcNow;
var localDateTime = LocalDateTime.FromDateTime(dateTime);
var instantUTC = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
var testDoc = TargetWithDates.Generate(dateTime);
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var results = new List<TargetWithDates>
{
// LocalDate
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate == localDateTime.Date),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate < localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate <= localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate > localDateTime.Date.PlusDays(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate >= localDateTime.Date.PlusDays(-1)),
//// Nullable LocalDate
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate == localDateTime.Date),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate < localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate <= localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate > localDateTime.Date.PlusDays(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate >= localDateTime.Date.PlusDays(-1)),
/*
//// LocalDateTime
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime == localDateTime),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime < localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime <= localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime > localDateTime.PlusSeconds(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime >= localDateTime.PlusSeconds(-1)),
//// Nullable LocalDateTime
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime == localDateTime),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime < localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime <= localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime > localDateTime.PlusSeconds(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime >= localDateTime.PlusSeconds(-1)),
//// Instant UTC
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC == instantUTC),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC < instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC <= instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC > instantUTC.PlusTicks(-1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC >= instantUTC.PlusTicks(-1000)),
// Nullable Instant UTC
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC == instantUTC),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC < instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC <= instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC > instantUTC.PlusTicks(-1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC >= instantUTC.PlusTicks(-1000))
*/
};
results.ToArray().ShouldAllBe(x => x.Equals(testDoc));
}
}
[Fact]
public async Task can_append_and_query_events()
{
StoreOptions(_ => _.UseNodaTime());
var startDate = DateTime.UtcNow;
var streamId = Guid.NewGuid();
var @event = new MonsterSlayed()
{
QuestId = Guid.NewGuid(),
Name = "test"
};
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, @event);
session.SaveChanges();
var streamState = session.Events.FetchStreamState(streamId);
var streamState2 = await session.Events.FetchStreamStateAsync(streamId);
var streamState3 = session.Events.FetchStream(streamId, timestamp: startDate);
}
}
[Fact]
public void bug_1276_can_select_instant()
{
StoreOptions(_ => _.UseNodaTime());
var dateTime = DateTime.UtcNow;
var instantUTC = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
var testDoc = TargetWithDates.Generate(dateTime);
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var resulta = query.Query<TargetWithDates>()
.Where(c => c.Id == testDoc.Id)
.Single();
var result = query.Query<TargetWithDates>()
.Where(c => c.Id == testDoc.Id)
.Select(c => new { c.Id, c.InstantUTC })
.Single();
result.ShouldNotBeNull();
result.Id.ShouldBe(testDoc.Id);
ShouldBeEqualWithDbPrecision(result.InstantUTC, instantUTC);
}
}
private class CustomJsonSerializer: ISerializer
{
public EnumStorage EnumStorage => throw new NotImplementedException();
public Casing Casing => throw new NotImplementedException();
public CollectionStorage CollectionStorage => throw new NotImplementedException();
public NonPublicMembersStorage NonPublicMembersStorage => throw new NotImplementedException();
public string ToJsonWithTypes(object document)
{
throw new NotImplementedException();
}
public ValueCasting ValueCasting { get; } = ValueCasting.Relaxed;
public T FromJson<T>(Stream stream)
{
throw new NotImplementedException();
}
public T FromJson<T>(DbDataReader reader, int index)
{
throw new NotImplementedException();
}
public ValueTask<T> FromJsonAsync<T>(Stream stream, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public ValueTask<T> FromJsonAsync<T>(DbDataReader reader, int index, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public object FromJson(Type type, Stream stream)
{
throw new NotImplementedException();
}
public object FromJson(Type type, DbDataReader reader, int index)
{
throw new NotImplementedException();
}
public ValueTask<object> FromJsonAsync(Type type, Stream stream, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public ValueTask<object> FromJsonAsync(Type type, DbDataReader reader, int index, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public string ToCleanJson(object document)
{
throw new NotImplementedException();
}
public string ToJson(object document)
{
throw new NotImplementedException();
}
}
private static void ShouldBeEqualWithDbPrecision(Instant actual, Instant expected)
{
static Instant toDbPrecision(Instant date) => Instant.FromUnixTimeMilliseconds(date.ToUnixTimeMilliseconds() / 100 * 100);
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public noda_time_acceptance() : base("noda_time_integration")
{
}
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201505;
using Google.Api.Ads.Dfp.v201505;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201505 {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
[TestFixture]
public class LineItemServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
private LineItemService lineItemService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Placement id for running tests.
/// </summary>
private long placementId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Line item 1 for running tests.
/// </summary>
private LineItem lineItem1;
/// <summary>
/// Line item 2 for running tests.
/// </summary>
private LineItem lineItem2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
lineItemService = (LineItemService)user.GetService(DfpService.v201505.LineItemService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
placementId = utils.CreatePlacement(user, new string[] {adUnitId}).id;
lineItem1 = utils.CreateLineItem(user, orderId, adUnitId);
lineItem2 = utils.CreateLineItem(user, orderId, adUnitId);
}
/// <summary>
/// Test whether we can create a list of line items.
/// </summary>
[Test]
public void TestCreateLineItems() {
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = new long[] {placementId};
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201505.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201505.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
// Create an array to store local line item objects.
LineItem[] lineItems = new LineItem[2];
for (int i = 0; i < lineItems.Length; i++) {
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the line item to run for one month.
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime =
DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.units = 500000L;
goal.unitType = UnitType.IMPRESSIONS;
lineItem.primaryGoal = goal;
lineItems[i] = lineItem;
}
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.createLineItems(lineItems);
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);
Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
}
/// <summary>
/// Test whether we can fetch a list of existing line items that match given
/// statement.
/// </summary>
[Test]
public void TestGetLineItemsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", lineItem1.id);
LineItemPage page = null;
Assert.DoesNotThrow(delegate() {
page = lineItemService.getLineItemsByStatement(statement);
});
Assert.NotNull(page);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results);
Assert.AreEqual(page.results[0].id, lineItem1.id);
Assert.AreEqual(page.results[0].name, lineItem1.name);
Assert.AreEqual(page.results[0].orderId, lineItem1.orderId);
}
/// <summary>
/// Test whether we can activate a line item.
/// </summary>
[Test]
public void TestPerformLineItemAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE orderId = '{0}' and status = '{1}'",
orderId, ComputedStatus.INACTIVE);
ActivateLineItems action = new ActivateLineItems();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = lineItemService.performLineItemAction(action, statement);
});
Assert.NotNull(result);
}
/// <summary>
/// Test whether we can update a list of line items.
/// </summary>
[Test]
public void TestUpdateLineItems() {
lineItem1.costPerUnit.microAmount = 3500000;
lineItem2.costPerUnit.microAmount = 3500000;
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.updateLineItems(new LineItem[] {lineItem1, lineItem2});
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].id, lineItem1.id);
Assert.AreEqual(localLineItems[0].name, lineItem1.name);
Assert.AreEqual(localLineItems[0].orderId, lineItem1.orderId);
Assert.AreEqual(localLineItems[0].costPerUnit.microAmount, lineItem1.costPerUnit.microAmount);
Assert.AreEqual(localLineItems[1].id, lineItem2.id);
Assert.AreEqual(localLineItems[1].name, lineItem2.name);
Assert.AreEqual(localLineItems[1].orderId, lineItem2.orderId);
Assert.AreEqual(localLineItems[1].costPerUnit.microAmount, lineItem2.costPerUnit.microAmount);
}
}
}
| |
// 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.Text;
using Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Theory]
[InlineData("a", "a", 'a', 0)]
[InlineData("ab", "a", 'a', 0)]
[InlineData("aab", "a", 'a', 0)]
[InlineData("acab", "a", 'a', 0)]
[InlineData("acab", "c", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaalmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'm', 12)]
[InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 11)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", '?', 27)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)]
public static void IndexOfAnyStrings_Byte(string raw, string search, char expectResult, int expectIndex)
{
byte[] buffers = Encoding.UTF8.GetBytes(raw);
var span = new Span<byte>(buffers);
char[] searchFor = search.ToCharArray();
byte[] searchForBytes = Encoding.UTF8.GetBytes(searchFor);
var index = span.IndexOfAny(new ReadOnlySpan<byte>(searchForBytes));
if (searchFor.Length == 1)
{
Assert.Equal(index, span.IndexOf((byte)searchFor[0]));
}
else if (searchFor.Length == 2)
{
Assert.Equal(index, span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1]));
}
else if (searchFor.Length == 3)
{
Assert.Equal(index, span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1], (byte)searchFor[2]));
}
var found = span[index];
Assert.Equal((byte)expectResult, found);
Assert.Equal(expectIndex, index);
}
[Fact]
public static void ZeroLengthIndexOfTwo_Byte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
int idx = sp.IndexOfAny<byte>(0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfTwo_Byte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
byte[] targets = { default, 99 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchTwo_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = 0;
byte target1 = a[targetIndex + 1];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchTwo_Byte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
Span<byte> span = new Span<byte>(a);
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchTwo_Byte()
{
for (int length = 3; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
Span<byte> span = new Span<byte>(a);
int idx = span.IndexOfAny<byte>(200, 200);
Assert.Equal(length - 3, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeTwo_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.IndexOfAny<byte>(99, 98);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.IndexOfAny<byte>(99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfThree_Byte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
int idx = sp.IndexOfAny<byte>(0, 0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfThree_Byte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
byte[] targets = { default, 99, 98 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
byte target2 = targets[(index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchThree_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
byte target2 = 0;
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
byte target2 = a[targetIndex + 2];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = 0;
byte target1 = 0;
byte target2 = a[targetIndex + 2];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
}
}
[Fact]
public static void TestNoMatchThree_Byte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
byte target2 = (byte)rnd.Next(1, 256);
Span<byte> span = new Span<byte>(a);
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchThree_Byte()
{
for (int length = 4; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
Span<byte> span = new Span<byte>(a);
int idx = span.IndexOfAny<byte>(200, 200, 200);
Assert.Equal(length - 4, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeThree_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.IndexOfAny<byte>(99, 98, 99);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.IndexOfAny<byte>(99, 99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfMany_Byte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, 0 });
int idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<byte>(new byte[] { });
idx = sp.IndexOfAny(values);
Assert.Equal(0, idx);
}
[Fact]
public static void DefaultFilledIndexOfMany_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { default, 99, 98, 0 });
for (int i = 0; i < length; i++)
{
int idx = span.IndexOfAny(values);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchMany_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], 0, 0, 0 });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, a[targetIndex + 3] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerMany_Byte()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
continue;
}
a[i] = 255;
}
Span<byte> span = new Span<byte>(a);
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
continue;
}
targets[i] = (byte)rnd.Next(1, 255);
}
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchMany_Byte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerMany_Byte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchMany_Byte()
{
for (int length = 5; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
a[length - 5] = 200;
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 });
int idx = span.IndexOfAny(values);
Assert.Equal(length - 5, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeMany_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 98, 99, 98, 99, 98 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 99, 99, 99, 99, 99 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
}
}
}
| |
using System;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Parameters;
using Raksha.Security;
namespace Raksha.Crypto.Signers
{
/// <summary> RSA-PSS as described in Pkcs# 1 v 2.1.
/// <p>
/// Note: the usual value for the salt length is the number of
/// bytes in the hash function.</p>
/// </summary>
public class PssSigner
: ISigner
{
public const byte TrailerImplicit = (byte)0xBC;
private readonly IDigest contentDigest1, contentDigest2;
private readonly IDigest mgfDigest;
private readonly IAsymmetricBlockCipher cipher;
private SecureRandom random;
private int hLen;
private int mgfhLen;
private int sLen;
private int emBits;
private byte[] salt;
private byte[] mDash;
private byte[] block;
private byte trailer;
public static PssSigner CreateRawSigner(
IAsymmetricBlockCipher cipher,
IDigest digest)
{
return new PssSigner(cipher, new NullDigest(), digest, digest, digest.GetDigestSize(), TrailerImplicit);
}
public static PssSigner CreateRawSigner(
IAsymmetricBlockCipher cipher,
IDigest contentDigest,
IDigest mgfDigest,
int saltLen,
byte trailer)
{
return new PssSigner(cipher, new NullDigest(), contentDigest, mgfDigest, saltLen, trailer);
}
public PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest)
: this(cipher, digest, digest.GetDigestSize())
{
}
/// <summary>Basic constructor</summary>
/// <param name="cipher">the asymmetric cipher to use.</param>
/// <param name="digest">the digest to use.</param>
/// <param name="saltLen">the length of the salt to use (in bytes).</param>
public PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLen)
: this(cipher, digest, saltLen, TrailerImplicit)
{
}
public PssSigner(
IAsymmetricBlockCipher cipher,
IDigest contentDigest,
IDigest mgfDigest,
int saltLen)
: this(cipher, contentDigest, mgfDigest, saltLen, TrailerImplicit)
{
}
public PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLen,
byte trailer)
: this(cipher, digest, digest, saltLen, TrailerImplicit)
{
}
public PssSigner(
IAsymmetricBlockCipher cipher,
IDigest contentDigest,
IDigest mgfDigest,
int saltLen,
byte trailer)
: this(cipher, contentDigest, contentDigest, mgfDigest, saltLen, trailer)
{
}
private PssSigner(
IAsymmetricBlockCipher cipher,
IDigest contentDigest1,
IDigest contentDigest2,
IDigest mgfDigest,
int saltLen,
byte trailer)
{
this.cipher = cipher;
this.contentDigest1 = contentDigest1;
this.contentDigest2 = contentDigest2;
this.mgfDigest = mgfDigest;
this.hLen = contentDigest2.GetDigestSize();
this.mgfhLen = mgfDigest.GetDigestSize();
this.sLen = saltLen;
this.salt = new byte[saltLen];
this.mDash = new byte[8 + saltLen + hLen];
this.trailer = trailer;
}
public string AlgorithmName
{
get { return mgfDigest.AlgorithmName + "withRSAandMGF1"; }
}
public virtual void Init(
bool forSigning,
ICipherParameters parameters)
{
if (parameters is ParametersWithRandom)
{
ParametersWithRandom p = (ParametersWithRandom) parameters;
parameters = p.Parameters;
random = p.Random;
}
else
{
if (forSigning)
{
random = new SecureRandom();
}
}
cipher.Init(forSigning, parameters);
RsaKeyParameters kParam;
if (parameters is RsaBlindingParameters)
{
kParam = ((RsaBlindingParameters) parameters).PublicKey;
}
else
{
kParam = (RsaKeyParameters) parameters;
}
emBits = kParam.Modulus.BitLength - 1;
if (emBits < (8 * hLen + 8 * sLen + 9))
throw new ArgumentException("key too small for specified hash and salt lengths");
block = new byte[(emBits + 7) / 8];
}
/// <summary> clear possible sensitive data</summary>
private void ClearBlock(
byte[] block)
{
Array.Clear(block, 0, block.Length);
}
/// <summary> update the internal digest with the byte b</summary>
public virtual void Update(
byte input)
{
contentDigest1.Update(input);
}
/// <summary> update the internal digest with the byte array in</summary>
public virtual void BlockUpdate(
byte[] input,
int inOff,
int length)
{
contentDigest1.BlockUpdate(input, inOff, length);
}
/// <summary> reset the internal state</summary>
public virtual void Reset()
{
contentDigest1.Reset();
}
/// <summary> Generate a signature for the message we've been loaded with using
/// the key we were initialised with.
/// </summary>
public virtual byte[] GenerateSignature()
{
contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
if (sLen != 0)
{
random.NextBytes(salt);
salt.CopyTo(mDash, mDash.Length - sLen);
}
byte[] h = new byte[hLen];
contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
contentDigest2.DoFinal(h, 0);
block[block.Length - sLen - 1 - hLen - 1] = (byte) (0x01);
salt.CopyTo(block, block.Length - sLen - hLen - 1);
byte[] dbMask = MaskGeneratorFunction1(h, 0, h.Length, block.Length - hLen - 1);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits)));
h.CopyTo(block, block.Length - hLen - 1);
block[block.Length - 1] = trailer;
byte[] b = cipher.ProcessBlock(block, 0, block.Length);
ClearBlock(block);
return b;
}
/// <summary> return true if the internal state represents the signature described
/// in the passed in array.
/// </summary>
public virtual bool VerifySignature(
byte[] signature)
{
contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
byte[] b = cipher.ProcessBlock(signature, 0, signature.Length);
b.CopyTo(block, block.Length - b.Length);
if (block[block.Length - 1] != trailer)
{
ClearBlock(block);
return false;
}
byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - 1, hLen, block.Length - hLen - 1);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits)));
for (int i = 0; i != block.Length - hLen - sLen - 2; i++)
{
if (block[i] != 0)
{
ClearBlock(block);
return false;
}
}
if (block[block.Length - hLen - sLen - 2] != 0x01)
{
ClearBlock(block);
return false;
}
Array.Copy(block, block.Length - sLen - hLen - 1, mDash, mDash.Length - sLen, sLen);
contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
contentDigest2.DoFinal(mDash, mDash.Length - hLen);
for (int i = block.Length - hLen - 1, j = mDash.Length - hLen; j != mDash.Length; i++, j++)
{
if ((block[i] ^ mDash[j]) != 0)
{
ClearBlock(mDash);
ClearBlock(block);
return false;
}
}
ClearBlock(mDash);
ClearBlock(block);
return true;
}
/// <summary> int to octet string.</summary>
private void ItoOSP(
int i,
byte[] sp)
{
sp[0] = (byte)((uint) i >> 24);
sp[1] = (byte)((uint) i >> 16);
sp[2] = (byte)((uint) i >> 8);
sp[3] = (byte)((uint) i >> 0);
}
/// <summary> mask generator function, as described in Pkcs1v2.</summary>
private byte[] MaskGeneratorFunction1(
byte[] Z,
int zOff,
int zLen,
int length)
{
byte[] mask = new byte[length];
byte[] hashBuf = new byte[mgfhLen];
byte[] C = new byte[4];
int counter = 0;
mgfDigest.Reset();
while (counter < (length / mgfhLen))
{
ItoOSP(counter, C);
mgfDigest.BlockUpdate(Z, zOff, zLen);
mgfDigest.BlockUpdate(C, 0, C.Length);
mgfDigest.DoFinal(hashBuf, 0);
hashBuf.CopyTo(mask, counter * mgfhLen);
++counter;
}
if ((counter * mgfhLen) < length)
{
ItoOSP(counter, C);
mgfDigest.BlockUpdate(Z, zOff, zLen);
mgfDigest.BlockUpdate(C, 0, C.Length);
mgfDigest.DoFinal(hashBuf, 0);
Array.Copy(hashBuf, 0, mask, counter * mgfhLen, mask.Length - (counter * mgfhLen));
}
return mask;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Collections.Concurrent;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.ProviderBase
{
// set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup
// when not found a new pool entry is created and potentially added
// DbConnectionPoolGroup starts in the Active state
// Open calls DbConnectionFactory.GetConnectionPool
// if the existing pool entry is Disabled, GetConnectionPoolGroup is called for a new entry
// DbConnectionFactory.GetConnectionPool calls DbConnectionPoolGroup.GetConnectionPool
// DbConnectionPoolGroup.GetConnectionPool will return pool for the current identity
// or null if identity is restricted or pooling is disabled or state is disabled at time of add
// state changes are Active->Active, Idle->Active
// DbConnectionFactory.PruneConnectionPoolGroups calls Prune
// which will QueuePoolForRelease on all empty pools
// and once no pools remain, change state from Active->Idle->Disabled
// Once Disabled, factory can remove its reference to the pool entry
sealed internal class DbConnectionPoolGroup
{
private readonly DbConnectionOptions _connectionOptions;
private readonly DbConnectionPoolKey _poolKey;
private readonly DbConnectionPoolGroupOptions _poolGroupOptions;
private ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> _poolCollection;
private int _state; // see PoolGroupState* below
private DbConnectionPoolGroupProviderInfo _providerInfo;
// always lock this before changing _state, we don't want to move out of the 'Disabled' state
// PoolGroupStateUninitialized = 0;
private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open
private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear
private const int PoolGroupStateDisabled = 4; // factory pool entry prunning method
internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions)
{
Debug.Assert(null != connectionOptions, "null connection options");
_connectionOptions = connectionOptions;
_poolKey = key;
_poolGroupOptions = poolGroupOptions;
// always lock this object before changing state
// HybridDictionary does not create any sub-objects until add
// so it is safe to use for non-pooled connection as long as
// we check _poolGroupOptions first
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
_state = PoolGroupStateActive;
}
internal DbConnectionOptions ConnectionOptions
{
get
{
return _connectionOptions;
}
}
internal DbConnectionPoolKey PoolKey
{
get
{
return _poolKey;
}
}
internal DbConnectionPoolGroupProviderInfo ProviderInfo
{
get
{
return _providerInfo;
}
set
{
_providerInfo = value;
if (null != value)
{
_providerInfo.PoolGroup = this;
}
}
}
internal bool IsDisabled
{
get
{
return (PoolGroupStateDisabled == _state);
}
}
internal DbConnectionPoolGroupOptions PoolGroupOptions
{
get
{
return _poolGroupOptions;
}
}
internal int Clear()
{
// must be multi-thread safe with competing calls by Clear and Prune via background thread
// will return the number of connections in the group after clearing has finished
// First, note the old collection and create a new collection to be used
ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null;
lock (this)
{
if (_poolCollection.Count > 0)
{
oldPoolCollection = _poolCollection;
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
}
}
// Then, if a new collection was created, release the pools from the old collection
if (oldPoolCollection != null)
{
foreach (var entry in oldPoolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, true);
}
}
}
// Finally, return the pool collection count - this may be non-zero if something was added while we were clearing
return _poolCollection.Count;
}
internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory)
{
// When this method returns null it indicates that the connection
// factory should not use pooling.
// We don't support connection pooling on Win9x;
// PoolGroupOptions will only be null when we're not supposed to pool
// connections.
DbConnectionPool pool = null;
if (null != _poolGroupOptions)
{
DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity;
if (_poolGroupOptions.PoolByIdentity)
{
// if we're pooling by identity (because integrated security is
// being used for these connections) then we need to go out and
// search for the connectionPool that matches the current identity.
currentIdentity = DbConnectionPoolIdentity.GetCurrent();
// If the current token is restricted in some way, then we must
// not attempt to pool these connections.
if (currentIdentity.IsRestricted)
{
currentIdentity = null;
}
}
if (null != currentIdentity)
{
if (!_poolCollection.TryGetValue(currentIdentity, out pool))
{ // find the pool
DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
// optimistically create pool, but its callbacks are delayed until after actual add
DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
lock (this)
{
// Did someone already add it to the list?
if (!_poolCollection.TryGetValue(currentIdentity, out pool))
{
if (MarkPoolGroupAsActive())
{
// If we get here, we know for certain that we there isn't
// a pool that matches the current identity, so we have to
// add the optimistically created one
newPool.Startup(); // must start pool before usage
bool addResult = _poolCollection.TryAdd(currentIdentity, newPool);
Debug.Assert(addResult, "No other pool with current identity should exist at this point");
pool = newPool;
newPool = null;
}
else
{
// else pool entry has been disabled so don't create new pools
Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");
}
}
else
{
// else found an existing pool to use instead
Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
}
}
if (null != newPool)
{
// don't need to call connectionFactory.QueuePoolForRelease(newPool) because
// pool callbacks were delayed and no risk of connections being created
newPool.Shutdown();
}
}
// the found pool could be in any state
}
}
if (null == pool)
{
lock (this)
{
// keep the pool entry state active when not pooling
MarkPoolGroupAsActive();
}
}
return pool;
}
private bool MarkPoolGroupAsActive()
{
// when getting a connection, make the entry active if it was idle (but not disabled)
// must always lock this before calling
if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateActive;
}
return (PoolGroupStateActive == _state);
}
internal bool Prune()
{
// must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread
// must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove
// to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry
lock (this)
{
if (_poolCollection.Count > 0)
{
var newPoolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
foreach (var entry in _poolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
// Actually prune the pool if there are no connections in the pool and no errors occurred.
// Empty pool during pruning indicates zero or low activity, but
// an error state indicates the pool needs to stay around to
// throttle new connection attempts.
if ((!pool.ErrorOccurred) && (0 == pool.Count))
{
// Order is important here. First we remove the pool
// from the collection of pools so no one will try
// to use it while we're processing and finally we put the
// pool into a list of pools to be released when they
// are completely empty.
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, false);
}
else
{
newPoolCollection.TryAdd(entry.Key, entry.Value);
}
}
}
_poolCollection = newPoolCollection;
}
// must be pruning thread to change state and no connections
// otherwise pruning thread risks making entry disabled soon after user calls ClearPool
if (0 == _poolCollection.Count)
{
if (PoolGroupStateActive == _state)
{
_state = PoolGroupStateIdle;
}
else if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateDisabled;
}
}
return (PoolGroupStateDisabled == _state);
}
}
}
}
| |
/*
* 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.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.CoreModules.World.Serialiser
{
public class SerialiserModule : ISharedRegionModule, IRegionSerialiserModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Commander m_commander = new Commander("export");
private List<Scene> m_regions = new List<Scene>();
private string m_savedir = "exports" + "/";
private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>();
#region ISharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Serialiser"];
if (config != null)
{
m_savedir = config.GetString("save_dir", m_savedir);
}
m_log.InfoFormat("[Serialiser] Enabled, using save dir \"{0}\"", m_savedir);
}
public void PostInitialise()
{
lock (m_serialisers)
{
m_serialisers.Add(new SerialiseTerrain());
m_serialisers.Add(new SerialiseObjects());
}
LoadCommanderCommands();
}
public void AddRegion(Scene scene)
{
scene.RegisterModuleCommander(m_commander);
scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
scene.RegisterModuleInterface<IRegionSerialiserModule>(this);
lock (m_regions)
{
m_regions.Add(scene);
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_regions)
{
m_regions.Remove(scene);
}
}
public void Close()
{
m_regions.Clear();
}
public string Name
{
get { return "ExportSerialisationModule"; }
}
#endregion
#region IRegionSerialiser Members
public void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
SceneXmlLoader.LoadPrimsFromXml(scene, fileName, newIDS, loadOffset);
}
public void SavePrimsToXml(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, string fileName)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, reader, startScripts);
}
public void SavePrimsToXml2(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml2(scene, fileName);
}
public void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimsToXml2(scene, stream, min, max);
}
public void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
SceneXmlLoader.SaveNamedPrimsToXml2(scene, primName, fileName);
}
public SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneXmlLoader.DeserializeGroupFromXml2(xmlString);
}
public string SerializeGroupToXml2(SceneObjectGroup grp)
{
return SceneXmlLoader.SaveGroupToXml2(grp);
}
public void SavePrimListToXml2(List<EntityBase> entityList, string fileName)
{
SceneXmlLoader.SavePrimListToXml2(entityList, fileName);
}
public void SavePrimListToXml2(List<EntityBase> entityList, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimListToXml2(entityList, stream, min, max);
}
public List<string> SerialiseRegion(Scene scene, string saveDir)
{
List<string> results = new List<string>();
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
lock (m_serialisers)
{
foreach (IFileSerialiser serialiser in m_serialisers)
{
results.Add(serialiser.WriteToFile(scene, saveDir));
}
}
TextWriter regionInfoWriter = new StreamWriter(saveDir + "README.TXT");
regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName);
regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString());
regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString());
regionInfoWriter.WriteLine("Serialise Version: 0.1");
regionInfoWriter.Close();
TextWriter manifestWriter = new StreamWriter(saveDir + "region.manifest");
foreach (string line in results)
{
manifestWriter.WriteLine(line);
}
manifestWriter.Close();
return results;
}
#endregion
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "export")
{
string[] tmpArgs = new string[args.Length - 2];
int i = 0;
for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
private void InterfaceSaveRegion(Object[] args)
{
foreach (Scene region in m_regions)
{
if (region.RegionInfo.RegionName == (string) args[0])
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
}
}
}
private void InterfaceSaveAllRegions(Object[] args)
{
foreach (Scene region in m_regions)
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
}
}
private void LoadCommanderCommands()
{
Command serialiseSceneCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveRegion, "Saves the named region into the exports directory.");
serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String");
Command serialiseAllScenesCommand = new Command("save-all",CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveAllRegions, "Saves all regions into the exports directory.");
m_commander.RegisterCommand("save", serialiseSceneCommand);
m_commander.RegisterCommand("save-all", serialiseAllScenesCommand);
}
}
}
| |
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
namespace UMA
{
/// <summary>
/// UMA data holds the recipe for creating a character and skeleton and Unity references for a built character.
/// </summary>
public class UMAData : MonoBehaviour
{
public SkinnedMeshRenderer myRenderer;
[NonSerialized]
public bool firstBake;
public UMAGeneratorBase umaGenerator;
[NonSerialized]
public GeneratedMaterials generatedMaterials = new GeneratedMaterials();
private LinkedListNode<UMAData> listNode;
public void MoveToList(LinkedList<UMAData> list)
{
if (listNode.List != null)
{
listNode.List.Remove(listNode);
}
list.AddLast(listNode);
}
public float atlasResolutionScale = 1f;
/// <summary>
/// Has the character mesh changed?
/// </summary>
public bool isMeshDirty;
/// <summary>
/// Has the character skeleton changed?
/// </summary>
public bool isShapeDirty;
/// <summary>
/// Have the overlay textures changed?
/// </summary>
public bool isTextureDirty;
/// <summary>
/// Have the texture atlases changed?
/// </summary>
public bool isAtlasDirty;
public RuntimeAnimatorController animationController;
private Dictionary<int, int> animatedBonesTable;
public void ResetAnimatedBones()
{
if (animatedBonesTable == null)
{
animatedBonesTable = new Dictionary<int, int>();
}
else
{
animatedBonesTable.Clear();
}
}
public void RegisterAnimatedBone(int hash)
{
if (!animatedBonesTable.ContainsKey(hash))
{
animatedBonesTable.Add(hash, animatedBonesTable.Count);
}
}
public void RegisterAnimatedBoneHierarchy(int hash)
{
if (!animatedBonesTable.ContainsKey(hash))
{
animatedBonesTable.Add(hash, animatedBonesTable.Count);
}
}
public bool cancelled { get; private set; }
[NonSerialized]
public bool dirty = false;
private bool isOfficiallyCreated = false;
/// <summary>
/// Callback event when character has been updated.
/// </summary>
public event Action<UMAData> OnCharacterUpdated { add { if (CharacterUpdated == null) CharacterUpdated = new UMADataEvent(); CharacterUpdated.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterUpdated.RemoveListener(new UnityAction<UMAData>(value)); } }
/// <summary>
/// Callback event when character has been completely created.
/// </summary>
public event Action<UMAData> OnCharacterCreated { add { if (CharacterCreated == null) CharacterCreated = new UMADataEvent(); CharacterCreated.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterCreated.RemoveListener(new UnityAction<UMAData>(value)); } }
/// <summary>
/// Callback event when character has been destroyed.
/// </summary>
public event Action<UMAData> OnCharacterDestroyed { add { if (CharacterDestroyed == null) CharacterDestroyed = new UMADataEvent(); CharacterDestroyed.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterDestroyed.RemoveListener(new UnityAction<UMAData>(value)); } }
public UMADataEvent CharacterCreated;
public UMADataEvent CharacterDestroyed;
public UMADataEvent CharacterUpdated;
public GameObject umaRoot;
public UMARecipe umaRecipe;
public Animator animator;
public UMASkeleton skeleton;
/// <summary>
/// The approximate height of the character. Calculated by DNA converters.
/// </summary>
public float characterHeight = 2f;
/// <summary>
/// The approximate radius of the character. Calculated by DNA converters.
/// </summary>
public float characterRadius = 0.25f;
/// <summary>
/// The approximate mass of the character. Calculated by DNA converters.
/// </summary>
public float characterMass = 50f;
public UMAData()
{
listNode = new LinkedListNode<UMAData>(this);
}
void Awake()
{
firstBake = true;
if (!umaGenerator)
{
var generatorGO = GameObject.Find("UMAGenerator");
if (generatorGO == null) return;
umaGenerator = generatorGO.GetComponent<UMAGeneratorBase>();
}
if (umaRecipe == null)
{
umaRecipe = new UMARecipe();
}
else
{
SetupOnAwake();
}
}
public void SetupOnAwake()
{
umaRoot = gameObject;
animator = umaRoot.GetComponent<Animator>();
}
#pragma warning disable 618
/// <summary>
/// Shallow copy from another UMAData.
/// </summary>
/// <param name="other">Source UMAData.</param>
public void Assign(UMAData other)
{
animator = other.animator;
myRenderer = other.myRenderer;
umaRoot = other.umaRoot;
if (animationController == null)
{
animationController = other.animationController;
}
}
#pragma warning restore 618
public bool Validate()
{
bool valid = true;
if (umaGenerator == null)
{
Debug.LogError("UMA data missing required generator!");
valid = false;
}
if (umaRecipe == null)
{
Debug.LogError("UMA data missing required recipe!");
valid = false;
}
else
{
valid = valid && umaRecipe.Validate();
}
#if UNITY_EDITOR
if (!valid && UnityEditor.EditorApplication.isPlaying) UnityEditor.EditorApplication.isPaused = true;
#endif
return valid;
}
[System.Serializable]
public class GeneratedMaterials
{
public List<GeneratedMaterial> materials = new List<GeneratedMaterial>();
}
[System.Serializable]
public class GeneratedMaterial
{
public UMAMaterial umaMaterial;
public Material material;
public List<MaterialFragment> materialFragments = new List<MaterialFragment>();
public Texture[] resultingAtlasList;
public Vector2 cropResolution;
public float resolutionScale;
public string[] textureNameList;
}
[System.Serializable]
public class MaterialFragment
{
public int size;
public Color baseColor;
public UMAMaterial umaMaterial;
public Rect[] rects;
public textureData[] overlays;
public Color32[] overlayColors;
public Color[][] channelMask;
public Color[][] channelAdditiveMask;
public SlotData slotData;
public OverlayData[] overlayData;
public Rect atlasRegion;
public bool isRectShared;
public List<OverlayData> overlayList;
public MaterialFragment rectFragment;
public textureData baseOverlay;
public Color GetMultiplier(int overlay, int textureType)
{
if (channelMask[overlay] != null && channelMask[overlay].Length > 0)
{
return channelMask[overlay][textureType];
}
else
{
if (textureType > 0) return Color.white;
if (overlay == 0) return baseColor;
return overlayColors[overlay - 1];
}
}
public Color32 GetAdditive(int overlay, int textureType)
{
if (channelAdditiveMask[overlay] != null && channelAdditiveMask[overlay].Length > 0)
{
return channelAdditiveMask[overlay][textureType];
}
else
{
return new Color32(0, 0, 0, 0);
}
}
}
[System.Serializable]
public class textureData
{
public Texture[] textureList;
public Texture alphaTexture;
public OverlayDataAsset.OverlayType overlayType;
}
[System.Serializable]
public class resultAtlasTexture
{
public Texture[] textureList;
}
/// <summary>
/// The UMARecipe class contains the race, DNA, and color data required to build a UMA character.
/// </summary>
[System.Serializable]
public class UMARecipe
{
public RaceData raceData;
Dictionary<int, UMADnaBase> _umaDna;
protected Dictionary<int, UMADnaBase> umaDna
{
get
{
if (_umaDna == null)
{
_umaDna = new Dictionary<int, UMADnaBase>();
for (int i = 0; i < dnaValues.Count; i++)
_umaDna.Add(dnaValues[i].DNATypeHash, dnaValues[i]);
}
return _umaDna;
}
set
{
_umaDna = value;
}
}
protected Dictionary<int, DnaConverterBehaviour.DNAConvertDelegate> umaDnaConverter = new Dictionary<int, DnaConverterBehaviour.DNAConvertDelegate>();
protected Dictionary<string, int> mergedSharedColors = new Dictionary<string, int>();
public List<UMADnaBase> dnaValues = new List<UMADnaBase>();
public SlotData[] slotDataList;
[Obsolete("UMA 2.1 - additionalSlotCount has been deprecated, SlotData.dontSerialize now takes care of scene based additonal slots. ", false)]
public int additionalSlotCount;
public OverlayColorData[] sharedColors;
public bool Validate()
{
bool valid = true;
if (raceData == null)
{
Debug.LogError("UMA recipe missing required race!");
valid = false;
}
else
{
valid = valid && raceData.Validate();
}
if (slotDataList == null || slotDataList.Length == 0)
{
Debug.LogError("UMA recipe slot list is empty!");
valid = false;
}
int slotDataCount = 0;
for (int i = 0; i < slotDataList.Length; i++)
{
var slotData = slotDataList[i];
if (slotData != null)
{
slotDataCount++;
valid = valid && slotData.Validate();
}
}
if (slotDataCount < 1)
{
Debug.LogError("UMA recipe slot list contains only null objects!");
valid = false;
}
return valid;
}
#pragma warning disable 618
/// <summary>
/// Gets the DNA array.
/// </summary>
/// <returns>The DNA array.</returns>
public UMADnaBase[] GetAllDna()
{
if ((raceData == null) || (slotDataList == null))
{
return new UMADnaBase[0];
}
return dnaValues.ToArray();
}
/// <summary>
/// Adds the DNA specified.
/// </summary>
/// <param name="dna">DNA.</param>
public void AddDna(UMADnaBase dna)
{
umaDna.Add(dna.DNATypeHash, dna);
dnaValues.Add(dna);
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <typeparam name="T">Type.</typeparam>
public T GetDna<T>()
where T : UMADnaBase
{
UMADnaBase dna;
if (umaDna.TryGetValue(UMAUtils.StringToHash(typeof(T).Name), out dna))
{
return dna as T;
}
return null;
}
/// <summary>
/// Removes all DNA.
/// </summary>
public void ClearDna()
{
umaDna.Clear();
dnaValues.Clear();
}
/// <summary>
/// DynamicUMADna:: a version of RemoveDna that uses the dnaTypeNameHash
/// </summary>
/// <param name="dnaTypeNameHash"></param>
public void RemoveDna(int dnaTypeNameHash)
{
dnaValues.Remove(umaDna[dnaTypeNameHash]);
umaDna.Remove(dnaTypeNameHash);
}
/// <summary>
/// Removes the specified DNA.
/// </summary>
/// <param name="type">Type.</param>
public void RemoveDna(Type type)
{
int dnaTypeNameHash = UMAUtils.StringToHash(type.Name);
dnaValues.Remove(umaDna[dnaTypeNameHash]);
umaDna.Remove(dnaTypeNameHash);
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetDna(Type type)
{
UMADnaBase dna;
if (umaDna.TryGetValue(UMAUtils.StringToHash(type.Name), out dna))
{
return dna;
}
return null;
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="dnaTypeNameHash">Type.</param>
public UMADnaBase GetDna(int dnaTypeNameHash)
{
UMADnaBase dna;
if (umaDna.TryGetValue(dnaTypeNameHash, out dna))
{
return dna;
}
return null;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <typeparam name="T">Type.</typeparam>
public T GetOrCreateDna<T>()
where T : UMADnaBase
{
T res = GetDna<T>();
if (res == null)
{
res = typeof(T).GetConstructor(System.Type.EmptyTypes).Invoke(null) as T;
umaDna.Add(res.DNATypeHash, res);
dnaValues.Add(res);
}
return res;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetOrCreateDna(Type type)
{
UMADnaBase dna;
var typeNameHash = UMAUtils.StringToHash(type.Name);
if (umaDna.TryGetValue(typeNameHash, out dna))
{
return dna;
}
dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
umaDna.Add(typeNameHash, dna);
dnaValues.Add(dna);
return dna;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetOrCreateDna(Type type, int dnaTypeHash)
{
UMADnaBase dna;
if (umaDna.TryGetValue(dnaTypeHash, out dna))
{
return dna;
}
dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
return dna;
}
#pragma warning restore 618
/// <summary>
/// Sets the race.
/// </summary>
/// <param name="raceData">Race.</param>
public void SetRace(RaceData raceData)
{
this.raceData = raceData;
ClearDNAConverters();
}
/// <summary>
/// Gets the race.
/// </summary>
/// <returns>The race.</returns>
public RaceData GetRace()
{
return this.raceData;
}
/// <summary>
/// Sets the slot at a given index.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="slot">Slot.</param>
public void SetSlot(int index, SlotData slot)
{
if (index >= slotDataList.Length)
{
System.Array.Resize<SlotData>(ref slotDataList, index + 1);
}
slotDataList[index] = slot;
}
/// <summary>
/// Sets the entire slot array.
/// </summary>
/// <param name="slots">Slots.</param>
public void SetSlots(SlotData[] slots)
{
slotDataList = slots;
}
/// <summary>
/// Combine additional slot with current data.
/// </summary>
/// <param name="slot">Slot.</param>
/// <param name="dontSerialize">If set to <c>true</c> slot will not be serialized.</param>
public void MergeSlot(SlotData slot, bool dontSerialize)
{
if ((slot == null) || (slot.asset == null))
return;
int overlayCount = 0;
for (int i = 0; i < slotDataList.Length; i++)
{
if (slotDataList[i] == null)
continue;
if (slot.asset == slotDataList[i].asset)
{
SlotData originalSlot = slotDataList[i];
overlayCount = slot.OverlayCount;
for (int j = 0; j < overlayCount; j++)
{
OverlayData overlay = slot.GetOverlay(j);
//DynamicCharacterSystem:: Needs to use alternative methods that find equivalent overlays since they may not be Equal if they were in an assetBundle
OverlayData originalOverlay = originalSlot.GetEquivalentUsedOverlay(overlay);
if (originalOverlay != null)
{
originalOverlay.CopyColors(overlay);//also copies textures
if (overlay.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
{
originalOverlay.colorData = sharedColors[sharedIndex];
}
}
}
else
{
OverlayData overlayCopy = overlay.Duplicate();
if (overlayCopy.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlayCopy.colorData.name, out sharedIndex))
{
overlayCopy.colorData = sharedColors[sharedIndex];
}
}
originalSlot.AddOverlay(overlayCopy);
}
}
originalSlot.dontSerialize = dontSerialize;
return;
}
}
int insertIndex = slotDataList.Length;
System.Array.Resize<SlotData>(ref slotDataList, slotDataList.Length + 1);
SlotData slotCopy = slot.Copy();
slotCopy.dontSerialize = dontSerialize;
overlayCount = slotCopy.OverlayCount;
for (int j = 0; j < overlayCount; j++)
{
OverlayData overlay = slotCopy.GetOverlay(j);
if (overlay.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
{
overlay.colorData = sharedColors[sharedIndex];
}
}
}
slotDataList[insertIndex] = slotCopy;
MergeMatchingOverlays();
}
/// <summary>
/// Gets a slot by index.
/// </summary>
/// <returns>The slot.</returns>
/// <param name="index">Index.</param>
public SlotData GetSlot(int index)
{
if (index < slotDataList.Length)
return slotDataList[index];
return null;
}
/// <summary>
/// Gets the complete array of slots.
/// </summary>
/// <returns>The slot array.</returns>
public SlotData[] GetAllSlots()
{
return slotDataList;
}
/// <summary>
/// Gets the number of slots.
/// </summary>
/// <returns>The slot array size.</returns>
public int GetSlotArraySize()
{
return slotDataList.Length;
}
/// <summary>
/// Are two overlay lists the same?
/// </summary>
/// <returns><c>true</c>, if lists match, <c>false</c> otherwise.</returns>
/// <param name="list1">List1.</param>
/// <param name="list2">List2.</param>
public static bool OverlayListsMatch(List<OverlayData> list1, List<OverlayData> list2)
{
if ((list1 == null) || (list2 == null))
return false;
if ((list1.Count == 0) || (list1.Count != list2.Count))
return false;
for (int i = 0; i < list1.Count; i++)
{
OverlayData overlay1 = list1[i];
if (!(overlay1))
continue;
bool found = false;
for (int j = 0; j < list2.Count; j++)
{
OverlayData overlay2 = list2[i];
if (!(overlay2))
continue;
if (OverlayData.Equivalent(overlay1, overlay2))
{
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
/// <summary>
/// Ensures slots with matching overlays will share the same references.
/// </summary>
public void MergeMatchingOverlays()
{
for (int i = 0; i < slotDataList.Length; i++)
{
if (slotDataList[i] == null)
continue;
List<OverlayData> slotOverlays = slotDataList[i].GetOverlayList();
for (int j = i + 1; j < slotDataList.Length; j++)
{
if (slotDataList[j] == null)
continue;
List<OverlayData> slot2Overlays = slotDataList[j].GetOverlayList();
if (OverlayListsMatch(slotOverlays, slot2Overlays))
{
slotDataList[j].SetOverlayList(slotOverlays);
}
}
}
}
#pragma warning disable 618
/// <summary>
/// Applies each DNA converter to the UMA data and skeleton.
/// </summary>
/// <param name="umaData">UMA data.</param>
public void ApplyDNA(UMAData umaData, bool fixUpUMADnaToDynamicUMADna = false)
{
EnsureAllDNAPresent();
//DynamicUMADna:: when loading an older recipe that has UMADnaHumanoid/Tutorial into a race that now uses DynamicUmaDna the following wont work
//so check that and fix it if it happens
if (fixUpUMADnaToDynamicUMADna)
DynamicDNAConverterBehaviourBase.FixUpUMADnaToDynamicUMADna(this);
foreach (var dnaEntry in umaDna)
{
DnaConverterBehaviour.DNAConvertDelegate dnaConverter;
if (umaDnaConverter.TryGetValue(dnaEntry.Key, out dnaConverter))
{
dnaConverter(umaData, umaData.GetSkeleton());
}
else
{
//DynamicUMADna:: try again this time calling FixUpUMADnaToDynamicUMADna first
if (fixUpUMADnaToDynamicUMADna == false)
{
ApplyDNA(umaData, true);
break;
}
else
{
Debug.LogWarning("Cannot apply dna: " + dnaEntry.Value.GetType().Name + " using key " + dnaEntry.Key);
}
}
}
}
/// <summary>
/// Ensures all DNA convertes from slot and race data are defined.
/// </summary>
public void EnsureAllDNAPresent()
{
if (raceData != null)
{
foreach (var converter in raceData.dnaConverterList)
{
var dnaTypeHash = converter.DNATypeHash;
if (!umaDna.ContainsKey(dnaTypeHash))
{
var dna = converter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
//DynamicUMADna:: needs the DNAasset from the converter
if (converter is DynamicDNAConverterBehaviourBase)
{
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)converter).dnaAsset;
}
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
}
}
}
foreach (var slotData in slotDataList)
{
if (slotData != null && slotData.asset.slotDNA != null)
{
var dnaTypeHash = slotData.asset.slotDNA.DNATypeHash;
if (!umaDna.ContainsKey(dnaTypeHash))
{
var dna = slotData.asset.slotDNA.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
//DynamicUMADna:: needs the DNAasset from the converter TODO are there other places where I heed to sort out this slotDNA?
if (slotData.asset.slotDNA is DynamicDNAConverterBehaviourBase)
{
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)slotData.asset.slotDNA).dnaAsset;
}
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
}
}
}
}
#pragma warning restore 618
/// <summary>
/// Resets the DNA converters to those defined in the race.
/// </summary>
public void ClearDNAConverters()
{
umaDnaConverter.Clear();
if (raceData != null)
{
foreach (var converter in raceData.dnaConverterList)
{
//DynamicDNAConverter:: We need to SET these values using the TypeHash since
//just getting the hash of the DNAType will set the same value for all instance of a DynamicDNAConverter
umaDnaConverter.Add(converter.DNATypeHash, converter.ApplyDnaAction);
}
}
}
/// <summary>
/// Adds a DNA converter.
/// </summary>
/// <param name="dnaConverter">DNA converter.</param>
public void AddDNAUpdater(DnaConverterBehaviour dnaConverter)
{
if (dnaConverter == null) return;
//DynamicDNAConverter:: We need to SET these values using the TypeHash since
//just getting the hash of the DNAType will set the same value for all instance of a DynamicDNAConverter
if (!umaDnaConverter.ContainsKey(dnaConverter.DNATypeHash))
{
umaDnaConverter.Add(dnaConverter.DNATypeHash, dnaConverter.ApplyDnaAction);
}
}
/// <summary>
/// Shallow copy of UMARecipe.
/// </summary>
public UMARecipe Mirror()
{
var newRecipe = new UMARecipe();
newRecipe.raceData = raceData;
newRecipe.umaDna = umaDna;
newRecipe.dnaValues = dnaValues;
newRecipe.slotDataList = slotDataList;
return newRecipe;
}
/// <summary>
/// Combine additional recipe with current data.
/// </summary>
/// <param name="recipe">Recipe.</param>
/// <param name="dontSerialize">If set to <c>true</c> recipe will not be serialized.</param>
public void Merge(UMARecipe recipe, bool dontSerialize)
{
if (recipe == null)
return;
if ((recipe.raceData != null) && (recipe.raceData != raceData))
{
Debug.LogWarning("Merging recipe with conflicting race data: " + recipe.raceData.name);
}
foreach (var dnaEntry in recipe.umaDna)
{
var destDNA = GetOrCreateDna(dnaEntry.Value.GetType(), dnaEntry.Key);
destDNA.Values = dnaEntry.Value.Values;
}
mergedSharedColors.Clear();
if (sharedColors == null)
sharedColors = new OverlayColorData[0];
if (recipe.sharedColors != null)
{
for (int i = 0; i < sharedColors.Length; i++)
{
if (sharedColors[i] != null && sharedColors[i].HasName())
{
while (mergedSharedColors.ContainsKey(sharedColors[i].name))
{
sharedColors[i].name = sharedColors[i].name + ".";
}
mergedSharedColors.Add(sharedColors[i].name, i);
}
}
for (int i = 0; i < recipe.sharedColors.Length; i++)
{
OverlayColorData sharedColor = recipe.sharedColors[i];
if (sharedColor != null && sharedColor.HasName())
{
int sharedIndex;
if (!mergedSharedColors.TryGetValue(sharedColor.name, out sharedIndex))
{
int index = sharedColors.Length;
mergedSharedColors.Add(sharedColor.name, index);
Array.Resize<OverlayColorData>(ref sharedColors, index + 1);
sharedColors[index] = sharedColor.Duplicate();
}
}
}
}
if (slotDataList == null)
slotDataList = new SlotData[0];
if (recipe.slotDataList != null)
{
for (int i = 0; i < recipe.slotDataList.Length; i++)
{
MergeSlot(recipe.slotDataList[i], dontSerialize);
}
}
}
}
[System.Serializable]
public class BoneData
{
public Transform boneTransform;
public Vector3 originalBoneScale;
public Vector3 originalBonePosition;
public Quaternion originalBoneRotation;
}
/// <summary>
/// Calls character updated and/or created events.
/// </summary>
public void FireUpdatedEvent(bool cancelled)
{
this.cancelled = cancelled;
if (!this.cancelled && !isOfficiallyCreated)
{
isOfficiallyCreated = true;
if (CharacterCreated != null)
{
CharacterCreated.Invoke(this);
}
}
if (CharacterUpdated != null)
{
CharacterUpdated.Invoke(this);
}
dirty = false;
}
public void ApplyDNA()
{
umaRecipe.ApplyDNA(this);
}
public virtual void Dirty()
{
if (dirty) return;
dirty = true;
if (!umaGenerator)
{
umaGenerator = GameObject.Find("UMAGenerator").GetComponent<UMAGeneratorBase>();
}
if (umaGenerator)
{
umaGenerator.addDirtyUMA(this);
}
}
void OnDestroy()
{
if (isOfficiallyCreated)
{
if (CharacterDestroyed != null)
{
CharacterDestroyed.Invoke(this);
}
isOfficiallyCreated = false;
}
if (umaRoot != null)
{
CleanTextures();
CleanMesh(true);
CleanAvatar();
Destroy(umaRoot);
}
}
/// <summary>
/// Destory Mecanim avatar and animator.
/// </summary>
public void CleanAvatar()
{
animationController = null;
if (animator != null)
{
if (animator.avatar) GameObject.Destroy(animator.avatar);
if (animator) GameObject.Destroy(animator);
}
}
/// <summary>
/// Destroy textures used to render mesh.
/// </summary>
public void CleanTextures()
{
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
Texture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex];
if (tempTexture is RenderTexture)
{
RenderTexture tempRenderTexture = tempTexture as RenderTexture;
tempRenderTexture.Release();
Destroy(tempRenderTexture);
tempRenderTexture = null;
}
else
{
Destroy(tempTexture);
}
generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] = null;
}
}
}
}
}
/// <summary>
/// Destroy materials used to render mesh.
/// </summary>
/// <param name="destroyRenderer">If set to <c>true</c> destroy mesh renderer.</param>
public void CleanMesh(bool destroyRenderer)
{
if (myRenderer)
{
var mats = myRenderer.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i])
{
Destroy(myRenderer.sharedMaterials[i]);
}
}
if (destroyRenderer)
{
Destroy(myRenderer.sharedMesh);
Destroy(myRenderer);
}
}
}
public Texture[] backUpTextures()
{
List<Texture> textureList = new List<Texture>();
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
Texture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex];
textureList.Add(tempTexture);
generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] = null;
}
}
}
}
return textureList.ToArray();
}
public RenderTexture GetFirstRenderTexture()
{
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
RenderTexture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] as RenderTexture;
if (tempTexture != null)
{
return tempTexture;
}
}
}
}
}
return null;
}
/// <summary>
/// Gets the game object for a bone by name.
/// </summary>
/// <returns>The game object (or null if hash not in skeleton).</returns>
/// <param name="boneName">Bone name.</param>
public GameObject GetBoneGameObject(string boneName)
{
return GetBoneGameObject(UMAUtils.StringToHash(boneName));
}
/// <summary>
/// Gets the game object for a bone by name hash.
/// </summary>
/// <returns>The game object (or null if hash not in skeleton).</returns>
/// <param name="boneHash">Bone name hash.</param>
public GameObject GetBoneGameObject(int boneHash)
{
return skeleton.GetBoneGameObject(boneHash);
}
/// <summary>
/// Gets the complete DNA array.
/// </summary>
/// <returns>The DNA array.</returns>
public UMADnaBase[] GetAllDna()
{
return umaRecipe.GetAllDna();
}
/// <summary>
/// DynamicUMADna:: Retrieve DNA by dnaTypeNameHash.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="dnaTypeNameHash">dnaTypeNameHash.</param>
public UMADnaBase GetDna(int dnaTypeNameHash)
{
return umaRecipe.GetDna(dnaTypeNameHash);
}
/// <summary>
/// Retrieve DNA by type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetDna(Type type)
{
return umaRecipe.GetDna(type);
}
/// <summary>
/// Retrieve DNA by type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <typeparam name="T">The type od DNA requested.</typeparam>
public T GetDna<T>()
where T : UMADnaBase
{
return umaRecipe.GetDna<T>();
}
/// <summary>
/// Marks portions of the UMAData as modified.
/// </summary>
/// <param name="dnaDirty">If set to <c>true</c> DNA has changed.</param>
/// <param name="textureDirty">If set to <c>true</c> texture has changed.</param>
/// <param name="meshDirty">If set to <c>true</c> mesh has changed.</param>
public void Dirty(bool dnaDirty, bool textureDirty, bool meshDirty)
{
isShapeDirty |= dnaDirty;
isTextureDirty |= textureDirty;
isMeshDirty |= meshDirty;
Dirty();
}
/// <summary>
/// Sets the slot at a given index.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="slot">Slot.</param>
public void SetSlot(int index, SlotData slot)
{
umaRecipe.SetSlot(index, slot);
}
/// <summary>
/// Sets the entire slot array.
/// </summary>
/// <param name="slots">Slots.</param>
public void SetSlots(SlotData[] slots)
{
umaRecipe.SetSlots(slots);
}
/// <summary>
/// Gets a slot by index.
/// </summary>
/// <returns>The slot.</returns>
/// <param name="index">Index.</param>
public SlotData GetSlot(int index)
{
return umaRecipe.GetSlot(index);
}
/// <summary>
/// Gets the number of slots.
/// </summary>
/// <returns>The slot array size.</returns>
public int GetSlotArraySize()
{
return umaRecipe.GetSlotArraySize();
}
/// <summary>
/// Gets the skeleton.
/// </summary>
/// <returns>The skeleton.</returns>
public UMASkeleton GetSkeleton()
{
return skeleton;
}
/// <summary>
/// Align skeleton to the TPose.
/// </summary>
public void GotoTPose()
{
if ((umaRecipe.raceData != null) && (umaRecipe.raceData.TPose != null))
{
var tpose = umaRecipe.raceData.TPose;
tpose.DeSerialize();
for (int i = 0; i < tpose.boneInfo.Length; i++)
{
var bone = tpose.boneInfo[i];
var hash = UMAUtils.StringToHash(bone.name);
var go = skeleton.GetBoneGameObject(hash);
if (go == null) continue;
skeleton.SetPosition(hash, bone.position);
skeleton.SetRotation(hash, bone.rotation);
skeleton.SetScale(hash, bone.scale);
}
}
}
public int[] GetAnimatedBones()
{
var res = new int[animatedBonesTable.Count];
foreach (var entry in animatedBonesTable)
{
res[entry.Value] = entry.Key;
}
return res;
}
/// <summary>
/// Calls character begun events on slots.
/// </summary>
public void FireCharacterBegunEvents()
{
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.CharacterBegun != null)
{
slotData.asset.CharacterBegun.Invoke(this);
}
}
}
/// <summary>
/// Calls DNA applied events on slots.
/// </summary>
public void FireDNAAppliedEvents()
{
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.DNAApplied != null)
{
slotData.asset.DNAApplied.Invoke(this);
}
}
}
/// <summary>
/// Calls character completed events on slots.
/// </summary>
public void FireCharacterCompletedEvents()
{
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.CharacterCompleted != null)
{
slotData.asset.CharacterCompleted.Invoke(this);
}
}
}
/// <summary>
/// Adds additional, non serialized, recipes.
/// </summary>
/// <param name="umaAdditionalRecipes">Additional recipes.</param>
/// <param name="context">Context.</param>
public void AddAdditionalRecipes(UMARecipeBase[] umaAdditionalRecipes, UMAContext context)
{
if (umaAdditionalRecipes != null)
{
foreach (var umaAdditionalRecipe in umaAdditionalRecipes)
{
UMARecipe cachedRecipe = umaAdditionalRecipe.GetCachedRecipe(context);
umaRecipe.Merge(cachedRecipe, true);
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PLATFORM_DETECTION
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
#if NETSTANDARD2_0
using System.Runtime.Versioning;
#else
using Microsoft.Win32;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>MonoTouch</summary>
MonoTouch,
/// <summary>Microsoft .NET Core</summary>
NetCore
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
// NOTE: This version of RuntimeFramework is for use
// within the NUnit framework assembly. It is simpler
// than the version in the test engine because it does
// not need to know what frameworks are available,
// only what framework is currently running.
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() =>
{
Type monoRuntimeType = null;
Type monoTouchType = null;
try
{
monoRuntimeType = Type.GetType("Mono.Runtime", false);
monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch", false);
}
catch
{
//If exception thrown, assume no valid installation
}
bool isMonoTouch = monoTouchType != null;
bool isMono = monoRuntimeType != null;
bool isNetCore = !isMono && !isMonoTouch && IsNetCore();
RuntimeType runtime = isMonoTouch
? RuntimeType.MonoTouch
: isMono
? RuntimeType.Mono
: isNetCore
? RuntimeType.NetCore
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else if (isNetCore)
{
major = 0;
minor = 0;
}
else /* It's windows */
#if NETSTANDARD2_0
{
minor = 5;
}
#else
if (major == 2)
{
// The only assembly we compile that can run on the v2 CLR uses .NET Framework 3.5.
major = 3;
minor = 5;
}
else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
{
minor = 5;
}
#endif
var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) )
{
ClrVersion = Environment.Version
};
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
return currentFramework;
});
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
Runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
DisplayName = GetDefaultDisplayName(runtime, version);
}
private void InitFromFrameworkVersion(Version version)
{
FrameworkVersion = ClrVersion = version;
if (version.Major > 0) // 0 means any version
switch (Runtime)
{
case RuntimeType.NetCore:
ClrVersion = new Version(4, 0, 30319);
break;
case RuntimeType.Net:
case RuntimeType.Mono:
case RuntimeType.Any:
switch (version.Major)
{
case 1:
switch (version.Minor)
{
case 0:
ClrVersion = Runtime == RuntimeType.Mono
? new Version(1, 1, 4322)
: new Version(1, 0, 3705);
break;
case 1:
if (Runtime == RuntimeType.Mono)
FrameworkVersion = new Version(1, 0);
ClrVersion = new Version(1, 1, 4322);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case 2:
case 3:
ClrVersion = new Version(2, 0, 50727);
break;
case 4:
ClrVersion = new Version(4, 0, 30319);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
}
}
private static void ThrowInvalidFrameworkVersion(Version version)
{
throw new ArgumentException("Unknown framework version " + version, nameof(version));
}
private void InitFromClrVersion(Version version)
{
FrameworkVersion = new Version(version.Major, version.Minor);
ClrVersion = version;
if (Runtime == RuntimeType.Mono && version.Major == 1)
FrameworkVersion = new Version(1, 0);
if (Runtime == RuntimeType.Net && version.Major == 4 && version.Minor == 5)
ClrVersion = new Version(4, 0, 30319);
if (Runtime == RuntimeType.NetCore)
ClrVersion = new Version(4, 0, 30319);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
return currentFramework.Value;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime { get; }
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion { get; private set; }
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion { get; private set; }
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return ClrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphenated RuntimeType-Version or
/// a Version prefixed by 'versionString'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split('-');
if (parts.Length == 2)
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (AllowAnyVersion)
{
return Runtime.ToString().ToLower();
}
else
{
string vstring = FrameworkVersion.ToString();
if (Runtime == RuntimeType.Any)
return "v" + vstring;
else
return Runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& Runtime != target.Runtime)
return false;
if (AllowAnyVersion || target.AllowAnyVersion)
return true;
if (!VersionsMatch(ClrVersion, target.ClrVersion))
return false;
if (FrameworkVersion.Major > target.FrameworkVersion.Major)
return true;
return FrameworkVersion.Major == target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsNetCore()
{
#if NETSTANDARD2_0
// Mono versions will throw a TypeLoadException when attempting to run the internal method, so we wrap it in a try/catch
// block to stop any inlining in release builds and check whether the type exists
Type runtimeInfoType = Type.GetType("System.Runtime.InteropServices.RuntimeInformation,System.Runtime.InteropServices.RuntimeInformation", false);
if (runtimeInfoType != null)
{
try
{
return IsNetCore_Internal();
}
catch (TypeLoadException) { }
}
#endif
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool IsNetCore_Internal()
{
#if NETSTANDARD2_0
// Mono versions will throw a TypeLoadException when attempting to run any method that uses RuntimeInformation
// so we wrap it in a try/catch block in IsNetCore to catch it in case it ever gets this far
if (System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase))
{
return true;
}
#endif
return false;
}
private static bool IsRuntimeTypeName(string name)
{
return Enum.GetNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() );
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version;
else
return runtime + " " + version;
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#endregion
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>
/// CA1303: Do not pass literals as localized parameters
/// A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable.
/// This warning is raised when a literal string is passed as a value to a parameter or property and one or more of the following cases is true:
/// 1. The LocalizableAttribute attribute of the parameter or property is set to true.
/// 2. The parameter or property name contains "Text", "Message", or "Caption".
/// 3. The name of the string parameter that is passed to a Console.Write or Console.WriteLine method is either "value" or "format".
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotPassLiteralsAsLocalizedParameters : DiagnosticAnalyzer
{
internal const string RuleId = "CA1303";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotPassLiteralsAsLocalizedParametersTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotPassLiteralsAsLocalizedParametersMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotPassLiteralsAsLocalizedParametersDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.Globalization,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
INamedTypeSymbol? localizableStateAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelLocalizableAttribute);
INamedTypeSymbol? conditionalAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute);
INamedTypeSymbol? systemConsoleSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole);
ImmutableHashSet<INamedTypeSymbol> typesToIgnore = GetTypesToIgnore(compilationContext.Compilation);
compilationContext.RegisterOperationBlockStartAction(operationBlockStartContext =>
{
if (!(operationBlockStartContext.OwningSymbol is IMethodSymbol containingMethod) ||
containingMethod.IsConfiguredToSkipAnalysis(operationBlockStartContext.Options,
Rule, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken))
{
return;
}
Lazy<DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>?> lazyValueContentResult = new Lazy<DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>?>(
valueFactory: ComputeValueContentAnalysisResult, isThreadSafe: false);
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var argument = (IArgumentOperation)operationContext.Operation;
IMethodSymbol? targetMethod = null;
switch (argument.Parent)
{
case IInvocationOperation invocation:
targetMethod = invocation.TargetMethod;
break;
case IObjectCreationOperation objectCreation:
targetMethod = objectCreation.Constructor;
break;
}
if (ShouldAnalyze(targetMethod))
{
AnalyzeArgument(argument.Parameter, containingPropertySymbol: null, operation: argument, reportDiagnostic: operationContext.ReportDiagnostic, GetUseNamingHeuristicOption(operationContext));
}
}, OperationKind.Argument);
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var propertyReference = (IPropertyReferenceOperation)operationContext.Operation;
if (propertyReference.Parent is IAssignmentOperation assignment &&
assignment.Target == propertyReference &&
!propertyReference.Property.IsIndexer &&
propertyReference.Property.SetMethod?.Parameters.Length == 1 &&
ShouldAnalyze(propertyReference.Property))
{
IParameterSymbol valueSetterParam = propertyReference.Property.SetMethod.Parameters[0];
AnalyzeArgument(valueSetterParam, propertyReference.Property, assignment, operationContext.ReportDiagnostic, GetUseNamingHeuristicOption(operationContext));
}
}, OperationKind.PropertyReference);
return;
// Local functions
bool ShouldAnalyze(ISymbol? symbol)
=> symbol != null && !symbol.IsConfiguredToSkipAnalysis(operationBlockStartContext.OwningSymbol, operationBlockStartContext.Options, Rule, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken);
static bool GetUseNamingHeuristicOption(OperationAnalysisContext operationContext)
=> operationContext.Options.GetBoolOptionValue(EditorConfigOptionNames.UseNamingHeuristic, Rule,
operationContext.Operation.Syntax.SyntaxTree, operationContext.Compilation, defaultValue: false, operationContext.CancellationToken);
void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol? containingPropertySymbol, IOperation operation, Action<Diagnostic> reportDiagnostic, bool useNamingHeuristic)
{
if (ShouldBeLocalized(parameter.OriginalDefinition, containingPropertySymbol?.OriginalDefinition, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore, useNamingHeuristic) &&
lazyValueContentResult.Value != null)
{
ValueContentAbstractValue stringContentValue = lazyValueContentResult.Value[operation.Kind, operation.Syntax];
if (stringContentValue.IsLiteralState)
{
Debug.Assert(!stringContentValue.LiteralValues.IsEmpty);
if (stringContentValue.LiteralValues.Any(l => !(l is string)))
{
return;
}
var stringLiteralValues = stringContentValue.LiteralValues.Cast<string?>();
// FxCop compat: Do not fire if the literal value came from a default parameter value
if (stringContentValue.LiteralValues.Count == 1 &&
parameter.IsOptional &&
parameter.ExplicitDefaultValue is string defaultValue &&
defaultValue == stringLiteralValues.Single())
{
return;
}
// FxCop compat: Do not fire if none of the string literals have any non-control character.
if (!LiteralValuesHaveNonControlCharacters(stringLiteralValues))
{
return;
}
// FxCop compat: Filter out xml string literals.
IEnumerable<string> filteredStrings = stringLiteralValues.Where(literal => literal != null && !LooksLikeXmlTag(literal))!;
if (filteredStrings.Any())
{
// Method '{0}' passes a literal string as parameter '{1}' of a call to '{2}'. Retrieve the following string(s) from a resource table instead: "{3}".
var arg1 = containingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
var arg2 = parameter.Name;
var arg3 = parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
var arg4 = FormatLiteralValues(filteredStrings);
var diagnostic = operation.CreateDiagnostic(Rule, arg1, arg2, arg3, arg4);
reportDiagnostic(diagnostic);
}
}
}
}
DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>? ComputeValueContentAnalysisResult()
{
var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph();
if (cfg != null)
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationBlockStartContext.Compilation);
return ValueContentAnalysis.TryGetOrComputeResult(cfg, containingMethod, wellKnownTypeProvider,
operationBlockStartContext.Options, Rule, PointsToAnalysisKind.PartialWithoutTrackingFieldsAndProperties, operationBlockStartContext.CancellationToken);
}
return null;
}
});
});
}
private static ImmutableHashSet<INamedTypeSymbol> GetTypesToIgnore(Compilation compilation)
{
var builder = PooledHashSet<INamedTypeSymbol>.GetInstance();
var xmlWriter = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlWriter);
if (xmlWriter != null)
{
builder.Add(xmlWriter);
}
var webUILiteralControl = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUILiteralControl);
if (webUILiteralControl != null)
{
builder.Add(webUILiteralControl);
}
var unitTestingAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert);
if (unitTestingAssert != null)
{
builder.Add(unitTestingAssert);
}
var unitTestingCollectionAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert);
if (unitTestingCollectionAssert != null)
{
builder.Add(unitTestingCollectionAssert);
}
var unitTestingCollectionStringAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert);
if (unitTestingCollectionStringAssert != null)
{
builder.Add(unitTestingCollectionStringAssert);
}
return builder.ToImmutableAndFree();
}
private static bool ShouldBeLocalized(
IParameterSymbol parameterSymbol,
IPropertySymbol? containingPropertySymbol,
INamedTypeSymbol? localizableStateAttributeSymbol,
INamedTypeSymbol? conditionalAttributeSymbol,
INamedTypeSymbol? systemConsoleSymbol,
ImmutableHashSet<INamedTypeSymbol> typesToIgnore,
bool useNamingHeuristic)
{
Debug.Assert(parameterSymbol.ContainingSymbol.Kind == SymbolKind.Method);
if (parameterSymbol.Type.SpecialType != SpecialType.System_String)
{
return false;
}
// Verify LocalizableAttributeState
if (localizableStateAttributeSymbol != null)
{
LocalizableAttributeState localizableAttributeState = GetLocalizableAttributeState(parameterSymbol, localizableStateAttributeSymbol);
switch (localizableAttributeState)
{
case LocalizableAttributeState.False:
return false;
case LocalizableAttributeState.True:
return true;
default:
break;
}
}
// FxCop compat checks.
if (typesToIgnore.Contains(parameterSymbol.ContainingType) ||
parameterSymbol.ContainingSymbol.HasAttribute(conditionalAttributeSymbol))
{
return false;
}
// FxCop compat: For overrides, check for localizability of the corresponding parameter in the overridden method.
var method = (IMethodSymbol)parameterSymbol.ContainingSymbol;
if (method.IsOverride &&
method.OverriddenMethod?.Parameters.Length == method.Parameters.Length)
{
int parameterIndex = method.GetParameterIndex(parameterSymbol);
IParameterSymbol overridenParameter = method.OverriddenMethod.Parameters[parameterIndex];
if (Equals(overridenParameter.Type, parameterSymbol.Type))
{
return ShouldBeLocalized(overridenParameter, containingPropertySymbol, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore, useNamingHeuristic);
}
}
if (useNamingHeuristic)
{
if (IsLocalizableByNameHeuristic(parameterSymbol) ||
containingPropertySymbol != null && IsLocalizableByNameHeuristic(containingPropertySymbol))
{
return true;
}
}
if (method.ContainingType.Equals(systemConsoleSymbol) &&
(method.Name.Equals("Write", StringComparison.Ordinal) ||
method.Name.Equals("WriteLine", StringComparison.Ordinal)) &&
(parameterSymbol.Name.Equals("format", StringComparison.OrdinalIgnoreCase) ||
parameterSymbol.Name.Equals("value", StringComparison.OrdinalIgnoreCase)))
{
return true;
}
return false;
// FxCop compat: If a localizable attribute isn't defined then fall back to name heuristics.
static bool IsLocalizableByNameHeuristic(ISymbol symbol) =>
symbol.Name.Equals("message", StringComparison.OrdinalIgnoreCase) ||
symbol.Name.Equals("text", StringComparison.OrdinalIgnoreCase) ||
symbol.Name.Equals("caption", StringComparison.OrdinalIgnoreCase);
}
private static LocalizableAttributeState GetLocalizableAttributeState(ISymbol symbol, INamedTypeSymbol localizableAttributeTypeSymbol)
{
if (symbol == null)
{
return LocalizableAttributeState.Undefined;
}
LocalizableAttributeState localizedState = GetLocalizableAttributeStateCore(symbol.GetAttributes(), localizableAttributeTypeSymbol);
if (localizedState != LocalizableAttributeState.Undefined)
{
return localizedState;
}
ISymbol containingSymbol = (symbol as IMethodSymbol)?.AssociatedSymbol is IPropertySymbol propertySymbol ? propertySymbol : symbol.ContainingSymbol;
return GetLocalizableAttributeState(containingSymbol, localizableAttributeTypeSymbol);
}
private static LocalizableAttributeState GetLocalizableAttributeStateCore(ImmutableArray<AttributeData> attributeList, INamedTypeSymbol localizableAttributeTypeSymbol)
{
var localizableAttribute = attributeList.FirstOrDefault(attr => localizableAttributeTypeSymbol.Equals(attr.AttributeClass));
if (localizableAttribute != null &&
localizableAttribute.AttributeConstructor.Parameters.Length == 1 &&
localizableAttribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Boolean &&
localizableAttribute.ConstructorArguments.Length == 1 &&
localizableAttribute.ConstructorArguments[0].Kind == TypedConstantKind.Primitive &&
localizableAttribute.ConstructorArguments[0].Value is bool isLocalizable)
{
return isLocalizable ? LocalizableAttributeState.True : LocalizableAttributeState.False;
}
return LocalizableAttributeState.Undefined;
}
private static string FormatLiteralValues(IEnumerable<string> literalValues)
{
var literals = new StringBuilder();
foreach (string literal in literalValues.Order())
{
// sanitize the literal to ensure it's not multiline
// replace any newline characters with a space
var sanitizedLiteral = literal.Replace(Environment.NewLine, " ");
sanitizedLiteral = sanitizedLiteral.Replace((char)13, ' ');
sanitizedLiteral = sanitizedLiteral.Replace((char)10, ' ');
if (literals.Length > 0)
{
literals.Append(", ");
}
literals.Append(sanitizedLiteral);
}
return literals.ToString();
}
/// <summary>
/// Returns true if the given string looks like an XML/HTML tag
/// </summary>
private static bool LooksLikeXmlTag(string literal)
{
// Call the trim function to remove any spaces around the beginning and end of the string so we can more accurately detect
// XML strings
string trimmedLiteral = literal.Trim();
return trimmedLiteral.Length > 2 && trimmedLiteral[0] == '<' && trimmedLiteral[^1] == '>';
}
/// <summary>
/// Returns true if any character in literalValues is not a control character
/// </summary>
private static bool LiteralValuesHaveNonControlCharacters(IEnumerable<string?> literalValues)
{
foreach (string? literal in literalValues)
{
if (literal == null)
{
continue;
}
foreach (char ch in literal)
{
if (!char.IsControl(ch))
{
return true;
}
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePartDefinition : ComposablePartDefinition, ICompositionElement
{
private readonly IReflectionPartCreationInfo _creationInfo;
private volatile ImportDefinition[] _imports;
private volatile ExportDefinition[] _exports;
private volatile IDictionary<string, object> _metadata;
private volatile ConstructorInfo _constructor;
private object _lock = new object();
public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
{
Assumes.NotNull(creationInfo);
_creationInfo = creationInfo;
}
public Type GetPartType()
{
return _creationInfo.GetPartType();
}
public Lazy<Type> GetLazyPartType()
{
return _creationInfo.GetLazyPartType();
}
public ConstructorInfo GetConstructor()
{
if (_constructor == null)
{
ConstructorInfo constructor = _creationInfo.GetConstructor();
lock (_lock)
{
if (_constructor == null)
{
_constructor = constructor;
}
}
}
return _constructor;
}
private ExportDefinition[] ExportDefinitionsInternal
{
get
{
if (_exports == null)
{
ExportDefinition[] exports = _creationInfo.GetExports().ToArray();
lock (_lock)
{
if (_exports == null)
{
_exports = exports;
}
}
}
return _exports;
}
}
public override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
return ExportDefinitionsInternal;
}
}
public override IEnumerable<ImportDefinition> ImportDefinitions
{
get
{
if (_imports == null)
{
ImportDefinition[] imports = _creationInfo.GetImports().ToArray();
lock (_lock)
{
if (_imports == null)
{
_imports = imports;
}
}
}
return _imports;
}
}
public override IDictionary<string, object> Metadata
{
get
{
if (_metadata == null)
{
IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly();
lock (_lock)
{
if (_metadata == null)
{
_metadata = metadata;
}
}
}
return _metadata;
}
}
internal bool IsDisposalRequired
{
get
{
return _creationInfo.IsDisposalRequired;
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public override ComposablePart CreatePart()
{
if (IsDisposalRequired)
{
return new DisposableReflectionComposablePart(this);
}
else
{
return new ReflectionComposablePart(this);
}
}
internal override ComposablePartDefinition GetGenericPartDefinition()
{
GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo;
if (genericCreationInfo != null)
{
return genericCreationInfo.OriginalPart;
}
return null;
}
internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
if (this.IsGeneric())
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(CompositionConstants.GenericParametersMetadataName) : null;
// if and only if generic parameters have been supplied can we attempt to "close" the generic
if (genericParameters != null)
{
Type[] genericTypeParameters = null;
// we only understand types
if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters))
{
HashSet<ComposablePartDefinition> candidates = null;
ComposablePartDefinition candidatePart = null;
ComposablePartDefinition previousPart = null;
// go through all orders of generic parameters that part exports allows
foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters))
{
if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart))
{
bool alreadyProcessed = false;
if (candidates == null)
{
if (previousPart != null)
{
if (candidatePart.Equals(previousPart))
{
alreadyProcessed = true;
}
else
{
candidates = new HashSet<ComposablePartDefinition>();
candidates.Add(previousPart);
candidates.Add(candidatePart);
}
}
else
{
previousPart = candidatePart;
}
}
else
{
if (candidates.Contains(candidatePart))
{
alreadyProcessed = true;
}
else
{
candidates.Add(candidatePart);
}
}
if (!alreadyProcessed)
{
Tuple<ComposablePartDefinition, ExportDefinition> candidateSingleMatch;
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches;
if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches))
{
exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches);
}
}
}
}
}
}
if (exports != null)
{
multipleMatches = exports;
return true;
}
else
{
return false;
}
}
else
{
return TryGetNonGenericExports(definition, out singleMatch, out multipleMatches);
}
}
// Optimised for local as array case
private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
bool matchesFound = false;
foreach (var export in ExportDefinitionsInternal)
{
if (definition.IsConstraintSatisfiedBy(export))
{
matchesFound = true;
if (singleExport == null)
{
singleExport = new Tuple<ComposablePartDefinition, ExportDefinition>(this, export);
}
else
{
if (multipleExports == null)
{
multipleExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
multipleExports.Add(singleExport);
}
multipleExports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(this, export));
}
}
}
if (!matchesFound)
{
return false;
}
if (multipleExports != null)
{
multipleMatches = multipleExports;
}
else
{
singleMatch = singleExport;
}
return true;
}
private IEnumerable<Type[]> GetCandidateParameters(Type[] genericParameters)
{
// we iterate over all exports and find only generic ones. Assuming the arity matches, we reorder the original parameters
foreach (ExportDefinition export in ExportDefinitionsInternal)
{
var genericParametersOrder = export.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName);
if ((genericParametersOrder != null) && (genericParametersOrder.Length == genericParameters.Length))
{
yield return GenericServices.Reorder(genericParameters, genericParametersOrder);
}
}
}
private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
{
genericTypeParameters = genericParameters as Type[];
if (genericTypeParameters == null)
{
object[] genericParametersAsArray = genericParameters.AsArray();
genericTypeParameters = new Type[genericParametersAsArray.Length];
for (int i = 0; i < genericParametersAsArray.Length; i++)
{
genericTypeParameters[i] = genericParametersAsArray[i] as Type;
if (genericTypeParameters[i] == null)
{
return false;
}
}
}
return true;
}
internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition)
{
genericPartDefinition = null;
if (!GenericSpecializationPartCreationInfo.CanSpecialize(Metadata, genericTypeParameters))
{
return false;
}
genericPartDefinition = new ReflectionComposablePartDefinition(new GenericSpecializationPartCreationInfo(_creationInfo, this, genericTypeParameters));
return true;
}
string ICompositionElement.DisplayName
{
get { return _creationInfo.DisplayName; }
}
ICompositionElement ICompositionElement.Origin
{
get { return _creationInfo.Origin; }
}
public override string ToString()
{
return _creationInfo.DisplayName;
}
public override bool Equals(object obj)
{
if (_creationInfo.IsIdentityComparison)
{
return object.ReferenceEquals(this, obj);
}
else
{
ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition;
if (that == null)
{
return false;
}
return _creationInfo.Equals(that._creationInfo);
}
}
public override int GetHashCode()
{
if (_creationInfo.IsIdentityComparison)
{
return base.GetHashCode();
}
else
{
return _creationInfo.GetHashCode();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CommandSenderApi.Areas.HelpPage.ModelDescriptions;
using CommandSenderApi.Areas.HelpPage.Models;
namespace CommandSenderApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// System.Collections.ICollection.CopyTo(System.Array,System.Int32)
/// </summary>
public class ICollectionCopyTo
{
const int Count = 1000;
static Random m_rand = new Random(-55);
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = new byte[Count];
TestLibrary.TestFramework.BeginScenario("PosTest1: Using Arraylist which implemented the CopyTo method in ICollection ");
try
{
((ICollection)arrayList).CopyTo(array, 0);
for (int i = 0; i < Count; i++)
{
if ((byte)(arrayList[i]) != array[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
int index =m_rand.Next(1,1000);
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = new byte[Count+index];
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the start index is not zero...");
try
{
((ICollection)arrayList).CopyTo(array, index);
for (int i = 0; i < Count; i++)
{
if ((byte)(arrayList[i]) != array[i+index])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: Verify the array is a null reference");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected when array is a null reference");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
byte[] array = new byte[Count];
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest2: Verify the index is less than zero");
try
{
index = -index;
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected when index is "+index.ToString());
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
byte[] array = new byte[Count];
int index = array.Length;
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest3: Verify the index is equal the length of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected when index equal length of array");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
byte[] array = new byte[Count];
int index = array.Length +m_rand.Next(1, 1000);
List<object> arrayList = new List<object>();
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest4: Verify the index is greater than the length of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("107", "The ArgumentException was not thrown as expected. \n index is " + index.ToString() + "\n array length is " + array.Length.ToString());
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
Array array = new byte[Count,Count];
int index = m_rand.Next(1, 1000);
byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest5: Verify the array is multidimensional");
try
{
((ICollection)arrayList).CopyTo(array, array.Length);
TestLibrary.TestFramework.LogError("109", "The ArgumentException was not thrown as expected when the array is multidimensional");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
int count = Count + m_rand.Next(1, 1000);
byte[] array = new byte[Count];
int index = m_rand.Next(1,1000);
byte[] byteValue = new byte[count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest6: The number of elements in the ICollection is greater than the available space from index to the end of array");
try
{
((ICollection)arrayList).CopyTo(array, array.Length);
TestLibrary.TestFramework.LogError("111", "The ArgumentException was not thrown as expecteds");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
byte[] array = new byte[Count+index];
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(new object());
}
TestLibrary.TestFramework.BeginScenario("NegTest7: Verify the type of the ICollection cannot be cast automatically to the type of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("113", "The InvalidCastException was not thrown as expected");
retVal = false;
}
catch (InvalidCastException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ICollectionCopyTo test = new ICollectionCopyTo();
TestLibrary.TestFramework.BeginTestCase("Test for method:System.Collections.ICollection.CopyTo(System.Array,System.Int32)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001
//
// File: SynchronizingStream.cs
//
// Description: Stream that locks on given syncRoot before entering any public API's.
//
// History: 01/20/06 - brucemac - created
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
namespace MS.Internal.IO.Packaging
{
/// <summary>
/// Wrap returned stream to protect non-thread-safe API's from race conditions
/// </summary>
internal class SynchronizingStream : Stream
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Serializes access by locking on the given object
/// </summary>
/// <param name="stream">stream to read from (baseStream)</param>
/// <param name="syncRoot">object to lock on</param>
internal SynchronizingStream(Stream stream, Object syncRoot)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (syncRoot == null)
throw new ArgumentNullException("syncRoot");
_baseStream = stream;
_syncRoot = syncRoot;
}
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
/// <summary>
/// Return the bytes requested
/// </summary>
/// <param name="buffer">destination buffer</param>
/// <param name="offset">offset to write into that buffer</param>
/// <param name="count">how many bytes requested</param>
/// <returns>how many bytes were written into buffer</returns>
public override int Read(byte[] buffer, int offset, int count)
{
lock (_syncRoot)
{
CheckDisposed();
return (_baseStream.Read(buffer, offset, count));
}
}
/// <summary>
/// Read a single byte
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
lock (_syncRoot)
{
CheckDisposed();
return (_baseStream.ReadByte());
}
}
/// <summary>
/// Write a single byte
/// </summary>
/// <param name="b">byte to write</param>
public override void WriteByte(byte b)
{
lock (_syncRoot)
{
CheckDisposed();
_baseStream.WriteByte(b);
}
}
/// <summary>
/// Seek
/// </summary>
/// <param name="offset">only zero is supported</param>
/// <param name="origin">only SeekOrigin.Begin is supported</param>
/// <returns>zero</returns>
public override long Seek(long offset, SeekOrigin origin)
{
lock (_syncRoot)
{
CheckDisposed();
return _baseStream.Seek(offset, origin);
}
}
/// <summary>
/// SetLength
/// </summary>
/// <exception cref="NotSupportedException">not supported</exception>
public override void SetLength(long newLength)
{
lock (_syncRoot)
{
CheckDisposed();
_baseStream.SetLength(newLength);
}
}
/// <summary>
/// Write
/// </summary>
/// <exception cref="NotSupportedException">not supported</exception>
public override void Write(byte[] buf, int offset, int count)
{
lock (_syncRoot)
{
CheckDisposed();
_baseStream.Write(buf, offset, count);
}
}
/// <summary>
/// Flush
/// </summary>
/// <exception cref="NotSupportedException">not supported</exception>
public override void Flush()
{
lock (_syncRoot)
{
CheckDisposed();
_baseStream.Flush();
}
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/// <summary>
/// Is stream readable?
/// </summary>
public override bool CanRead
{
get
{
lock (_syncRoot)
{
return ((_baseStream != null) && _baseStream.CanRead);
}
}
}
/// <summary>
/// Is stream seekable?
/// </summary>
/// <remarks>We MUST support seek as this is used to implement ILockBytes.ReadAt()</remarks>
public override bool CanSeek
{
get
{
lock (_syncRoot)
{
return ((_baseStream != null) && _baseStream.CanSeek);
}
}
}
/// <summary>
/// Is stream writeable?
/// </summary>
public override bool CanWrite
{
get
{
lock (_syncRoot)
{
return ((_baseStream != null) && _baseStream.CanWrite);
}
}
}
/// <summary>
/// Logical byte position in this stream
/// </summary>
public override long Position
{
get
{
lock (_syncRoot)
{
CheckDisposed();
return _baseStream.Position;
}
}
set
{
lock (_syncRoot)
{
CheckDisposed();
_baseStream.Position = value;
}
}
}
/// <summary>
/// Length
/// </summary>
public override long Length
{
get
{
lock (_syncRoot)
{
CheckDisposed();
return _baseStream.Length;
}
}
}
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
protected override void Dispose(bool disposing)
{
lock (_syncRoot)
{
try
{
if (disposing && (_baseStream != null))
{
// close the underlying Stream
_baseStream.Close();
// NOTE: We cannot set _syncRoot to null because it is used
// on entry to every public method and property.
}
}
finally
{
base.Dispose(disposing);
_baseStream = null;
}
}
}
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
/// <summary>
/// CheckDisposed
/// </summary>
/// <remarks>Pre-condition that lock has been acquired.</remarks>
private void CheckDisposed()
{
if (_baseStream == null)
throw new ObjectDisposedException("Stream");
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
private Stream _baseStream; // stream we are wrapping
private Object _syncRoot; // object to lock on
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.